From d9e9bee7c0a13addb267b0a540804a6cf3f98c45 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:24:02 -0700 Subject: [PATCH 001/585] plan(M5): carry the M5 plan pair and its ADRs onto the tagged main The m5 branch was drafted 237 commits ago under the retired gate structure. It is rebuilt on main at v0.1.0 with the planning documents carried by content: the M5 plan pair, ADRs 0031, 0032 and 0033 with their index rows, the plan indexed and registered as Open with the derived capsule and README summary the status check requires, and the outcome the maintainer set on 2026-09-19 (the credential handoff over the bootstrap channel) intact. The gate contract, opening probe and gate scripts of the old lineage are not carried: the milestone guide replaces them, and the plan pair is refreshed onto it next. The old lineage stays reachable at tag m5-planning-lineage (6ee40db2). --- README.md | 2 +- docs/README.md | 4 + ...store-selection-and-migration-technical.md | 188 +++++++++++ ...mon-grade-store-selection-and-migration.md | 106 +++++++ ...tachment-residency-and-replay-technical.md | 191 ++++++++++++ ...-daemon-attachment-residency-and-replay.md | 101 ++++++ ...controller-lease-and-takeover-technical.md | 166 ++++++++++ ...aboration-controller-lease-and-takeover.md | 90 ++++++ docs/adr/README.md | 15 + docs/plans/M5-technical.md | 293 ++++++++++++++++++ docs/plans/M5.md | 272 ++++++++++++++++ docs/plans/README.md | 11 +- 12 files changed, 1433 insertions(+), 6 deletions(-) create mode 100644 docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md create mode 100644 docs/adr/0031-daemon-grade-store-selection-and-migration.md create mode 100644 docs/adr/0032-daemon-attachment-residency-and-replay-technical.md create mode 100644 docs/adr/0032-daemon-attachment-residency-and-replay.md create mode 100644 docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md create mode 100644 docs/adr/0033-collaboration-controller-lease-and-takeover.md create mode 100644 docs/plans/M5-technical.md create mode 100644 docs/plans/M5.md diff --git a/README.md b/README.md index 50bf0a114..dae675929 100644 --- a/README.md +++ b/README.md @@ -25,7 +25,7 @@ while the session lives; a session "brain" can coordinate local or remote ## Where Things Stand -**Revision status:** Closed milestone product baseline; no milestone is active; no next candidate is recorded. +**Revision status:** Closed milestone product baseline; active milestone `M5` is open; no next candidate is recorded. [Canonical milestone status and plan records](docs/plans/) diff --git a/docs/README.md b/docs/README.md index 6bec5d779..b17eb5d11 100644 --- a/docs/README.md +++ b/docs/README.md @@ -76,6 +76,9 @@ pairing, link, review, code-documentation, and enforcement contracts. | 0028 — bounded artifact retrieval | [Decision](adr/0028-bounded-artifact-retrieval.md#concept) | [Technical depth](adr/0028-bounded-artifact-retrieval-technical.md#technical-depth) | | 0029 — bounded provider failure diagnostics | [Decision](adr/0029-bounded-provider-failure-diagnostics.md#concept) | [Technical depth](adr/0029-bounded-provider-failure-diagnostics-technical.md#technical-depth) | | 0030 — observability: tracing and telemetry | [Decision](adr/0030-observability-tracing-and-telemetry.md#concept) | [Technical depth](adr/0030-observability-tracing-and-telemetry-technical.md#technical-depth) | +| 0031 — daemon-grade store selection and migration | [Decision](adr/0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](adr/0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | +| 0032 — daemon attachment residency and replay | [Decision](adr/0032-daemon-attachment-residency-and-replay.md#concept) | [Technical depth](adr/0032-daemon-attachment-residency-and-replay-technical.md#technical-depth) | +| 0033 — collaboration: controller lease and takeover | [Decision](adr/0033-collaboration-controller-lease-and-takeover.md#concept) | [Technical depth](adr/0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth) | An ADR pair is one decision. Its status and governance record live in the Concept file and bind both files when accepted. @@ -88,6 +91,7 @@ whose path or explicit fragment does not resolve. - [M3 foundations](plans/M3.md#concept) and [technical plan](plans/M3-technical.md#technical-depth) — project skills and core repairs; Closed with retained evidence in the plan. - [M4 headless external consumption](plans/M4.md#concept) and [technical plan](plans/M4-technical.md#technical-depth) — durable interactions, artifact transfers, the floor refresh, observability, and the experimental session protocol driven by an independent Node consumer in plain JavaScript; Closed, with its runs in [M4 closure runs](evidence/M4-closure-runs.md). +- [M5 durable service](plans/M5.md#concept) and [technical plan](plans/M5-technical.md#technical-depth) — daemon-owned session lifetime on the ADR-selected local store within its documented limits, generation-2-only Unix-domain-socket transport, in-memory controller lease with observers and takeover, and at-least-once replay with residency limits over M4; Open planning lookahead with a red gate. - [Development contract](../AGENTS.md) — canonical tool-neutral authority, autonomy, documentation, milestone, and enforcement rules. diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md new file mode 100644 index 000000000..5f2854dcc --- /dev/null +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -0,0 +1,188 @@ + +## Technical depth + +Concept: [Daemon-grade store selection and migration](0031-daemon-grade-store-selection-and-migration.md#concept). + + +### Contract and Evidence + +Concept: [Context and decision](0031-daemon-grade-store-selection-and-migration.md#concept-adr-0031-decision). + +### M5 selection: the local adapter and its limits + +The M5 daemon opens the state root through `loopex_store_local` exactly as +the foreground server does, and holds its writer marker from before the +socket is bound until the daemon process exits. The adapter's limits are the +daemon's limits, and every one is an existing constant or refusal of +`Loopex.Store.Local.Log`: + +- one append-only, length-prefixed, digest-checked log per state root, held + by one operating-system process through the writer marker with the + `store_writer_active` and `store_writer_unverifiable` refusals; +- a hard log capacity of 256 MiB (`@max_log_bytes`): an append that would + exceed it refuses with `store_capacity_exceeded`, and a log already larger + than the bound refuses at open with `store_log_too_large`; +- a 4 MiB frame ceiling (`@max_frame_bytes`) on any single record; +- full-history retention: no compaction, no retention cutoff, and full replay + at every open, so replay time and memory grow with the root's history until + the root is retired; +- session discovery through the existing session directory beside the log, + which lists every session the root knows. + +Root retirement is an operator procedure, not a store operation: stop the +daemon so the marker is released; move the root directory aside under a name +of the operator's choosing; start the daemon on a fresh root with the same +placement identity source. A session in a retired root is resumed only by +stopping the daemon and reopening that root, with the daemon or the +foreground server. The daemon's operator documentation states the capacity, +the refusal reason, the frame ceiling, full retention and this procedure. + +Evidence for the M5 selection lives in the M5 gate, not here: a root driven +to the capacity ceiling refuses further mutation with the store's own reason +while observers stay attached and an orderly stop still succeeds, and after +that stop the foreground server reopens the same root. No new conformance +evidence is required, because the adapter and its suites are unchanged. + +### Boundary + +`loopex_store_daemon`, the successor's adapter, implements the same private +port set `Loopex.Store` already fixes for the local adapter: `transact/2`, +`transaction_status/4`, `runtime_command/2`, `ownership_head/3`, +`load_records/4` and `load_events/4`, plus the snapshot store and load calls +the port declares. It changes no callback arity or result shape; ADR 0006 +owner epochs and incarnation identities remain the commit-authority fence and +the writer marker remains physical writer exclusion. The public protocol, the +embedded API and every public event are unchanged by the adapter choice. +Neither core nor `loopex_store_local` depends on the adapter, and the +daemon's controller lease stays in daemon memory under ADR 0033; no adapter +stores a lease. + +### Candidate one: BEAM-native segmented log + +- One root directory per state root with a `manifest` file naming the format + version `loopex_store_daemon_v1`, the placement identity the root was + created under, and the migration ledger. +- One append-only frame log per session, reusing the local adapter's + length-prefixed, digest-checked frame and its sync-after-commit rule, so a + torn tail is detected and truncated at the last complete frame exactly as + today. +- Private and public snapshots written every N private records or M seconds, + whichever first, each naming the journal version and public sequence it + covers; open replays only records after the newest verified snapshot, so + replay is bounded by the snapshot interval rather than session age. +- A session index file listing session identity, source and fork lineage, + genesis and tombstone state and the last known public sequence, rebuilt from + the logs when absent or inconsistent rather than trusted. +- The root-scoped daemon writer marker held for the whole root, using the + local adapter's liveness-probe discipline and the same + `store_writer_active` and `store_writer_unverifiable` refusals. + +### Candidate two: SQLite through a NIF binding + +One database per state root with tables for sessions, private records, +public outbox rows, snapshots and idempotency; transactions through the +engine's journal; the same port mapping. Both candidates use a root manifest +with format version, placement identity and migration ledger; SQLite keeps its +session index as database lookup state rather than a separate index file. It +is evaluated on the same suite with three additional obligations: the NIF's +failure containment (a crash or +a blocked scheduler is a VM-level risk the native candidate does not carry), +its packaging (a compiled dependency joins the version train and the release +archive), and equivalent crash and corruption outcomes under its own journal +and database file format. + +### Selection experiment and evidence + +After M5 closes and the successor milestone's refreshed opening gate is +established red on that closed base, both candidates run in separate +isolated, disposable contract branches and task roots. The experiments may +build only the adapter slices and fixtures necessary to measure this +decision; they do not enter that milestone's Open candidate, integrate to +`main`, become accepted product bytes, or claim an inherited-gate result for +the milestone branch. The gate-first checkpoint permits bounded contract +experiments only after the one-lookahead planning restriction ends with M5 +closure. Both run: + +- the shared store conformance suite that the local and in-memory adapters + already pass, unchanged; +- common semantic fault cut points: kill before durable commit, after durable + commit but before acknowledgement, and during snapshot or checkpoint write; + corrupt or incomplete durable bytes, missing or corrupt derived lookup state, + and a marker left by a dead writer. Each candidate uses physical injections + appropriate to its representation and proves the same Store-level recovery + or refusal outcomes. The native candidate additionally runs literal torn + last frame, corrupt middle frame, and missing or corrupt session-index + fixtures; SQLite runs its corresponding database and journal corruption and + index-rebuild fixtures. The decision packet records the exact injection and + observed outcome for each candidate and cut point; +- commit-ambiguity resolution: a `transact` whose acknowledgement was lost is + resolved by `transaction_status` to exactly one outcome; +- bounded replay: open time and memory grow with the snapshot interval, not + with session length, measured on a session with at least one hundred + thousand records; +- backup and restore: a quiescent copy reopens with every session identity and + public sequence intact and the integrity check clean. + +Record each experiment's exact candidate SHA, commands, platform and measured +results in the decision packet. Revise this still-Proposed pair to name the +winner, both experiment SHAs, its evidence and any packaging cost; +independently review that candidate before the maintainer accepts it. +Selection does not itself accept the successor milestone. Product +implementation of the adapter starts only after this revised pair and that +milestone's plan are accepted. + +### Migration + +Supported pair: local adapter format `loopex_store_writer_v2` log, as the M4 +foreground server, the reference CLI and the M5 daemon write it, to +`loopex_store_daemon_v1` root. The import reads the original log through the +local adapter's own reader, writes each session and derived lookup state through +the selected adapter into a new root, records `started`, +`session imported`, `verified` and `completed` +in the manifest's migration ledger with the source log digest, and refuses to +serve until `completed` is present. Reopen after interruption reads the +ledger: a root without `completed` is either resumed from the last recorded +session or discarded and restarted, both without touching the source log. The +original log is never modified, moved or deleted by the import. + +Every previous local-reader binary, the M5 daemon release included, treats +the daemon-grade root directory as an invalid store file and returns its +existing `store_file_invalid` reason. It cannot name `loopex_store_daemon_v1` +or advertise a maximum format it never implemented. The successor daemon +reader validates the root manifest version and refuses unknown versions +explicitly; it is the oldest reader of this new root. A daemon binary opening +a local log serves it only through explicit import; it never upgrades in +place. + +### Evidence and alternatives + +Successor tests cover forward migration of a genuine local session log with +identical replay afterwards, interruption at each ledger step with detection +on reopen, safe refusal by the exact previous binary with its actual reason, +and backup and restore. Mnesia and DETS were rejected: DETS carries a +two-gigabyte table limit and no tail-repair story, and Mnesia's schema is +VM-global state that contradicts the runtime-instance rule. A hosted +PostgreSQL adapter remains a later choice under the same ports and is not +evaluated here. Deferring this ADR entirely from M5 was rejected on +2026-09-14: the daemon still needs a recorded selection, and the local +adapter's ceilings are a fact the operator must be told rather than an +absence of decision. + + +### Compatibility and Rollback Mechanics + +Concept: [Consequences and rollback](0031-daemon-grade-store-selection-and-migration.md#concept-adr-0031-consequences). + +In M5 no journal format changes; the daemon, the foreground server and the +CLI reopen one another's roots, and rollback is stopping the daemon. The +private journal is a separate compatibility surface and stays experimental +in 0.x; the successor adapter adds no public event, snapshot field, wire +method or embedded function. Successor rollback is the retained original log +plus the previous binary, which is a copy back, not a reverse migration. +Backup is a quiescent copy of the root plus the adapter's integrity check; +restore reopens the copy under the same placement identity and refuses a +placement mismatch exactly as resume does today. + +Acceptance of the M5 selection binds this pair at an exact candidate under +the M5 gate; the successor selection is bound again, with its experiment +evidence, by the adopting milestone's gate. diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md new file mode 100644 index 000000000..fa4597a55 --- /dev/null +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -0,0 +1,106 @@ + +## Concept + +Technical depth: [Daemon-grade store mechanics](0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth). + +- **Status:** Proposed +- **Date:** 2026-09-14 +- **Decision owner:** Maintainer +- **Supersedes:** nothing; refines the store posture in vision §12.2 +- **Prerequisite for:** M5 acceptance, for the local-adapter selection and + its documented limits; the successor milestone that adopts the daemon-grade + adapter, for the selection experiment and migration + + +### Context and Decision + +The local Store that M1 through M4 use is one append-only framed log per +state root, replayed in full at every open, held by one operating-system +process through a writer marker, with a hard capacity, no compaction and no +session index. That is exactly right for a foreground process that owns one +session at a time and exits with it. The vision's reference daemon runs on +an ADR-selected store, and a service makes operational claims that the +bootstrap adapters were never asked to make: bounded replay, an index, a +migration pair with interrupted-migration recovery, backup and restore, and +a stated oldest binary that may reopen a migrated root. The vision freezes +the store contract, not an engine, and says adapters are selected by +evidence. + +This ADR decides two things at two times. + +**For M5, select the existing local adapter as the daemon's store.** The +daemon holds the local writer marker for its process's lifetime and inherits +the adapter's exact, documented limits: one append-only log per state root +with a hard 256 MiB capacity, a 4 MiB frame ceiling, full-history retention +with no compaction, full replay at open, and one writer per root. Reaching +capacity is a truthful refusal, never a silent loss: the adapter answers +`store_capacity_exceeded`, the daemon refuses further mutation with that +reason while observers stay attached and an orderly stop still succeeds, and +the operator retires the root by stopping the daemon, moving the root aside +and starting a fresh root. Sessions in a retired root are resumable only by +reopening that root. This is a bounded, experimental selection made on +evidence the local adapter already carries; it is not a daemon-grade store, +and the 0.2.0 daemon's operator documentation states these limits and the +retirement procedure. The maintainer chose this on 2026-09-14 over deferring +the ADR entirely: the reference daemon needs a recorded store selection even +when the selected adapter is the existing one, and documenting the ceilings +makes the durable-service claim truthful without adding an engine. + +**For the successor milestone, decide the selection procedure now and let its +evidence fix the engine before that milestone's acceptance.** The +daemon-grade store is a new adapter, `loopex_store_daemon`, behind the +unchanged private session Store ports. After M5 closes and the successor's +opening gate is refreshed red on that closed base, isolated, disposable +contract experiments on separate task roots compare a BEAM-native segmented +log and a SQLite-backed NIF adapter against the same conformance and +fault-injection suites. Neither experiment becomes product implementation, +enters that milestone's Open candidate, or integrates to `main`. This pair is +then revised to name the selected engine, both exact experiment revisions and +their measured evidence before independent review and acceptance of those +exact bytes. The current recommendation is the BEAM-native adapter because it +avoids a compiled dependency and VM-level NIF risk while reusing proven local +framing and repair; these are hypotheses to test, not a categorical veto of +SQLite. Any candidate that fails a required fault case is ineligible. + +Migration is one-way and explicit: the successor's daemon imports a local log +written by the M4 foreground server, the reference CLI or the M5 daemon into +its own root, retains the original untouched beside it as the rollback pair, +records every step so an interrupted import is detected and completed or +rolled back on the next open, and stamps the new root with a format version. +Every previous release binary must safely refuse that root with its existing +error; it cannot report a version it does not know. No in-place rewrite and +no silent upgrade on first open. + +Technical depth: [Contract and evidence](0031-daemon-grade-store-selection-and-migration-technical.md#technical-adr-0031-decision). + + +### Consequences, Compatibility and Rollback + +The daemon and its clients see the same durable session truth the embedded +API and the foreground server see; the store adapter is a host choice, not a +semantic one. In M5 the foreground server, the reference CLI and the daemon +all run on the local adapter and can reopen one another's roots. A root that +reaches the local log's capacity stops accepting mutation and is retired by +the operator; nothing already committed is lost. The private journal format +is a separate compatibility surface: adding an adapter later freezes no wire, +artifact or embedded contract, and the exact private format stays +experimental in 0.x. + +M5 rollback is stopping the daemon: the foreground server and CLI reopen the +same root under the same placement identity. Successor rollback is the +retained original local log plus the previous binary. A previous binary +cannot open the daemon-grade root; when pointed at that directory, its +existing local reader returns `store_file_invalid`, without claiming to +understand the new format. The selected successor daemon binary is the oldest +reader of the daemon-grade root. The imported original is never modified, so +restoring it is a copy, not a reverse migration. Backup is a quiescent copy +of the root verified by the adapter's own integrity check; restore reopens +that copy under the same placement identity. + +Technical depth: [Compatibility mechanics](0031-daemon-grade-store-selection-and-migration-technical.md#technical-adr-0031-compatibility). + +## Governance Record + +| Decision | Authority | Authority evidence | Bound bytes | +| --- | --- | --- | --- | +| Acceptance | — | — | — | diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md new file mode 100644 index 000000000..dfe58c141 --- /dev/null +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -0,0 +1,191 @@ + +## Technical depth + +Concept: [Daemon attachment residency and replay](0032-daemon-attachment-residency-and-replay.md#concept). + + +### Contract and Evidence + +Concept: [Context and decision](0032-daemon-attachment-residency-and-replay.md#concept-adr-0032-decision). + +### Transport + +The daemon listens on one Unix-domain socket. Its path is +`/daemon.sock` by default and may be set explicitly; a path +longer than the platform's socket-address bound (104 bytes on Darwin, 108 on +Linux) is refused at start with `socket_path_too_long` naming the bound, never +truncated. The socket file is created with owner-only permissions and the +daemon reads the connecting peer's credentials; a peer whose user identity +differs from the daemon's is closed before any frame is read. + +Startup order is fixed. The daemon first opens the state root through the +local adapter and acquires its writer marker; a daemon that does not hold the +marker refuses with the adapter's `store_writer_active` or +`store_writer_unverifiable` reason and never reads, unlinks or binds the +socket path. Only the marker holder may remove a stale `daemon.sock` left by +a dead daemon and bind a new one, so two simultaneous starts on one root +resolve at the marker, exactly one listener exists, and the loser exits +without touching the socket. If the daemon loses store ownership while +running, because its Store child exits or the marker can no longer be +proved held, it closes the listener and every connection before anything +else and then exits; no connection outlives the daemon's ownership of the +root. + +Framing, the initialize handshake, request and admission records, snapshot, +event and progress records, the frame ceiling, the strict UTF-8/LF rule and +the unknown-field rule are reused from ADR 0023 unchanged. A connection is +one attachment after `session.attach`; generation 2 permits a connection to +hold at most one attachment at a time and a client process to hold as many +connections as the residency limits admit. + +The core EventDispatcher and Control retain multiple live attachment IDs and +incarnations for one session. A new distinct attachment does not implicitly +detach another session attachment or cancel its pending read. Repetition of +the same attachment request returns its live attachment; explicit replacement +invalidates only the named prior incarnation at its last emitted cursor. +Snapshot barriers, queued durable delivery, stale-handle checks and detach +remain core operations. The daemon neither copies the snapshot into a second +fan-out owner nor reads coordinator state to repair an attachment race. + +### Queue ownership + +Two bounded stages exist per attachment, with distinct owners. The core +dispatcher owns the per-attachment event-count queue that already exists, +configured by the daemon at 1,024 events through the runtime's +`attachment_capacity`; it never holds encoded bytes. The daemon owns a +per-connection socket output buffer of encoded frames not yet written to the +socket, bounded at 4 MiB, and the per-session resident window of encoded +recent events, bounded at 4,096 events and 16 MiB, and it enforces the +512 MiB aggregate across every output buffer and resident window it holds. +When the next event would exceed the core count or a daemon byte bound, the +daemon detaches the attachment at its last completely emitted cursor with a +stable reason rather than letting either stage grow. No byte limit is +enforced inside core. + +### Generation 2 additions + +| Method | Required fields | Result | +| --- | --- | --- | +| `session.list` | `limit` (1 to 256), optional `after_session_id` | A page of at most `limit` session entries ordered by session ID bytes ascending and starting strictly after `after_session_id`; each entry carries session identity, lineage, lifecycle state, last committed sequence and controller presence, never content; `next_after_session_id` is present exactly when more entries exist | +| `session.stop` | `session_id`, `command_id`, `writer_epoch` | Admission of a durable stop under the current controller; observers refuse | +| `daemon.status` | none | Placement identity, daemon incarnation, socket path, attachment and session counts against their limits, uptime | +| `session.acquire_control`, `session.release_control` | `session_id`, `request_id` and the lease fields ADR 0033 fixes | Lease result naming the writer epoch and the remaining lease term | + +`session.list` reads a daemon-owned index, never the session directory or the +store on the request path. The index is built once at daemon start from the +session directory and updated when the daemon creates, resumes or stops a +session; it is rebuilt only by a daemon restart. A page is consistent with +the index at the moment it is read; no consistency is promised across pages, +so a session created or stopped between pages may appear in neither or both, +and a client that needs a stable view deduplicates by session ID. A `limit` +outside 1 to 256 or an `after_session_id` that is not a well-formed session +ID refuses with the existing invalid-argument reason; an `after_session_id` +naming an unknown session is admitted and pages from its byte position. + +The client supplies its ordered supported generations in `initialize`. The +daemon supports exactly `loopex.experimental/2`: it selects that generation +when the client lists it, at any position, and otherwise refuses with +`unsupported_generation`, leaving the connection uninitialized with no second +attempt, exactly as ADR 0023 fixes for a foreground process. The successful +reply carries `selected_generation`, the exact generation-2 schema digest, +the generation-2 method inventory and limits. The generation-2 schema and +vectors are canonical bytes bound by the M5 gate before acceptance; a +negotiation vector proves selection from a list that also names generation 1 +and refusal of a generation-1-only list. The M4 foreground server keeps +serving generation 1 only, with its one-attachment-per-process rule. + +### Attachment lifecycle + +Attach is the runtime's race-free cursor transaction: the dispatcher +establishes the barrier at committed sequence N, the snapshot is anchored at +exactly N, and durable events after N are buffered for that attachment and +delivered contiguously after the snapshot. The daemon adds: + +- a resident window of at most 4,096 durable events and 16 MiB of encoded + events per session held in memory; a cursor inside the window replays from + memory and a cursor older than the window replays from the store. On the + local adapter every durable event is retained until the root is retired, + so store replay always succeeds. `cursor_expired` with a fresh snapshot + and cursor is the defined response a compacting adapter returns for a + cursor older than its retained history; no M5 witness can produce it and + none claims to; +- the core event-count queue and the daemon socket output buffer above; when + the next event would exceed either, the attachment is detached at its last + completely emitted cursor with a stable reason and the client reconnects + at that cursor; +- at most 512 MiB of retained encoded events across the daemon's output + buffers and resident windows; on aggregate pressure, evict or detach the + slowest eligible attachment before admitting more bytes, without stalling + a journal transaction; +- 64 attachments per session and 512 per daemon, refused at attach with a + stable reason when exhausted; +- eviction of an attachment that has consumed nothing for ten minutes; the + eviction record names the cursor the client may resume from; +- transient progress coalesced per attachment and dropped first under + pressure, with a counted drop; no progress item ever waits on a journal + transaction. + +A detached, evicted or reconnecting client that attaches at its retained +cursor receives every durable event after that cursor at least once and in +order; it never receives a gap, and it deduplicates by session ID, event +sequence and event ID. + +### Evidence + +Tests prove: two core attachments to one session keep independent live handles, +snapshots and cursors with no implicit replacement; an explicit replacement +invalidates only its named incarnation; snapshot-then-contiguous at-least-once +delivery with no gap across the window boundary; a slow observer detached at +its last emitted cursor while the controller and other attachments continue; +the per-session and per-daemon limits refusing independently; idle eviction +and reconnect with no missing durable event and any duplicate deduplicated by +session ID, sequence and event ID; the three encoded-byte ceilings at maximum +attachment count and payload pressure enforced in the daemon-owned stages, +with process RSS observed and reported separately; a generation-1-only +initialize refused with `unsupported_generation` and nothing created; +simultaneous daemon starts on one root leaving exactly one listener with the +loser never touching the socket; Store-child failure closing the listener and +every connection before exit; `session.list` pages of at most 256 entries in +session-ID order with an exact continuation cursor; progress coalescing under +pressure with counted drops and no journal delay; peer-credential refusal; a +socket path beyond the bound refused at start; frame, fragment and +malformed-input refusals identical to the foreground server's. + +### Alternatives + +TCP on loopback was rejected for the local daemon: it has no peer-credential +check and invites remote exposure by misconfiguration; WebSocket and HTTP +remain later transports under vision §18.8. An unbounded per-attachment queue +was rejected because it lets one client grow coordinator-adjacent memory +without bound. Keeping the M4 one-attachment-per-process rule was rejected +because a daemon's clients are processes by definition. A daemon-owned proxy +fan-out was rejected because it would duplicate core cursor and queue +ownership and need a second replay boundary to preserve the +subscribe/snapshot race. Serving generation 1 on the daemon was rejected: its +wire has no lease field, so it could only ever be served as one exclusive +connection per session, which the foreground server already provides, and it +would add a second fencing path with no wire epoch. Promising exactly-once +replay was rejected on 2026-09-14 because the founding contract is +at-least-once with client deduplication, and a stronger daemon promise would +create an expectation no other surface honors. Removing `session.list` was +rejected on the same day because an observer without filesystem access to +the root would have no way to discover sessions; the bounded page contract +above is the cost of keeping it. + + +### Compatibility and Rollback Mechanics + +Concept: [Consequences and rollback](0032-daemon-attachment-residency-and-replay.md#concept-adr-0032-consequences). + +Generation 2 is additive over generation 1's method set and both are +experimental with the exact-generation rule; no mixed-generation stream +promise exists. The daemon serves generation 2 only; the existing foreground +server still serves generation 1 with one attachment in its process. The +residency limits are server-enforced ceilings advertised at initialize under +the existing `limits` member. Removing the daemon leaves the foreground server +unchanged; existing embedded callers retain their behavior, and the core +supports independent same-session attachments. No durable record depends on +residency state or on the session index. + +Acceptance binds this complete pair at an exact candidate. Its evidence and +compatibility claims remain unproved until the M5 gate's required paths execute. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md new file mode 100644 index 000000000..7c1724d30 --- /dev/null +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -0,0 +1,101 @@ + +## Concept + +Technical depth: [Attachment residency mechanics](0032-daemon-attachment-residency-and-replay-technical.md#technical-depth). + +- **Status:** Proposed +- **Date:** 2026-09-14 +- **Decision owner:** Maintainer +- **Supersedes:** nothing; ADR 0023's one-attachment-per-foreground-process rule and generation-1 wire remain in force on the foreground server +- **Prerequisite for:** M5 acceptance + + +### Context and Decision + +The M4 foreground server maps one connection to one attachment in one +process that exits with the client. A daemon keeps sessions alive across +client processes, so it must answer what a client is owed when it attaches, +reconnects, falls behind or goes idle, and it must do that over a transport +that several processes on one machine can reach. The vision fixes the +semantics: attach is one race-free cursor transaction anchored at a committed +sequence; delivery of durable events is at least once and contiguous, so +duplicates are permitted and gaps are not, and a client deduplicates by +session ID, event sequence and event ID; a cursor older than a store's +retained history returns `cursor_expired` with a fresh snapshot instead of +truncating silently; a slow attachment is bounded and cannot block the +coordinator or another client; and a reconnecting client is owed complete +durable events and terminal outcomes, not every dropped progress fragment. + +Decide the transport and the residency rules together, because the numbers +only mean something against a transport. The daemon carries the ADR 0023 +JSONL protocol over a Unix-domain socket, reusing its framing, initialize +handshake, request, admission, snapshot, event and progress records and +limits unchanged, and serves exactly one generation, +`loopex.experimental/2`, which adds `session.list`, `session.stop`, +`daemon.status`, the two control methods and the writer-epoch field ADR 0033 +names. A client that offers only generation 1 is refused at initialize under +ADR 0023's existing no-common-generation rule and nothing durable is +created; generation-1 clients keep the M4 foreground server, whose wire, +one-attachment rule and behavior do not change. A narrow core change lets +distinct attachments to the same session coexist without replacing one +another; the core continues to own their independent cursor barriers and +event-count queues, while the daemon owns per-connection socket output +buffers, the resident window and the residency ceilings. The socket path is +the state root's `daemon.sock` unless the operator names another, and a path +beyond the platform bound is refused at start rather than truncated. A daemon +acquires the root's store writer marker before it touches the socket path, +so two simultaneous starts resolve at the marker and never at the socket, +and a daemon that loses its store closes the listener and every connection +before it exits. Only the daemon's own operating-system user may connect; a +foreign peer is refused before initialize. + +Every attachment starts from a snapshot anchored at the committed sequence +and then receives the buffered and live stream contiguously, at least once. +The daemon keeps a bounded resident window of recent durable events per +session and replays older ones from the store on demand. On M5's local +adapter every durable event stays replayable until the operator retires the +root, so replay always succeeds; `cursor_expired` remains the defined +response a compacting adapter returns for a cursor older than its retained +history, and no M5 path produces it. Each connection owns a bounded socket +output buffer; a slow attachment is detached at its last completely emitted +cursor while every other attachment continues. Idle attachments are evicted +at the residency limit and reconnect at their retained cursor with no +missing durable event. Transient progress is coalesced or dropped first and +never delays a journal transaction. `session.list` returns bounded pages +with an exact continuation cursor from a daemon-owned index. The proposed +limits are exact and are bound at acceptance: 64 attachments per session, +512 per daemon, a 1,024-event core queue per attachment, a 4,096-event +resident window per session, 4 MiB of encoded output buffered per +connection, 16 MiB of encoded resident-window events per session, 512 MiB +of aggregate retained encoded events per daemon, ten minutes of idle time +before eviction, 256 sessions per list page, and the ADR 0023 frame ceiling +unchanged. Count and byte ceilings apply together; an event that would +exceed either triggers the stated detachment, eviction or refusal behavior +before the ceiling is crossed. + +Technical depth: [Contract and evidence](0032-daemon-attachment-residency-and-replay-technical.md#technical-adr-0032-decision). + + +### Consequences, Compatibility and Rollback + +A client that reconnects at its cursor sees every durable event after it, in +order, possibly more than once, never with a gap; it deduplicates by session +ID, event sequence and event ID exactly as the vision requires of every +consumer. A misbehaving client costs the daemon a bounded buffer and its own +detachment, never another client's progress. Generation 2 is additive over +generation 1's method set; a client that can speak only generation 1 learns +at initialize that this daemon does not serve it, and the foreground server +still does. The public protocol remains experimental with exact-generation +agreement and no mixed-generation stream promise. + +Rollback is the M4 foreground server on the same local store: the daemon +carries no residency state, so removing it loses nothing durable. Numbers are +safety ceilings to prove under the M5 gate, not measured service promises. + +Technical depth: [Compatibility mechanics](0032-daemon-attachment-residency-and-replay-technical.md#technical-adr-0032-compatibility). + +## Governance Record + +| Decision | Authority | Authority evidence | Bound bytes | +| --- | --- | --- | --- | +| Acceptance | — | — | — | diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md new file mode 100644 index 000000000..28265271b --- /dev/null +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -0,0 +1,166 @@ + +## Technical depth + +Concept: [Collaboration: controller lease and takeover](0033-collaboration-controller-lease-and-takeover.md#concept). + + +### Contract and Evidence + +Concept: [Context and decision](0033-collaboration-controller-lease-and-takeover.md#concept-adr-0033-decision). + +### Lease record + +The daemon keeps one lease record per session in its own process memory, +never in the session journal, in a file or in any store: + +```text +session_id, writer_epoch, holder (connection identity), granted_at (monotonic), +deadline (monotonic), state ∈ {held, released, expired} +``` + +`writer_epoch` is an opaque string from ADR 0023's identifier alphabet, at +most 64 bytes, carrying at least 128 bits of fresh randomness. It is minted +at every grant and never reused: not across grants to the same connection, +not across a restart of the per-session lease owner process, and not across +a restart of the daemon. Clients treat the epoch as opaque and compare it +only for equality. The daemon incarnation is a fresh opaque identifier +generated at each daemon start and reported by `daemon.status` as a +diagnostic; it confers nothing and is not part of the epoch. It is a daemon +fact: core session epochs, owner incarnations and receipts are unchanged and +remain the commit-authority fence. + +One owner process per session serializes every lease read, grant, renewal, +release and expiry transition with that session's mutation-admission handoff, +so a takeover cannot pass a mutation whose holder check has already started +but whose core admission is unresolved; that admission first resolves or +remains fenced. If that owner process crashes and is restarted by the daemon +while the daemon and its client sockets survive, the restarted owner holds no +lease: the session is uncontrolled, the previous holder's epoch can never be +minted again, and its delayed commands refuse on both the holder and the +epoch check until it acquires again and receives a new epoch. Expiry and +admission use the daemon's monotonic clock: a deadline is set only by a +successful grant or renewal, and a wall-clock jump cannot shorten or extend +a live holder's authority. Nothing about a lease is persisted or recovered. +After a daemon restart no lease exists, every session is uncontrolled, the +previous socket and its connections are gone, and a client presenting an old +epoch is refused both because it can never match and because it is not a +holder connection. Writer exclusion between two daemons on one state root is +the local store's writer marker, unchanged. + +### Methods and fields + +- `session.acquire_control` (`session_id`, `request_id`): grants control when + no lease is held, or when the held lease is released or expired; refuses + with `control_held` naming the current epoch otherwise. The result carries + the new `writer_epoch` and `expires_in_ms`, the remaining term on the + daemon's clock. For a known dormant session, a connection may acquire by + session ID before attach. The daemon validates durable session existence + first; the held lease lets that connection call `session.resume` and then + attach. Daemon startup recovery of sessions is a root-owner operation under + the store's writer marker, never a client mutation and never a grant of + controller authority. +- `session.release_control` (`session_id`, `request_id`): releases the + caller's own lease; a non-holder refuses. +- Renewal is implicit on any admitted command and explicit through + `session.acquire_control` from the holder, which extends the deadline + without changing the epoch. +- Every existing-session mutation in generation 2, including + `session.resume`, `session.stop`, `session.prompt`, `session.steer`, + `session.follow_up`, `session.abort`, `session.respond_interaction`, + `session.admit_resources` and `session.activate_skill`, carries + `writer_epoch`. The daemon admits it only if the sending connection is the + recorded holder, the epoch matches, the lease state is `held`, the deadline + is later than the live daemon's monotonic admission time, and the + connection holds a controller-capable attachment, except that a verified + dormant session's `session.resume` may precede attach under that + connection's held lease. The check and core handoff are serialized against + lease transitions for the session. A mismatch or failed condition refuses + before core admission and before a session write; an observer who copied + the visible current epoch still refuses. Queries and attach carry no epoch. +- `session.create` has no `writer_epoch` because the session lease does not + exist. It creates an uncontrolled session. The caller must attach, acquire + control explicitly, and use the returned epoch for its first session + command. Creation never implicitly grants control. +- An orderly connection close by the holder releases the lease; an abrupt + loss leaves it to expire. + +Proposed terms bound at acceptance: lease length 30 seconds, renewal interval +10 seconds for the reference clients, takeover admitted when the live daemon's +monotonic deadline is reached, no grace period beyond the lease itself. + +### Cancellation across processes + +`session.abort` is the durable abort command the core already accepts. The +daemon forwards it from the current controller regardless of which +connection or process admitted the command that started the running work, +because dispatch, cancellation and the two-phase abort with its truthful +`cancelled` or `outcome_unknown` terminal belong to the core's coordinator, +not to the client that prompted. An observer's abort refuses before +admission. + +### Authority + +Control is a daemon-owned scheduling fact. It grants no effect: host policy, +grants, fences and executor validation apply to a controller's tool calls +exactly as to a single-client session. The daemon's configuration may +restrict takeover to the daemon's own operating-system user, which the socket +already enforces, and to an operator-supplied allow rule; it cannot admit a +command that host policy would refuse. No client content, model output, +interaction answer, metadata, request identity or attachment order confers +control, and a read-only attachment never admits a command whatever it sends. +The daemon's observer role is connection authorization. An explicit successful +acquire grants that connection a controller role scoped to the lease; neither +the existing core attachment handle nor an observer's knowledge of the epoch +is itself command authority. + +### Evidence + +Tests prove: exactly one controller with observers within the ADR 0032 bounds; +a stale epoch, copied current epoch, non-holder connection, released state +and expired state each refused before core admission with the current +controller unaffected; a lease transition racing command admission preserves +this order; takeover only after release or expiry with a fresh epoch minted +before the successor's first command; a controller killed mid-run fenced +after takeover, its late commands refused; the per-session lease owner +process crashing and restarting while the daemon and client sockets survive, +after which the previous holder's delayed command is refused, no epoch is +ever reused, and a new acquire carries a new epoch; an abort from the new +controller cancelling work dispatched under the old controller's command +with a truthful cleanup outcome; an observer never acquiring authority +through content, metadata, answers or order; after a daemon restart every +session uncontrolled, an epoch from before the restart refused, and the +first acquire granting a fresh epoch; forward and backward wall-clock jumps +not changing live admission or takeover timing; creation yielding an +uncontrolled session and requiring attach plus explicit acquire before +prompt; a dormant session acquired by ID, then resumed with epoch and +attached. + +### Alternatives + +Placing the lease in core was rejected because the vision keeps collaboration +policy above core and another host may choose a different rule. Last-writer- +wins without an epoch was rejected because a killed controller's late command +would interleave with the successor's. A lease with no expiry was rejected +because a crashed controller would hold the session forever. A durable lease +record was rejected: after a daemon restart every connection is gone with its +socket and admission already requires the holder connection, so durability +could only preserve an epoch counter that nothing needs. A counter-based +epoch scoped to the daemon incarnation was rejected on 2026-09-14 because a +lease-owner process restart under the same incarnation would mint values +already issued, and a connection re-acquiring after such a restart could +have its own earlier delayed command admitted; a fresh random epoch per +grant costs nothing and closes that hole. + + +### Compatibility and Rollback Mechanics + +Concept: [Consequences and rollback](0033-collaboration-controller-lease-and-takeover.md#concept-adr-0033-consequences). + +The lease methods and the `writer_epoch` field exist only in generation 2 of +the experimental protocol, which is the only generation the daemon serves. +The M4 foreground server still has its own single connection and no daemon +lease. Core session records, events and snapshots are unchanged. Removing the +daemon removes the lease with it; no journal or file depends on it. + +Acceptance binds this complete pair at an exact candidate. Its evidence and +compatibility claims remain unproved until the M5 gate's required paths execute. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md new file mode 100644 index 000000000..98d18d988 --- /dev/null +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -0,0 +1,90 @@ + +## Concept + +Technical depth: [Collaboration mechanics](0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth). + +- **Status:** Proposed +- **Date:** 2026-09-14 +- **Decision owner:** Maintainer +- **Supersedes:** nothing; the core keeps the vision §11.6 rule that it mandates no controller lease +- **Prerequisite for:** M5 acceptance + + +### Context and Decision + +Once several client processes can attach to one live session, two of them can +try to drive it. The core serializes every durably admitted command and does +not care which client sent it, so without a rule above the core two terminals +would interleave prompts, steers and aborts into one run and each would see +the other's work as its own. The vision assigns that rule to the reference +daemon: one controller, many observers, stale-controller fencing and crash +takeover, none of it in core semantics, and a read-only attachment never +acquiring command authority. + +Decide the rule. Each daemon-owned session has at most one controller at a +time, held under a lease the daemon owns and keeps in its own memory for the +daemon process's lifetime, never in the session journal or any durable +record. Every other attachment is an observer: it receives the same snapshot +and events and may not admit a command. For an existing session, the daemon +admits a mutation only when the sending connection is the current holder, +its supplied writer epoch matches, the lease is held and unexpired, and the +attachment has command capability. The daemon checks those facts together +before core admission and serializes that handoff with lease changes; an +observer cannot reuse an epoch it learned from a result or status. +`session.create` is the one exception because no session lease exists yet: +it creates an uncontrolled session, after which the client attaches and +explicitly acquires control before its first session command. For a known +dormant session, a client may acquire control by session ID before +`session.resume`, then resume with the granted epoch and attach. A +controller renews its lease while it lives and releases it on an orderly +disconnect; a lease that is not renewed expires. Takeover is explicit: an +observer asks for control and receives it only when the lease is released or +expired, and the grant mints a new writer epoch before the new controller's +first command can be admitted, so a controller that was killed mid-run and +comes back late is fenced by its stale epoch. The writer epoch is an opaque +value minted fresh for every grant and never reused, so a stale epoch from +any earlier tenure, including one issued before the lease owner or the whole +daemon restarted, never matches. After a daemon restart every session is +uncontrolled and every earlier connection is gone with the old socket; +nothing about control survives the daemon that granted it, while session +truth lives in the journal exactly as before. Cancellation crosses processes +because the core owns dispatch: the current controller's `session.abort` +cancels work that an earlier controller's command dispatched, with the +truthful cleanup outcome the core already commits. + +Nothing but the lease grants control. No client content, model output, +interaction answer, metadata field or attachment order confers it, and the +daemon's own configuration may narrow who may take over; it cannot widen what +the host's policy allows a command to do. The proposed lease terms are exact +and are bound at acceptance: a thirty-second lease renewed every ten seconds, +takeover admitted at the live daemon's steady-clock expiry, and immediate +release on orderly disconnect. Writer exclusion between two daemons on one +state root stays the local store's writer marker, unchanged. + +Technical depth: [Contract and evidence](0033-collaboration-controller-lease-and-takeover-technical.md#technical-adr-0033-decision). + + +### Consequences, Compatibility and Rollback + +Two people, or one person and one automation, can watch one session while +exactly one of them drives it, and a crashed driver's terminal cannot +interfere after someone else has taken over. Core semantics are unchanged: +admission, ordering, durability, fencing by session epoch and receipts stay +exactly as accepted, and another host may implement a different collaboration +policy above the same core. The wire gains lease methods and a writer-epoch +field in generation 2 only. Creating a session grants no command authority +until control is acquired. Because the lease is not durable, a daemon restart +is a clean slate for control and for nothing else: the first client to +acquire after restart becomes the controller. + +Rollback is the M4 foreground server, whose single connection is its own +controller by construction; the lease is daemon memory and is simply absent +without a daemon. + +Technical depth: [Compatibility mechanics](0033-collaboration-controller-lease-and-takeover-technical.md#technical-adr-0033-compatibility). + +## Governance Record + +| Decision | Authority | Authority evidence | Bound bytes | +| --- | --- | --- | --- | +| Acceptance | — | — | — | diff --git a/docs/adr/README.md b/docs/adr/README.md index 7873bb569..4746e93c7 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -40,6 +40,9 @@ a decision adds a new record rather than rewriting the old one. | 0028 | Bounded artifact retrieval | Accepted | [Decision](0028-bounded-artifact-retrieval.md#concept) | [Technical depth](0028-bounded-artifact-retrieval-technical.md#technical-depth) | | 0029 | Bounded provider failure diagnostics | Accepted | [Decision](0029-bounded-provider-failure-diagnostics.md#concept) | [Technical depth](0029-bounded-provider-failure-diagnostics-technical.md#technical-depth) | | 0030 | Observability: tracing and telemetry | Accepted | [Decision](0030-observability-tracing-and-telemetry.md#concept) | [Technical depth](0030-observability-tracing-and-telemetry-technical.md#technical-depth) | +| 0031 | Daemon-grade store selection and migration | Proposed | [Decision](0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | +| 0032 | Daemon attachment residency and replay | Proposed | [Decision](0032-daemon-attachment-residency-and-replay.md#concept) | [Technical depth](0032-daemon-attachment-residency-and-replay-technical.md#technical-depth) | +| 0033 | Collaboration: controller lease and takeover | Proposed | [Decision](0033-collaboration-controller-lease-and-takeover.md#concept) | [Technical depth](0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth) | 0001 and 0002 were the prerequisites that unblocked the first milestone candidate; the [plans register](../plans/README.md) records current status. @@ -156,3 +159,15 @@ than assume three. All five were accepted on 2026-09-13 at candidate gate record and does not accept the M4 plan pair or gate. The protocol/interaction proposals were renumbered from the old draft's 0019/0020 because those numbers are now accepted M2 decisions. + +0031, 0032 and 0033 are the three Proposed M5 prerequisites: the daemon's +store selection, which for M5 is the existing local adapter with its +documented limits and retirement procedure and for the successor milestone +the daemon-grade adapter chosen by contract experiments plus its migration; +daemon attachment residency and at-least-once replay over the +generation-2-only Unix-domain-socket transport with bounded session pages; +and the collaboration rule of one in-memory controller lease with fresh +per-grant epochs, observers and takeover. They were proposed with the Open M5 +lookahead on 2026-09-14 and revised twice that day on independent review; +they accept nothing, and each must be accepted before the outcome that +depends on it is implemented. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md new file mode 100644 index 000000000..5d88214f2 --- /dev/null +++ b/docs/plans/M5-technical.md @@ -0,0 +1,293 @@ + +## Technical depth + +Concept: [Durable service](M5.md#concept). + + +## Normative Technical Envelope + + +### Prerequisites and Acceptance Points + +Concept: [Scope](M5.md#concept-plan-scope). + +Concept: [non-goals](M5.md#concept-plan-non-goals). + +The Open M5 planning bytes were drafted on M4's accepted governance checkpoint +`6f973f774a403f76330058e3d0a59f7b83e038f1`, but inherited M1 and M2 +gates were unavailable there. The M4-specific waiver and deferral do not +authorize this opening. M4 is Accepted and remains the sole implementation +authority; these M5 bytes confer none. Before M5 can be accepted, M4 must be +Closed and integrated; reconstruct M5's branch-only opening checkpoint on +that exact inherited-green product base, re-prove every inherited gate green +and its own distinct red on it, bind the generation-2 schema and vector +bytes, prove their fixture shape and digest integrity on both locked +toolchain pairs, and obtain fresh exact-SHA review. +At final acceptance all inherited gates are green and the M5 boundary remains +truthfully red for the missing daemon. No draft candidate from the unavailable +opening is eligible for acceptance or integration. + +M5 accepts three decisions before dependent work: + +| Decision | Owner and acceptance point | Effect | +| --- | --- | --- | +| [**ADR 0031**](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Maintainer, before M5 acceptance; binds the local-adapter selection, its exact limits and the retirement procedure, and fixes the successor's selection procedure without running it | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and root retirement documented; the daemon-grade adapter, its experiments and migration reserved for the successor | +| [**ADR 0032**](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Maintainer, before M5 acceptance; must bind every residency number below, the generation-2-only negotiation rule, the marker-first startup order and the `session.list` page contract | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's daemon methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, race-free attach with at-least-once contiguous delivery, a resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages | +| [**ADR 0033**](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Maintainer, before M5 acceptance; must fix the lease terms below | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds the holder connection, held state, unexpired term and writer epoch, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | + +ADR 0031's daemon-grade adapter, contract experiments and migration belong to +the successor milestone and bind nothing in M5; only its local-adapter +selection and documented limits are M5 prerequisites. + +**Residency and lease profile (proposed, bound at acceptance).** 64 +attachments per session and 512 per daemon, refused independently; a +1,024-durable-event core queue per attachment and a 4 MiB encoded-byte +daemon-owned socket output buffer per connection, detaching at the last +completely emitted cursor before the next event would exceed either bound; a +4,096-event and 16 MiB encoded-byte daemon-owned resident window per session +with store replay behind it, which on the local adapter always succeeds; 512 +MiB total retained encoded durable-event bytes across all output buffers and +resident windows in one daemon, with pressure detached or evicted before that +total is exceeded; eviction after ten minutes without consumption, naming the +resumable cursor; `session.list` pages of at most 256 entries with an exact +continuation cursor; a thirty-second lease renewed every ten seconds, +takeover admitted at expiry with no further grace, release on orderly +disconnect; the ADR 0023 frame ceiling unchanged. These are retained-payload +ceilings, not an exact BEAM RSS promise. Measure and report actual process +RSS under the maximum attachment count and at payload pressure separately. + +**Daemon launch inputs.** State root, socket path, placement identity, policy +module with identity and revision, provider, executor, ArtifactStore and +project resource snapshot are fixed when the daemon starts. No connection +replaces any of them; a client may select admitted resources and answer +interactions exactly as under M4, and may acquire control only through the +lease. + +**Holder transactions.** M5 changes bytes that Closed gates bind in two +places, both after acceptance: + +| Artifact | Holders | Restriction today | Planned change | Phase | Route and checks | +| --- | --- | --- | --- | --- | --- | +| `apps/loopex/lib/mix/tasks/loopex.deps_budget.ex`, `apps/loopex/test/deps_budget_test.exs`, `apps/loopex_daemon` | M1 (the application is unbound M5 product) | Ten-application inventory after M4; the daemon application absent | Eleven-application inventory, the daemon as a client-role application depending inward on core, protocol and composition, negative tests, and the minimal application in the same proposal | B | One Closed-M1 v2 proposal `A` carrying M1's next gate generation, both dependency-oracle artifacts and the minimal application, following the M1 Amendment 7 pattern M4's phase B reuses; review and accept `A`; governance-only `R` | +| `VERSION`, application versions, and every version-aware runner and verifier M4's closure made version-aware | M1, M2, M3, M4 | 0.1.0 after M4 closure | 0.2.0 | C | Separately approved version transition; v2 for Closed M1, M2, M3 and M4 in register order, then Accepted M5 last through its own v1 amendment and rebind | + +`.tool-versions` is unchanged. The generation-2 schema and vectors are new +files; M4's bound generation-1 bytes are not touched, so M4 is not a holder +there. M5 adds no external dependency. Phase B and C bindings settle before +the rejoin or closure candidate that depends on them; closure cannot be +recorded while any is stale. + +M4 owns interactions, transfers, the foreground server and observability; an +inherited defect is reproduced at the exact base and repaired at its owner, +and a daemon workaround cannot conceal it. + + +### Ownership, Decision Owners, and Rejoin Barriers + +Concept: [Scope](M5.md#concept-plan-scope). + +| Component | Owns | Cannot own | +| --- | --- | --- | +| `loopex` | Durable session truth, race-free attach barrier and cursor, independent concurrent attachments to the same session, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex_protocol` | Generation-2 DTOs, validators, schema and vectors | Daemon behaviour or lease semantics | +| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` refusal and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | +| `loopex_daemon` | Marker-first process and socket lifetime, peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session stop, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity or any durable record | +| `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | +| `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | +| TypeScript consumer | Socket connection, observer following and takeover presentation | Normative semantics | + +The ordered rejoin is prerequisite decisions → holder transaction for the one +minimal application → narrow core multi-attachment support → marker-first +daemon lifetime and socket over the local adapter → collaboration lease and +takeover → residency, replay and backpressure → two-process workflow with the +reference CLI and TypeScript consumer → integrated audit → independent +review. Prove lifetime, refusal of a second daemon at the marker, shutdown on +store loss, capacity refusal, reopening under the foreground server after an +orderly stop, independent simultaneous core attachments, +snapshot-then-contiguous delivery, stale-epoch refusal, takeover and +cross-process abort before the client workflow rejoins. + +Use the existing command identity for every mutating method; request +identities never enter journals. `session.create` has no existing session or +epoch to authorize: it creates an uncontrolled session, after which a client +may attach before or after acquiring control, while `session.resume` requires +acquiring control first. Existing-session mutation requires control. The +lease record lives in the daemon's memory, keyed by session, for the daemon +process's lifetime; one owner process per session serializes its lease +transitions with its admission handoff, and a restart of that owner leaves +the session uncontrolled. For every existing-session mutation, the daemon +checks the requesting connection identity, current epoch, held state and +unexpired term together before forwarding to core; an epoch alone is not +authority, and every epoch is minted fresh at grant so no earlier value can +match. Attach reuses the runtime's cursor transaction; the core keeps +attachments independent and its event-count queues, while the daemon +buffers encoded output, evicts above it and never reads coordinator state. +Cross-process abort forwards the existing durable `session.abort` command; +no daemon-side cancellation path exists. + + +### Evidence Obligations and Mapping + +Concept: [Outcomes](M5.md#concept-plan-outcomes). + +| Outcome | Mandatory proof beyond a unit test | +| --- | --- | +| 1 | Real daemon process per state root; sessions progress with zero attachments; orderly stop releases the writer marker and records nothing false; abrupt kill followed by restart recovers every session under the same placement identity with no duplicate effect; simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket; Store-child failure closes the listener and every connection before exit; a root driven to the 256 MiB log capacity refuses further mutation with `store_capacity_exceeded` while observers stay attached and an orderly stop still succeeds; `session.list` pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index; after an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay; session open and stop through the socket only | +| 2 | Raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its generation, and a generation-1-only initialize is refused with nothing created; identical durable identities for the same command corpus through facade, foreground server and socket; foreign-uid peer refused before initialize; frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons; client disconnect recorded as transport loss with no cancellation and no interaction change | +| 3 | One lease per session in daemon memory with observers attached; connection identity, epoch, held state and unexpired term checked together before core admission or durable write, including a known current epoch sent by an observer; takeover only after release or expiry with a fresh epoch minted before the successor's first command; killed controller fenced and its late commands refused; the per-session lease owner crashing and restarting while the daemon and client sockets survive, with the previous holder's delayed command refused and no epoch ever reused; daemon restart leaving every session uncontrolled with every earlier epoch refused; controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome; no control from content, metadata, answers or attachment order | +| 4 | Several core attachments to one session remain independent when one detaches or backpressures; snapshot anchored at the committed sequence then contiguous at-least-once buffered and live delivery across the window boundary with no gap; slow observer detached at its last emitted cursor while the controller and other attachments continue; per-session and per-daemon limits refusing independently; idle eviction and reconnect with no missing durable event and any duplicate deduplicated by session ID, sequence and event ID; retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings enforced in the daemon-owned stages, separately exercising 512 attachments and maximum-sized output records, with observed process RSS recorded; progress coalesced or dropped with counted drops and no journal delay | +| 5 | From a fresh extraction of the exact source candidate, an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the TypeScript consumer as observer, kills the controller, takes over from the observer and aborts cross-process work; the attended real-provider selector runs from the extracted tree; every daemon boundary emits ADR 0030 spans and a daemon-scoped trace session captures identities only; every operator and developer documentation file receives an exact-source final documentation audit and independent finding disposition; the full gate's staged source archive of the exact candidate, with source `VERSION` exactly `0.2.0`, extracts, compiles and carries the attended workflow, and its report is retained | + +| 6 | Provider child receives its credential over the bootstrap channel: the parent VM's environment holds no credential before, during or after a call (asserted on the parent and on a child probe); a child of one invocation cannot observe another invocation's credential when two run at once; the crash-report, late-delivery, sink-loss, rotation and version-refusal cases of `credential_plane_test.exs` pass against the channel handoff with their assertions unchanged in meaning; a security review of the handoff is recorded with the milestone; the provider suite runs its modules concurrently and its measured duration is recorded beside the M4-closure baseline (~250 s serial on the Mac) | + +The final documentation audit enumerates every tracked file beneath +`docs/operator/` and `docs/developer/` in the exact closure source tree, +including new, materially updated and reviewed-unchanged files. Retain one +row per file with path, source SHA, file SHA-256, role for its reader, audit +disposition and finding resolution. Inspect content for consistency with the +daemon, socket, controller and observer rules, residency, restart and +local-store limit behavior, the source-only `v0.2.0` release sequence, +current M5 information, relevance, working links and directory-index routing +where applicable, and stale foreground-only claims. +The exact seven-row Documentation Obligations table names required material +updates; this broader audit is required even for files outside that table. +Automated status and link checks contribute evidence but cannot replace the +per-file content judgment. The independent closure reviewer examines the +complete inventory and every finding disposition at the exact source SHA; +unresolved blocking or high-severity documentation findings block closure. + +The opening runner binds one real behavioral red for outcomes 1 and 2. Local +positive controls prove same-VM attachment replay and cross-process recovery +after Store release. Its fixture then starts a separate daemon operating-system +process through +`Loopex.Daemon.start_link(state_root: root, runtime_options: runtime_opts)`; +the daemon alone owns the session Store and session. The fixture root is short +enough for ADR 0032's default `/daemon.sock`. Two independent +client processes use only ADR 0023 JSONL over that socket: the first +initializes generation 2, creates an uncontrolled session, attaches, acquires +control and commits a deterministic turn with its writer epoch; the second +initializes and attaches while the daemon still owns the session. Its +correlated snapshot has top-level `event_cursor` equal to +`snapshot.event_sequence`, at or beyond the committed tail. On the opening +base no daemon start or socket exists, so the declared behavior is red. Green +requires that daemon-owned socket path and those correlated protocol records +to complete. Second-daemon writer exclusion is proved separately under +Outcome 1. Before acceptance, bind +that real opening red, the exact selectors and witness names, the +generation-2 schema and vector bytes, the client interpreter pins, the exact +residency, encoded-byte and lease numbers and the fail-closed routing. After +acceptance, implement the daemon, the CLI commands and the consumer workflow; +every lane must pass before closure. A daemon that proxies several socket +connections to one replaceable core attachment cannot pass, because +independent concurrent attachments, lifetime with zero attachments, fencing +after a real kill and cross-process abort are required. + +Every protected selector uses the existing authoritative standalone ExUnit +channel. Preserve the inherited repair manifest rather than re-listing old +case counts in this plan. The complete gate runs inherited predecessors, +protected selectors, whole suite, language clients and retained-evidence +validation, with M3-style checkpoint and full modes and one decisive named +witness per clause. Real provider cases live in separate files. Under the +same preparation rule M3 recorded, future test bodies are written with +implementation; a missing witness is never a pass. + +Apply the M3 integrated audit and the M4 self-audit to the daemon, the socket, +the CLI commands and the recovery path. Test every lifetime, lease and +residency cut and each decoder-side negative at the receiver. Run actual +Darwin floor/current and Linux current lanes early. A repeated finding class +triggers a full adjacent-path audit. Final exact-source evidence and +independent review remain mandatory; no fixed review-round limit or +retry-to-green rule. + + +### Compatibility + +Concept: [Scope](M5.md#concept-plan-scope). + +The `v0.2.0` source tag identifies a numbered release, not a compatibility +freeze. All surfaces remain experimental. The socket reuses ADR 0023's +framing, handshake, records and limits unchanged; generation 2 is additive +over generation 1's method set with the exact-generation rule, a +generation-1 client sees no daemon method and no lease field, the daemon +refuses a generation-1-only initialize, and the foreground server keeps +serving generation 1 unchanged. The private journal, its adapter and its +format are unchanged; the embedded API, public events, snapshots, artifact +formats and executor protocol are unchanged. Source VERSION is distinct from +protocol generation, provider build and schema digest. + + +### Migration and Rollback + +Concept: [Scope](M5.md#concept-plan-scope). + +No journal migration exists in M5. The daemon reads and writes the same local +log the M4 foreground server and CLI write, under the same placement +identity, so a state root moves between the daemon and the foreground +surfaces by stopping one and starting the other. Prove that an orderly daemon +stop releases the writer marker and that the foreground server and the CLI +then resume a daemon-created session with identical replay. A root that +reaches the local log's 256 MiB capacity is retired, not migrated: stop the +daemon, move the root aside, start a fresh root; a session in a retired root +is resumed only by reopening that root. Rollback is stopping the daemon: +removing it restores the M4 foreground server and CLI on the same root with +no durable dependency on residency, index or lease state. Restore floor, +version and inventory protections through governed transactions. No in-place +downgrade, installed-data migration or service-manager claim. + + +### Packaging + +Concept: [Scope](M5.md#concept-plan-scope). + +Add exactly one application: `loopex_daemon`, the eleventh, with role +`:client`, depending inward on core, protocol and composition and reusing the +foreground server's protocol mapping. The application inventory and role +rules in `loopex.deps_budget.ex` change under M1's transaction. M5 adds no +external dependency. No transport library, socket abstraction layer or +service-manager integration enters any application; the socket is the +runtime's own `gen_tcp` local address family. + +Supply `loopex daemon`, `loopex attach` and `loopex sessions` in the +reference CLI, extend the TypeScript consumer to connect over the socket and +to follow and take over, and reuse the M4 Elixir and Python conformance +clients for generation 2. Pin Node and Python execution versions in +`scripts/fixtures/m5/client-toolchain.txt`; the runner verifies the pinned +executables before any client lane and reports absence or mismatch as +UNAVAILABLE. At the separately approved version transition set source +VERSION and application versions to 0.2.0; the full gate's report validator +accepts exactly `0.2.0` and nothing else. The full gate stages a tar source +archive from its exact committed candidate, extracts it outside the checkout, +compiles it, and runs the attended two-process selector from the extracted +tree following the operator guide; that staged, release-ready archive report +is the last Purpose obligation. Gate green and independent exact-SHA closure +review precede an explicit combined closure and release/tag disposition. +Record the closure transition under that authority, obtain its required +read-only exact-SHA review, and integrate that same reviewed commit to +`main` without rewrite. Release completion then follows closure: create one +annotated `v0.2.0` tag on precisely that integrated commit, and run the +post-tag check, which verifies the tag object is annotated, `v0.2.0^{commit}` +is the reviewed integration commit and is reachable from `main`, that +`git show :VERSION` is exactly `0.2.0`, and that the source +archive was generated from that commit; retain the archive SHA-256, source +commit and tree, and tag object identity. That completion is required by +this plan and is not a closure condition. Do not move the tag or publish +packages, binaries, installers or service units. + + +### Proportional Minimalism Budget + +Concept: [Scope](M5.md#concept-plan-scope). + +One application, one socket listener, one narrow core concurrent-attachment +change, one in-memory lease record and admission check, one resident window +and eviction policy, one per-connection output buffer, one session index +with bounded pages, three CLI commands and the consumer's socket mode +justify growth. No lease, transport, byte limit or residency policy in core; +no second loop, event dispatcher, cancellation path or protocol codec; no +transport registry, plugin socket layer, generic service framework, store +adapter, control store or durable daemon record; no daemon-side session +state beyond the lease, index and residency facts it holds in memory. +Implement lifetime, transport and collaboration once against the local +adapter. Raw line count is a review signal; behaviour and measured limits +govern. + diff --git a/docs/plans/M5.md b/docs/plans/M5.md new file mode 100644 index 000000000..f299ce119 --- /dev/null +++ b/docs/plans/M5.md @@ -0,0 +1,272 @@ + +## Concept + +Technical depth: [Durable service mechanics](M5-technical.md#technical-depth). + + +## Normative Concept Envelope + + +### Purpose + +Let independent client processes share one durable session without any of +them owning its lifetime. A local daemon owns every session in a state root: +it keeps sessions running while no client is connected, serves several client +processes over a Unix-domain socket with the same protocol the M4 foreground +server speaks, lets exactly one client drive while others observe, survives +the driver's crash with an explicit takeover, replays snapshot and cursor to a +reconnecting client contiguously and at least once with no gap, cancels work +across processes, and does all of it on the existing local store adapter, +which the daemon holds for its process's lifetime within that adapter's +documented limits. +Complete M5 as an operator-usable, source-only `0.2.0` release candidate: +from the exact source candidate, an operator follows the documented setup, +starts the daemon, and drives one session from two real client processes +with their own inputs, and the full gate proves a staged, release-ready +source archive of that candidate. Closure review and an explicit combined +closure and release/tag disposition then lead to an integrated closure +commit on `main`. Creating the annotated `v0.2.0` tag on that commit and +verifying its archive is the release completion this plan requires after +closure; it is not a closure condition, because closure cannot wait on a tag +that closure itself authorizes. + +M5 answers the vision's durable-service question and carries the roadmap's +v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and +observability unchanged and adds the daemon and its collaboration rule above +the core. The core's attachment machinery gains narrow support for several +independent attachments to one session; it gains no lease, transport or +second loop. No new store engine enters M5: ADR 0031 selects the existing +local adapter for this release, with its 256 MiB log ceiling, full-history +retention and root-retirement procedure documented, and reserves the +daemon-grade adapter, its selection experiments and migration for the +successor milestone. + + +### Outcomes + +| # | Outcome | Evidence class | Gate selector | +| --- | --- | --- | --- | +| 1 | A daemon owns session lifetime for a state root: sessions run while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon recovers every session under the same placement identity, a second daemon on the same root loses at the store writer marker before touching the socket, losing the store closes the socket and every connection, a root at the local log's capacity refuses further mutation truthfully while observers stay attached, sessions are listed in bounded pages, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault tests with real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated and a generation-1-only client refused, the same durable identities as facade and foreground server, owner-only peer access and the same framing refusals | Differential conformance across facade, foreground server and socket; negative transport and generation-2 Python-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_daemon/test/python_client_conformance_test.exs` | +| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Collaboration and fencing tests with real killed processes | `apps/loopex_daemon/test/collaboration_test.exs` | +| 4 | Several core attachments coexist without replacement; daemon attach, replay, residency and backpressure are race-free and bounded: snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with exact reconnect, retained encoded-event bytes within the daemon-owned bounds, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | +| 5 | From a clean source extraction and operator-supplied inputs, two real client processes, the reference CLI and the TypeScript consumer, drive one daemon-owned session through controller work, observer following, controller kill and takeover, with every daemon boundary emitting the accepted telemetry spans; a final exact-source audit covers every operator and developer documentation file, including relevant unchanged files, before closure review; and the full gate stages, extracts and proves a release-ready `0.2.0` source archive of the exact candidate | Operator setup smoke, integrated two-process workflow, attended real-provider demonstration, per-file final documentation audit with independent finding disposition, and the staged release-ready source archive report | `apps/loopex_daemon/test/multi_client_workflow_test.exs` | +| 6 | The provider adapter hands the credential to each provider child per invocation over the child's private bootstrap channel instead of the process-wide environment variable the child inherits today, so no provider child can receive another invocation's credential, the parent VM's environment never carries it, the existing credential-plane proofs (crash reports, late delivery, sink loss, rotation, version refusal) hold under the new handoff, and the provider test modules that today serialise on that one variable run concurrently | Credential-plane negative tests re-pointed at the channel handoff, an environment-scrub proof on parent and child, a security review of the handoff, and the measured provider suite with its modules concurrent | `apps/loopex_llm_reqllm/test/credential_plane_test.exs` | + +Technical depth: [Evidence mapping](M5-technical.md#technical-plan-evidence). + + +### Scope + +The daemon owns session lifetime, the socket, attachment residency, the +collaboration lease, its session index and the local store root it holds for +its process's lifetime. Core owns durable session truth and supports several +independent attachments to one session through its existing race-free attach +barrier and dispatcher. Hosts still supply workspace, identity, policy, +provider configuration and project resources when the daemon starts; no +client connection replaces any of them, and the daemon's configuration may +narrow who may take control but never widens what host policy allows. + +The socket reuses ADR 0023's framing, initialize handshake, request, +admission, snapshot, event and progress records and limits unchanged, and +serves generation `loopex.experimental/2` only, which adds `session.list`, +`session.stop`, `daemon.status`, the two control methods and the +writer-epoch field, and lifts the one-attachment-per-process rule to +residency limits. A client offering only generation 1 is refused at +initialize; generation-1 clients keep the M4 foreground server, whose wire +and behavior do not change. Attach is the runtime's race-free cursor +transaction, and delivery is contiguous and at least once: gaps are +forbidden, duplicates are permitted, and a client deduplicates by session +ID, event sequence and event ID as the vision requires. The daemon adds a +bounded resident window, daemon-owned bounded socket output buffers, +detachment at the last emitted cursor and idle eviction; on the local adapter +every durable event stays replayable until the operator retires the root, so +`cursor_expired` remains a defined protocol response no M5 path produces. +The credential handoff to a provider child moves from the process-wide +environment variable to the per-invocation bootstrap channel the launcher +already opens for the nonce and build manifest. The maintainer set this as an +M5 baseline on 2026-09-19: the environment handoff makes the twelve heavy +provider test modules serial, which pins the fast check near the provider +suite's length, and a credential that lives in the parent VM's environment is +a weaker property than one that exists only on a private channel to the child +that needs it. The change stays inside the credential plane: what a child may +receive, from whom and when does not widen; every negative proof M0–M2 +established is carried to the new mechanism, not relaxed. It is scheduled as +its own workstream with its own security review, and its measured result is +part of closure. +The residency and lease numbers are exact in the technical envelope and bound +at acceptance with the accepted ADRs 0032 and 0033: 64 attachments per +session, 512 per daemon, a 1,024-event core queue and 4 MiB socket output +buffer per attachment, a 4,096-event and 16 MiB per-session resident window, +512 MiB of aggregate retained encoded event bytes, ten idle minutes, 256 +sessions per list page, and a thirty-second lease renewed every ten seconds. + +Session creation makes an uncontrolled session; a client then acquires +control before existing-session mutation. Exactly one controller holds a +daemon-owned lease per session; every other attachment is read-only. For an +existing session, the daemon admits a mutation only when its requesting +connection is the holder of a held, unexpired lease and carries its current +writer epoch. Takeover is explicit, only after release or expiry, and mints +a fresh epoch before the successor's first command. The lease lives in the +daemon's memory for the daemon process's lifetime, never in the session +journal or any durable record; every writer epoch is minted fresh and never +reused, so a restart of the daemon or of a session's lease owner leaves that +session uncontrolled with every earlier epoch stale, and the core keeps +mandating no lease. Cancellation crosses processes because the core owns +dispatch: the current controller's `session.abort` cancels work an earlier +controller started, with the truthful two-phase outcome the core already +commits. + +The daemon runs every session on the existing local store adapter, selected +for this release by ADR 0031: one state root, the local log the M4 +foreground server and CLI already write, and the local writer marker held by +the daemon from before the socket is bound until the daemon exits. The +adapter's limits are the daemon's limits and the operator documentation +states them: a hard 256 MiB log capacity refused as `store_capacity_exceeded`, +a 4 MiB frame ceiling, full-history retention with no compaction, and full +replay at open; a root at capacity is retired by stopping the daemon, moving +the root aside and starting a fresh root. No new store adapter, journal +format version, migration or backup tooling enters M5. After an orderly +daemon stop the foreground server and the CLI reopen the same root and +sessions under the same placement identity, which is also M5's rollback. The +daemon-grade adapter, its selection experiments and its migration are the +successor milestone's first decision under the same ADR. + +M4's observability continues without change: every daemon boundary emits the +ADR 0030 spans, and a trace session scoped to the daemon's runtime captures +identities only. The socket path is bounded by the platform and refused when +too long; the socket is owner-only and a foreign peer is refused before +initialize; the daemon never runs as a service manager unit by itself and the +documented launch is a foreground command an operator or their service +manager runs. + +The release is one annotated `v0.2.0` tag on the exact reviewed closure +integration commit on `main`, and a source archive of that tagged commit. The +full gate retains a report for a staged candidate archive, extracts it, +compiles it and runs the attended two-process workflow from that extraction; +that staged proof is the last Purpose obligation. After gate green and +independent closure review, a combined explicit closure and release/tag +disposition authorizes the closure transition, integration, tag creation and +post-tag archive verification. The tag and its verification complete the +release after closure; the full gate cannot claim the future tag exists, and +closure does not wait for it. The release publishes no Hex package, binary, +installer or service unit and freezes no public protocol or embedded API. + +At the final source candidate, audit every tracked file under +`docs/operator/` and `docs/developer/` for consistency with M5, relevance, +links and indexing where applicable, and stale foreground-only claims. New, +materially updated +and reviewed-unchanged files all receive a recorded per-file disposition; +the independent closure reviewer examines the inventory and any finding +resolution. The seven-row gate table still names the exact files M5 must +materially update. Release instructions describe the required `v0.2.0` tag +and archive workflow without claiming a tag before it exists. + +Technical depth: [Prerequisites](M5-technical.md#technical-plan-prerequisites). + +Technical depth: [ownership](M5-technical.md#technical-plan-ownership). + +Technical depth: [compatibility](M5-technical.md#technical-plan-compatibility). + +Technical depth: [rollback](M5-technical.md#technical-plan-migration). + +Technical depth: [packaging](M5-technical.md#technical-plan-packaging). + +Technical depth: [minimalism](M5-technical.md#technical-plan-minimalism). + + +### Non-Goals + +No controller lease, transport, socket or collaboration rule inside core. Its +only M5 change is independent concurrent attachment support. No daemon-grade +store adapter, journal format version, migration, backup tooling, compaction, +retention cutoff or NIF dependency; no daemon-served generation 1; no durable +lease record; no exactly-once delivery promise beyond the founding +at-least-once contract. No WebSocket, HTTP, TCP, remote or native-BEAM +transport; no multi-host or multi-user identity, tenancy or authorization +beyond the socket's owner-only peer rule; no trusted extension activation, +isolated hands, ACP mapping, public-protocol freeze, hosted store, Hex +package, binary, installer or service-manager integration. Generation 2 adds +daemon methods and lease fields only; no other protocol breadth. Those +capabilities retain their vision barriers and require their own evidence. + +Technical depth: [Acceptance boundaries](M5-technical.md#technical-plan-prerequisites). + + +## Workstreams + +After M4 closes, reconstruct M5's valid opening checkpoint and settle the +three prerequisite decisions before M5 acceptance. After acceptance, land the +one application through its holder transaction and the narrow core +attachment change, then build daemon lifetime and socket over the local +adapter, prove collaboration and replay on that base, and join the +two-process workflow with the reference CLI and the TypeScript consumer +before method breadth. Reuse M4's focused checkpoints, clause witnesses and +integrated self-audit; full inherited checks remain at contract moments and +scheduled CI. No second loop, lease in core or transport registry. + +**Revision of 2026-09-14 (first).** On the independent review of +`dc81212360327caa7e8b0ed371cb5ed531b960d9`, the maintainer decided to narrow +this Open plan in three ways. The daemon-grade store, its selection +experiments and its migration leave M5 for the successor milestone, so M5 +adds one application. The daemon serves generation 2 only, so no +generation-1 exclusive lease exists. The controller lease is daemon memory, +so no durable daemon-control store exists. The rung question needs none of +the three, each doubled evidence without adding a proved capability, and the +daemon on the local adapter already reopens under the foreground server after +an orderly stop. + +**Revision of 2026-09-14 (second).** On the independent review of +`6e8319da299dc92ef0c2441da8e0443262292fb8`, the maintainer accepted every +finding and two recommendations. Delivery is stated as the founding +at-least-once contract with client deduplication, because a stronger daemon +promise would contradict the vision and no other surface honors it. ADR 0031 +returns as an M5 prerequisite, selecting the existing local adapter with its +256 MiB ceiling, full retention and root-retirement procedure documented, +rather than being deferred outright: the reference daemon runs on an +ADR-selected store and the roadmap ties operational claims to store +selection, so the daemon needs a recorded selection even when the selected +adapter is the existing one; the daemon-grade adapter and migration stay with +the successor. The closure and release cycle is broken by ending the last +Purpose outcome at the staged, release-ready source archive and making the +tag a post-closure release completion. The `cursor_expired` witness is +removed because the local adapter retains everything until the root is +retired, so no truthful path reaches it. `session.list` is kept with an exact +bounded page contract over a daemon-owned index, because observers without +filesystem access to the root would otherwise have no discovery; removal was +the cheaper alternative and was rejected for that reason. Writer epochs are +minted fresh per grant so a lease-owner restart can never reuse one; startup +acquires the store writer marker before touching the socket and store loss +closes the listener; byte limits live in daemon-owned socket output buffers +while core keeps its event-count queues; the report validator requires +exactly `0.2.0`; and wording now says the daemon process's lifetime and +names the reused and added protocol parts precisely. + +These Open M5 planning bytes were drafted on branch `m5` from the integrated +M4 acceptance checkpoint `6f973f774a403f76330058e3d0a59f7b83e038f1`. +M4 is Accepted and remains the sole implementation authority; these bytes +grant no M5 implementation authority and do not establish a valid lookahead +opening. The inherited M1 and M2 gates were unavailable on this base, and +the M4-specific waiver and deferral do not authorize an M5 exception. Before +M5 acceptance, reconstruct its branch-only opening checkpoint on M4's exact +Closed, integrated, inherited-green product base, re-prove every inherited +gate green and M5's distinct behavioral red, settle prerequisites, and obtain +fresh exact-SHA review. No candidate produced by this unavailable opening is +eligible for acceptance or integration. + +## Progress and Evidence + +| # | State | Evidence | +| --- | --- | --- | +| 1 | Open | No daemon exists; the opening probe observes that independent socket clients cannot initialize and attach to a daemon-owned live session. Marker-first startup, store-loss shutdown, capacity refusal, bounded listing and reopening under the foreground server are separate Outcome 1 witnesses | +| 2 | Open | No socket transport exists; generation 2 is not defined in canonical bytes | +| 3 | Open | No controller lease, writer epoch or takeover exists above core | +| 4 | Open | Core currently replaces an existing same-session attachment; no independent concurrent attachments, resident window, socket output buffer or eviction exists | +| 5 | Open | No two-process workflow, daemon operator guide or staged `0.2.0` candidate archive exists | + +## Governance Records + +| Decision | Authority | Authority evidence | Bound bytes | +| --- | --- | --- | --- | +| Acceptance | — | — | — | +| Closure | — | — | — | diff --git a/docs/plans/README.md b/docs/plans/README.md index 8f7d29fec..bafd493f2 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -16,16 +16,16 @@ its last `Closed` row identifies the last closed product baseline. ## Current Status -**Revision status:** Closed milestone product baseline; no milestone is active; no next candidate is recorded. +**Revision status:** Closed milestone product baseline; active milestone `M5` is open; no next candidate is recorded. | Field | Value | | --- | --- | | Integrated phase | Closed milestone product baseline | | Last closed product checkpoint | `M4` — 2026-09-19 | -| Blockers | None; `M4` is closed and its governance row is recorded | -| Authorized work | Explicitly authorized planning, ADR, and review work only; no product implementation until the next milestone is accepted | -| Next maintainer decision | Open the next milestone, or defer it | -| Next transition | Write the next milestone's plan pair and move it to Open | +| Blockers | `M5` is open and not accepted; the maintainer must accept its plan pair; `M5` waits on ADR 0031, ADR 0032, and ADR 0033 before the outcomes that depend on them | +| Authorized work | Explicitly authorized planning, ADR, bootstrap, and review work only; no product implementation | +| Next maintainer decision | Accept or reject the `M5` plan pair; disposition [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept), [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept), and [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | +| Next transition | Record the acceptance governance row and move `M5` to Accepted | | Validation | `bash scripts/check-bootstrap.sh` | @@ -133,6 +133,7 @@ representable. | `M2` | Closed | [concept](M2.md) | [technical depth](M2-technical.md) | [gate](M2-gate.md) | | `M3` | Closed | [concept](M3.md) | [technical depth](M3-technical.md) | [gate](M3-gate.md) | | `M4` | Closed | [concept](M4.md) | [technical depth](M4-technical.md) | [gate](M4-gate.md) | +| `M5` | Open | [concept](M5.md) | [technical depth](M5-technical.md) | — | When a plan exists, the Concept and Technical depth columns link their exact From 4e242fe169c73e64c9f9ab3e80f96aa34ee3f406 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:34:40 -0700 Subject: [PATCH 002/585] adr(M5): refresh 0031-0033 for the post-gate verification rules The three M5 decisions were written while milestone gates, locked digest tables and amendment transactions still existed. They now speak the current rules: evidence obligations live in the plan and are proved by the current suite and the two check commands, and acceptance binds the pair at the candidate the maintainer names in the governance record. Each Decision section now also states, in the Concept file where a reader meets the decision, the alternatives that were rejected and why, and the evidence class the verification guide makes its acceptance require. The alternatives themselves were already recorded in the companions; nothing new is decided here. The generation-2 schema and vector files are named at the paths they will occupy beside generation 1's. --- ...store-selection-and-migration-technical.md | 31 ++++++------- ...mon-grade-store-selection-and-migration.md | 45 ++++++++++++++----- ...tachment-residency-and-replay-technical.md | 12 +++-- ...-daemon-attachment-residency-and-replay.md | 31 ++++++++++++- ...controller-lease-and-takeover-technical.md | 5 ++- ...aboration-controller-lease-and-takeover.md | 22 +++++++++ 6 files changed, 110 insertions(+), 36 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 5f2854dcc..f8f2082b4 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -37,11 +37,12 @@ stopping the daemon and reopening that root, with the daemon or the foreground server. The daemon's operator documentation states the capacity, the refusal reason, the frame ceiling, full retention and this procedure. -Evidence for the M5 selection lives in the M5 gate, not here: a root driven -to the capacity ceiling refuses further mutation with the store's own reason -while observers stay attached and an orderly stop still succeeds, and after -that stop the foreground server reopens the same root. No new conformance -evidence is required, because the adapter and its suites are unchanged. +Evidence for the M5 selection is the M5 plan's Outcome 1 obligation, not a +second copy here: a root driven to the capacity ceiling refuses further +mutation with the store's own reason while observers stay attached and an +orderly stop still succeeds, and after that stop the foreground server reopens +the same root. No new conformance evidence is required, because the adapter +and its suites are unchanged. ### Boundary @@ -93,15 +94,10 @@ and database file format. ### Selection experiment and evidence -After M5 closes and the successor milestone's refreshed opening gate is -established red on that closed base, both candidates run in separate -isolated, disposable contract branches and task roots. The experiments may -build only the adapter slices and fixtures necessary to measure this -decision; they do not enter that milestone's Open candidate, integrate to -`main`, become accepted product bytes, or claim an inherited-gate result for -the milestone branch. The gate-first checkpoint permits bounded contract -experiments only after the one-lookahead planning restriction ends with M5 -closure. Both run: +After M5 closes, both candidates run in separate disposable branches and +worktrees. The experiments may build only the adapter slices and fixtures +necessary to measure this decision; they do not merge to `main` or become +accepted product bytes. Both run: - the shared store conformance suite that the local and in-memory adapters already pass, unchanged; @@ -183,6 +179,7 @@ Backup is a quiescent copy of the root plus the adapter's integrity check; restore reopens the copy under the same placement identity and refuses a placement mismatch exactly as resume does today. -Acceptance of the M5 selection binds this pair at an exact candidate under -the M5 gate; the successor selection is bound again, with its experiment -evidence, by the adopting milestone's gate. +Acceptance of the M5 selection binds this pair at the exact candidate the +maintainer names in the governance record. The successor selection is a second +disposition on the revised pair, recorded the same way once its experiment +evidence exists. diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index fa4597a55..642f3f8af 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -49,18 +49,41 @@ makes the durable-service claim truthful without adding an engine. **For the successor milestone, decide the selection procedure now and let its evidence fix the engine before that milestone's acceptance.** The daemon-grade store is a new adapter, `loopex_store_daemon`, behind the -unchanged private session Store ports. After M5 closes and the successor's -opening gate is refreshed red on that closed base, isolated, disposable -contract experiments on separate task roots compare a BEAM-native segmented +unchanged private session Store ports. After M5 closes, isolated, disposable +contract experiments in their own worktrees compare a BEAM-native segmented log and a SQLite-backed NIF adapter against the same conformance and -fault-injection suites. Neither experiment becomes product implementation, -enters that milestone's Open candidate, or integrates to `main`. This pair is -then revised to name the selected engine, both exact experiment revisions and -their measured evidence before independent review and acceptance of those -exact bytes. The current recommendation is the BEAM-native adapter because it -avoids a compiled dependency and VM-level NIF risk while reusing proven local -framing and repair; these are hypotheses to test, not a categorical veto of -SQLite. Any candidate that fails a required fault case is ineligible. +fault-injection suites. Neither experiment becomes product implementation or +merges to `main`. This pair is then revised to name the selected engine, both +exact experiment revisions and their measured evidence, before independent +review and acceptance of those exact bytes. The current recommendation is the +BEAM-native adapter because it avoids a compiled dependency and VM-level NIF +risk while reusing proven local framing and repair; these are hypotheses to +test, not a categorical veto of SQLite. Any candidate that fails a required +fault case is ineligible. + +**Alternatives rejected.** Deferring this decision out of M5 entirely was +rejected on 2026-09-14: the reference daemon still needs a recorded store +selection, and the local adapter's ceilings are a fact the operator must be +told rather than an absence of decision. Building the daemon-grade adapter +inside M5 was rejected because it doubles the milestone's evidence — a new +engine, its fault matrix, its migration and its rollback — without adding a +proved capability to the durable-service question M5 exists to answer. +Raising or removing the local log's 256 MiB capacity to postpone retirement +was rejected because a silently growing log trades a truthful refusal for an +unbounded replay at open. Mnesia and DETS were rejected as successor +candidates for the reasons the companion records. + +**Evidence its acceptance requires.** The M5 half is a durability claim, so +its class is process and store fault injection on the real adapter plus a +rollback proof: a root driven to capacity refuses further mutation with the +store's own reason while observers stay attached, an orderly stop still +succeeds, and the foreground server and reference CLI then reopen the same +root. No new conformance evidence is required, because the adapter and its +suites are unchanged. The successor half claims a new engine and a migration, +so its class is the full store conformance suite, the fault matrix, bounded +replay measurement, backup and restore, forward migration with interrupted- +import recovery, and safe refusal by the exact previous binary; none of it is +owed before the successor milestone's acceptance. Migration is one-way and explicit: the successor's daemon imports a local log written by the M4 foreground server, the reference CLI or the M5 daemon into diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index dfe58c141..bf812299b 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -88,8 +88,11 @@ when the client lists it, at any position, and otherwise refuses with `unsupported_generation`, leaving the connection uninitialized with no second attempt, exactly as ADR 0023 fixes for a foreground process. The successful reply carries `selected_generation`, the exact generation-2 schema digest, -the generation-2 method inventory and limits. The generation-2 schema and -vectors are canonical bytes bound by the M5 gate before acceptance; a +the generation-2 method inventory and limits. The generation-2 schema and its +vectors are new files beside generation 1's, as +`apps/loopex_protocol/priv/schema/loopex-experimental-2.json` and +`apps/loopex_protocol/priv/vectors/loopex-experimental-2.json`, reviewed with +the change that adds them; generation 1's bytes are untouched. A negotiation vector proves selection from a list that also names generation 1 and refusal of a generation-1-only list. The M4 foreground server keeps serving generation 1 only, with its one-attachment-per-process rule. @@ -187,5 +190,6 @@ unchanged; existing embedded callers retain their behavior, and the core supports independent same-session attachments. No durable record depends on residency state or on the session index. -Acceptance binds this complete pair at an exact candidate. Its evidence and -compatibility claims remain unproved until the M5 gate's required paths execute. +Acceptance binds this complete pair at the exact candidate the maintainer +names in the governance record. Its evidence and compatibility claims remain +unproved until the tests the M5 plan maps to outcomes 2 and 4 exist and pass. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 7c1724d30..8f3ddc4a6 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -73,6 +73,32 @@ unchanged. Count and byte ceilings apply together; an event that would exceed either triggers the stated detachment, eviction or refusal behavior before the ceiling is crossed. +**Alternatives rejected.** TCP on loopback has no peer-credential check and +invites remote exposure by misconfiguration. Serving generation 1 from the +daemon would need a second fencing path with no wire epoch, and its one +exclusive connection per session is what the foreground server already +provides. Keeping M4's one-attachment-per-process rule contradicts what a +daemon is for. An unbounded per-attachment queue lets one slow client grow +coordinator-adjacent memory without bound. A daemon-owned proxy fan-out would +duplicate core's cursor and queue ownership and need a second replay boundary +to preserve the subscribe/snapshot race. Promising exactly-once replay was +rejected on 2026-09-14 because at-least-once with client deduplication is the +founding contract and no other surface honors more. Removing `session.list` +was rejected the same day because an observer without filesystem access to the +root would have no way to discover sessions. The companion records each in +full. + +**Evidence its acceptance requires.** Two classes together. The transport and +its generation are a protocol claim, so they need vectors and a compatibility +proof: a generation-2 negotiation vector, refusal of a generation-1-only +initialize, and an independent client over the socket. The residency rules are +a durability and resource claim, so they need process fault injection and +bounded-resource negatives on real processes: simultaneous daemon starts, loss +of the store under a live listener, a slow observer detached at its last +emitted cursor, idle eviction and reconnect with no missing durable event, and +each count and byte ceiling refusing independently with observed process RSS +recorded beside it. + Technical depth: [Contract and evidence](0032-daemon-attachment-residency-and-replay-technical.md#technical-adr-0032-decision). @@ -89,8 +115,9 @@ still does. The public protocol remains experimental with exact-generation agreement and no mixed-generation stream promise. Rollback is the M4 foreground server on the same local store: the daemon -carries no residency state, so removing it loses nothing durable. Numbers are -safety ceilings to prove under the M5 gate, not measured service promises. +carries no residency state, so removing it loses nothing durable. The numbers +are safety ceilings the M5 tests must show are enforced, not measured service +promises. Technical depth: [Compatibility mechanics](0032-daemon-attachment-residency-and-replay-technical.md#technical-adr-0032-compatibility). diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 28265271b..58a474259 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -162,5 +162,6 @@ The M4 foreground server still has its own single connection and no daemon lease. Core session records, events and snapshots are unchanged. Removing the daemon removes the lease with it; no journal or file depends on it. -Acceptance binds this complete pair at an exact candidate. Its evidence and -compatibility claims remain unproved until the M5 gate's required paths execute. +Acceptance binds this complete pair at the exact candidate the maintainer +names in the governance record. Its evidence and compatibility claims remain +unproved until the tests the M5 plan maps to Outcome 3 exist and pass. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index 98d18d988..f59f22502 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -61,6 +61,28 @@ takeover admitted at the live daemon's steady-clock expiry, and immediate release on orderly disconnect. Writer exclusion between two daemons on one state root stays the local store's writer marker, unchanged. +**Alternatives rejected.** Putting the lease in core was rejected because the +vision keeps collaboration policy above core and another host may choose a +different rule. Last-writer-wins without an epoch was rejected because a +killed controller's late command would interleave with its successor's. A +lease with no expiry was rejected because a crashed controller would hold the +session forever. A durable lease record was rejected because after a daemon +restart every connection is gone with its socket and admission already +requires the holder connection, so durability could only preserve a counter +nothing needs. A counter-based epoch scoped to the daemon incarnation was +rejected on 2026-09-14 because a lease-owner restart under the same +incarnation would mint values already issued. + +**Evidence its acceptance requires.** This is a trust claim, so its class is +negative tests on real processes plus a security reading of the admission +path: every refusal — stale epoch, copied current epoch, non-holder +connection, released lease, expired lease, observer abort — proved before core +admission and before any session write, a controller killed mid-run fenced +after takeover, a lease-owner process restarted while the daemon and its +sockets survive, and a daemon restart leaving every session uncontrolled with +every earlier epoch refused. No durable record changes, so no migration or +rollback evidence is owed. + Technical depth: [Contract and evidence](0033-collaboration-controller-lease-and-takeover-technical.md#technical-adr-0033-decision). From 60cc344a1d873ba36fcc3e0aed18bf6951b05cb9 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:36:46 -0700 Subject: [PATCH 003/585] adr(M5): record the provider credential handoff decision ADR 0034 proposes moving the provider adapter's credential off the parent VM's process-wide environment and onto the per-invocation private channel ADR 0019 already opens, where the credential frame is sent after the child proves its nonce, codec version and build manifest digest and before the invocation frame. Why it is a decision rather than an implementation choice: it changes what the credential plane guarantees, it changes host composition, and the alternatives that buy the same test speed buy none of the property. The pair records the threat model it improves, the four rejected alternatives, the frame shape and ordering, every scrub point, and the existing credential_plane_test.exs cases each re-pointed proof maps to. It stays Proposed; acceptance and the security review are the maintainer's. --- docs/README.md | 1 + ...andoff-over-bootstrap-channel-technical.md | 176 ++++++++++++++++++ ...edential-handoff-over-bootstrap-channel.md | 114 ++++++++++++ docs/adr/README.md | 25 +-- 4 files changed, 305 insertions(+), 11 deletions(-) create mode 100644 docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md create mode 100644 docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md diff --git a/docs/README.md b/docs/README.md index b17eb5d11..69e82f475 100644 --- a/docs/README.md +++ b/docs/README.md @@ -79,6 +79,7 @@ pairing, link, review, code-documentation, and enforcement contracts. | 0031 — daemon-grade store selection and migration | [Decision](adr/0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](adr/0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | | 0032 — daemon attachment residency and replay | [Decision](adr/0032-daemon-attachment-residency-and-replay.md#concept) | [Technical depth](adr/0032-daemon-attachment-residency-and-replay-technical.md#technical-depth) | | 0033 — collaboration: controller lease and takeover | [Decision](adr/0033-collaboration-controller-lease-and-takeover.md#concept) | [Technical depth](adr/0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth) | +| 0034 — provider credential handoff over the bootstrap channel | [Decision](adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | [Technical depth](adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-depth) | An ADR pair is one decision. Its status and governance record live in the Concept file and bind both files when accepted. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md new file mode 100644 index 000000000..eaf97edb6 --- /dev/null +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -0,0 +1,176 @@ + +## Technical depth + +Concept: [Provider credential handoff over the bootstrap channel](0034-provider-credential-handoff-over-bootstrap-channel.md#concept). + + +### Contract and Evidence + +Concept: [Context and decision](0034-provider-credential-handoff-over-bootstrap-channel.md#concept-adr-0034-decision). + +### The channel and its frame + +ADR 0019's launcher already opens one private channel per invocation: a +directory mode `0700` under the caller's temporary root, a Unix-domain socket +mode `0600` inside it, and a control pipe pair to the guard shell. Only the +parent VM and the one child ever hold either end, and both are removed when +the invocation's guard completes its cleanup. + +The credential frame on that socket keeps the shape it has today. The codec +carries an eight-byte header — `LP`, version 2, a closed kind byte and a +length — and the `credential` kind admits exactly the two members `nonce` and +`credential`, with the credential a non-empty binary of at most 65,536 bytes +and the frame capped at 69,632. Nothing about the frame changes; what changes +is where its second member comes from. + +### Ordering + +The order is fixed and is the reason the credential is not folded into an +earlier frame: + +1. The parent opens the namespace and the listening socket, then spawns the + carrier and guard with `env -i` and a fixed `PATH`, passing the namespace, + the nonce, the cleanup grace, the interpreter and worker paths, the socket + path, the build manifest digest and the deadline as arguments. No + credential is among them. +2. The parent writes `bootstrap::` on the control pipe; the + guard answers `ready::::` and execs the + worker, again under `env -i`. +3. The parent accepts the socket and sends the `bootstrap` frame: nonce, + codec version and build manifest digest. +4. The child answers with a `ready` frame that must equal that payload + exactly. Until this point the child has proved nothing, and no credential + exists anywhere in the invocation. +5. Only then does the parent send the `credential` frame, from a process + spawned for that one send. +6. The `invocation` frame follows, carrying the request, its canonical bytes + and its staged digest. Possible delivery begins here, not before. + +A child that fails step 4 — a wrong manifest digest, a wrong nonce, a codec +version it does not speak, or a deadline that expires while it is still +booting — never reaches step 5. That is the property the two existing +bootstrap-refusal cases assert, and it is why the credential is not carried by +the step-3 frame. + +### Resolution and scrub points + +- **At the call.** The credential reaches the adapter as an opaque reference + in the per-invocation configuration the host already supplies to + `complete/3`. The reference is not the bytes: it is resolved exactly once, + and only where the frame is written. +- **In the sender.** The minimal credential sender keeps the shape it has + today: it is spawned for this one send, it installs its own group leader + sink so no IO request can carry anything out of it, it resolves the + reference, validates the size bound, writes the frame itself and reports a + bare `:ok` or `:error` atom to the guardian. Its closure holds the + reference, never the resolved value; the value exists only in that + process's own stack for the duration of one send, so no guardian state, no + message, no exit reason and no crash report can hold it. +- **In the parent's environment.** The adapter performs no `System.get_env/1` + for the credential. `Loopex.LLM.ReqLLM.credential_variable/0` remains as the + one name the *host* reads when it composes a runtime — the reference CLI at + start, and the real-provider lane when it names the variable in its own + failure message — and nothing in the adapter's call path reads it. + `ProviderLauncher.spawn_environment/0` keeps removing that name, and every + other known credential and loader name, from the first spawned image; the + fixed `env -i` argument lists stay as they are. +- **In the child.** Unchanged: the child receives the credential on the socket + and nowhere else. Its environment at entry is the fixed `PATH`, `LANG`, + `LC_ALL` and the two crash-dump suppressions, and ADR 0029's bounded + non-secret status is still the only failure information that leaves it. + +### Proofs + +Every case below exists today in +`apps/loopex_llm_reqllm/test/credential_plane_test.exs`. Each is re-pointed at +the per-invocation reference — the module's `setup` and the two rotation cases +stop writing the process-wide variable, and each fixture carries its own +credential — and each must hold with its assertion unchanged in meaning: + +| Claim | Case | +| --- | --- | +| Version refusal before any credential | `actual version two companion refuses version one bootstrap before readiness or credential` | +| Bootstrap refusal before any credential | `invalid protected bootstrap cannot receive a credential or dispatch` | +| Late delivery after expiry is impossible | `expired bootstrap cannot deliver a credential later or relaunch` | +| Rotation between invocations | `a child transport raise after environment rotation cannot expose its request credential` | +| Two live credentials in one VM | `one child diagnostic containing two concurrently live synthetic keys cannot escape` | +| Sink loss | `loss of child diagnostic protection cannot leak its credential` | +| One child's loss does not poison another | `losing one credential-bearing child does not poison another invocation or host logs` | +| Nothing in ordinary host messages | `ordinary guardian messages and results never carry its credential` | +| Returned reasons | `a provider error echoing the key is substituted before it is returned` | +| Child Logger forms and metadata | `ordinary and split actual child Logger messages cannot expose the credential`, `all actual child Logger message forms and metadata stay private`, `repeated credential bytes in actual child metadata cannot reach host channels`, `credential-bearing child metadata keys cannot reach host channels` | +| Crash reports | `a provider request adapter that throws cannot put the credential in a stream-server crash report`, `a provider request adapter that exits cannot put the credential in a stream-server crash report`, `an actual child report containing its own request credential stays private`, `an actual child StreamServer termination cannot forward its credential` | + +Two cases carry over unchanged from elsewhere and are not re-pointed: the +child-environment conformance case in +`apps/loopex_llm_reqllm/test/m0_child_environment_conformance_test.exs`, which +reads the child's recorded entry environment and refutes the credential name, +and the size-bound case in +`apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, which +drives the 65,536-byte ceiling. + +Two proofs are new: + +- **Parent environment.** Before, during and after a call, the parent VM's + environment holds no credential under the adapter's name or any value equal + to the credential in use. "During" is observed from inside the call, at the + point the child reports readiness. +- **Concurrent independence.** Two invocations with distinct credentials run + at once and each child records only its own; neither child, nor either + child's diagnostics, ever sees the other's. + +Both belong in `credential_plane_test.exs` beside the cases they generalise. + +### Security review + +The review is an acceptance point of M5 Outcome 6, read by someone other than +the implementer, over the exact diff. It answers: where the reference is held +between the call and the send; that the resolved value has no path into +guardian state, a message, an exit reason, a crash report, an IO request, a +file or the environment; that a failed or partial send leaves no retained +copy; that the deadline, cleanup and abandonment paths do not resurrect one; +and that a host supplying no reference is refused rather than falling back to +an ambient read. Its record is retained with the milestone's evidence. + +### Concurrency, as a measurement + +With the process-wide read gone, the twelve `loopex_llm_reqllm` modules that +declare `async: false` for that reason may declare `async: true` one at a +time, each kept only after the application's suite stays green across several +seeds, exactly as the M4 speed work converted the other twenty-one modules. +The result is recorded against the baseline in the +[verification companion](../developer/verification-technical.md#technical-verification-speed): +that application was the fast check's critical path at M4 closure, with 96% of +its time in those twelve modules. Any module that stays serial keeps its +reason recorded beside it. The measurement is evidence about the change, never +a condition a test may be weakened to meet. + + +### Compatibility and Rollback Mechanics + +Concept: [Consequences and rollback](0034-provider-credential-handoff-over-bootstrap-channel.md#concept-adr-0034-consequences). + +Adapter-internal. The `Loopex.Model` callbacks, the public protocol and its +generations, public events, snapshots, artifacts, the executor protocol and +every durable record are untouched, so no vector, schema or migration is +affected. The private codec's version and frame kinds are unchanged, and a +child built from the same manifest digest behaves identically; the build +manifest is not revised by this decision. + +The one visible change is host composition: a host that starts a runtime with +this adapter supplies a credential reference with the call. The reference CLI +and the real-provider lane keep reading `LOOPEX_PROVIDER_API_KEY` where they +compose, so an operator's setup is unchanged and the release check's +credential frame is unchanged. An embedder that relied on the adapter reading +the environment for it must pass the reference instead; that is the refusal +path, not a silent fallback, and it is stated in the operator and developer +documentation the milestone updates. + +Rollback is reverting the adapter change. Nothing durable, no root and no +protocol generation records which mechanism delivered a credential to a +process that has since exited, so a rollback needs no migration and leaves no +trace to repair. + +Acceptance binds this complete pair at the exact candidate the maintainer +names in the governance record. Its claims remain unproved until the tests the +M5 plan maps to Outcome 6 exist and pass and the security review is recorded. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md new file mode 100644 index 000000000..955dfdc2d --- /dev/null +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -0,0 +1,114 @@ + +## Concept + +Technical depth: [Credential handoff mechanics](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-depth). + +- **Status:** Proposed +- **Date:** 2026-09-19 +- **Decision owner:** Maintainer +- **Supersedes:** nothing; refines where ADR 0019's credential-bearing + invocation reads its credential from +- **Prerequisite for:** M5 Outcome 6 + + +### Context and Decision + +ADR 0019 gave the reference provider adapter a private, one-invocation child +process: a namespace of its own, a nonce, a private Unix-domain socket, a +build manifest digest the child must echo before it is trusted, and an +environment scrubbed down to a fixed `PATH` so the child inherits no ambient +secret. The credential already crosses that private channel as its own frame +rather than through the child's environment. + +One thing was left on the process-wide plane. The adapter resolves the +credential by reading the operating-system environment variable +`LOOPEX_PROVIDER_API_KEY` from the parent VM, inside the call, at the moment +it is about to send the frame. The parent VM's environment is a single global +slot, so the credential of whichever invocation wrote it last is the +credential every concurrent invocation sends. That has two costs. It is a +weaker property than the rest of the plane: a secret that has to sit in a +process-wide slot for the duration of every call is reachable by anything in +the VM that can read the environment, and it is exactly the kind of ambient +authority the runtime refuses everywhere else. And it forces serialisation: +the twelve heavy `loopex_llm_reqllm` test modules each install their own +canary in that slot, so two of them running at once would hand each other's +canary to each other's child. The +[verification companion](../developer/verification-technical.md#technical-verification-speed) +measured the result at M4 closure — that application is the critical path of +the fast check, 96% of its time sits in those twelve modules, and no further +test change shortens the check while the slot is shared. + +**Decide that the credential is a per-invocation input, delivered on the +child's private channel and never resident in any process-wide slot.** The +host supplies the credential to the adapter with the call, as an opaque +reference it owns; the adapter resolves that reference to bytes only inside +the minimal sender process that writes the credential frame, and only after +the child has proved its nonce, codec version and build manifest digest. The +adapter reads no environment variable for the credential. Nothing else +changes about where the credential may go: it is never in the child's +environment, never in argv, never in the journal, a public event, a snapshot, +a progress item or a diagnostic, never in a process state, a message, an exit +reason or a crash report, and never written to a file. The operator still +names the credential once, to the host, through the same environment variable; +the host reads it where it composes the runtime and holds a reference from +then on, so the variable is a configuration input rather than a live transport +for every call. + +**Alternatives rejected.** Keeping the environment variable and buying the +speed by sharding the provider suite across test VMs was rejected: it is +cheaper for speed alone and buys nothing for the credential plane, and it +answers a defect in the product with an arrangement of the tests. A credential +file in the invocation's namespace was rejected because it makes the secret +observable to anything that can read the directory, adds a removal step whose +failure is a leak, and survives a crash that the channel does not. Passing an +already-open file descriptor to the child over the socket was rejected because +it adds a platform-specific mechanism to a channel that already carries bounded +frames, without removing a single place the credential can be observed. Widening +the existing bootstrap frame to carry the credential alongside the manifest +digest was rejected because the child must prove its identity before it is +handed a secret, and that frame is sent before the child has proved anything. + +**Evidence its acceptance requires.** This is a trust claim, so its class is +negative tests plus a security review, with a real-provider proof for the path +the release check already runs. Every credential-plane negative that M0 to M2 +established is re-pointed at the new handoff and must hold with its assertion +unchanged in meaning; the parent VM's environment is proved empty of the +credential before, during and after a call; two invocations running at once +are proved unable to observe each other's credential; and a named reviewer +reads the handoff — resolution point, frame ordering, failure paths and every +place a value could be retained — and records the reading with the milestone. +The real-provider lane in `bash scripts/check-release.sh` proves the path +still reaches a real provider. The concurrency result is a measurement +recorded beside the M4-closure baseline, not a pass condition. + +Technical depth: [Contract and evidence](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-decision). + + +### Consequences, Compatibility and Rollback + +The credential plane gets the property the rest of ADR 0019's design already +has: the secret exists in the parent only inside one short-lived process that +does nothing but send it, and in the child that needs it. Two invocations in +one VM become independent, so the twelve provider test modules can run +concurrently and the fast check stops being pinned by that application. Host +composition gains one explicit input: a host that starts a runtime with this +adapter says which credential reference the adapter is to use, instead of +relying on the VM's environment being right at call time. A host that supplies +no reference gets the adapter's ordinary refusal to dispatch, which is what a +missing environment variable produces today. + +Nothing public changes. This is adapter-internal: no Model callback, no public +event, snapshot, artifact, wire method or protocol generation, no durable +record, and no change to what the child may receive, from whom, or when. The +credential-size bound and the refusal behaviour ADR 0019 fixed stay as they +are. Rollback is reverting the adapter change; no data, root or protocol +depends on which mechanism delivered a credential to a process that has since +exited. + +Technical depth: [Compatibility mechanics](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-compatibility). + +## Governance Record + +| Decision | Authority | Authority evidence | Bound bytes | +| --- | --- | --- | --- | +| Acceptance | — | — | — | diff --git a/docs/adr/README.md b/docs/adr/README.md index 4746e93c7..8c144fd20 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -43,6 +43,7 @@ a decision adds a new record rather than rewriting the old one. | 0031 | Daemon-grade store selection and migration | Proposed | [Decision](0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | | 0032 | Daemon attachment residency and replay | Proposed | [Decision](0032-daemon-attachment-residency-and-replay.md#concept) | [Technical depth](0032-daemon-attachment-residency-and-replay-technical.md#technical-depth) | | 0033 | Collaboration: controller lease and takeover | Proposed | [Decision](0033-collaboration-controller-lease-and-takeover.md#concept) | [Technical depth](0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth) | +| 0034 | Provider credential handoff over the bootstrap channel | Proposed | [Decision](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | [Technical depth](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-depth) | 0001 and 0002 were the prerequisites that unblocked the first milestone candidate; the [plans register](../plans/README.md) records current status. @@ -160,14 +161,16 @@ gate record and does not accept the M4 plan pair or gate. The protocol/interaction proposals were renumbered from the old draft's 0019/0020 because those numbers are now accepted M2 decisions. -0031, 0032 and 0033 are the three Proposed M5 prerequisites: the daemon's -store selection, which for M5 is the existing local adapter with its -documented limits and retirement procedure and for the successor milestone -the daemon-grade adapter chosen by contract experiments plus its migration; -daemon attachment residency and at-least-once replay over the -generation-2-only Unix-domain-socket transport with bounded session pages; -and the collaboration rule of one in-memory controller lease with fresh -per-grant epochs, observers and takeover. They were proposed with the Open M5 -lookahead on 2026-09-14 and revised twice that day on independent review; -they accept nothing, and each must be accepted before the outcome that -depends on it is implemented. +0031 to 0034 are the four Proposed M5 prerequisites: the daemon's store +selection, which for M5 is the existing local adapter with its documented +limits and retirement procedure and for the successor milestone the +daemon-grade adapter chosen by contract experiments plus its migration; daemon +attachment residency and at-least-once replay over the generation-2-only +Unix-domain-socket transport with bounded session pages; the collaboration +rule of one in-memory controller lease with fresh per-grant epochs, observers +and takeover; and the provider adapter's credential handoff, moved off the +parent VM's process-wide environment onto the per-invocation private channel +the launcher already opens. The first three were proposed with the Open M5 +plan on 2026-09-14 and revised twice that day on independent review; 0034 +follows the maintainer's outcome of 2026-09-19. They accept nothing, and each +must be accepted before the outcome that depends on it is implemented. From 1861b835aede8cf67b80aed04fbb48e19fa2a747 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:42:28 -0700 Subject: [PATCH 004/585] plan(M5): rewrite the pair for the current milestone structure The pair was drafted while per-milestone verification machinery still existed. Both halves are rewritten to the shape the milestone and verification guides now define, keeping the substance: the daemon, the socket, the controller lease, residency and replay, the two-client workflow and the source-only 0.2.0 release candidate. The pair is one review unit, so it moves in one change. Concept half. Outcomes are a numbered table whose last column names the test file or demonstration that witnesses each claim. Design Decisions is a new section mapping each outcome to the decision it rests on. A new verification section maps every outcome to the three stages and states which extra checks each changed boundary selects. Rollout and compatibility is its own section. The progress section states what each lifecycle transition records. The spent conditions about reconstructing an opening on a closed M4 base are removed; the two revisions of 2026-09-14 and the outcome of 2026-09-19 are kept as the record of what the maintainer decided. Technical half. Prerequisites declare ADR 0034 alongside 0031 to 0033 and name the implementation each blocks. The holder-transaction table is replaced by the ordinary reviewed changes that do the same work: the dependency-budget inventory with the application that needs it, and the VERSION move before closure. The opening-probe description becomes the first integrated workflow to build early. Evidence gains the per-outcome test paths, the boundary selections, the closure runs, and the documentation the milestone must update. A new table lists every number the plan commits to beside the decision it comes from, so plan and decision cannot drift. Substance added: Outcome 6 gains its witnesses, its evidence row and its own workstream. Outcome 2 and Outcome 5 name the independent Node client and the generation-2 vectors rather than a Python client that does not exist. The register's derived status capsule is updated to exactly what mix loopex.status derives now that the pair declares a fourth prerequisite. --- docs/plans/M5-technical.md | 510 ++++++++++++++++++++----------------- docs/plans/M5.md | 497 ++++++++++++++++++++++-------------- docs/plans/README.md | 4 +- 3 files changed, 581 insertions(+), 430 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 5d88214f2..0c6f8780d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1,85 +1,34 @@ ## Technical depth -Concept: [Durable service](M5.md#concept). - - -## Normative Technical Envelope +Concept: [Durable service purpose and outcomes](M5.md#concept). ### Prerequisites and Acceptance Points Concept: [Scope](M5.md#concept-plan-scope). -Concept: [non-goals](M5.md#concept-plan-non-goals). - -The Open M5 planning bytes were drafted on M4's accepted governance checkpoint -`6f973f774a403f76330058e3d0a59f7b83e038f1`, but inherited M1 and M2 -gates were unavailable there. The M4-specific waiver and deferral do not -authorize this opening. M4 is Accepted and remains the sole implementation -authority; these M5 bytes confer none. Before M5 can be accepted, M4 must be -Closed and integrated; reconstruct M5's branch-only opening checkpoint on -that exact inherited-green product base, re-prove every inherited gate green -and its own distinct red on it, bind the generation-2 schema and vector -bytes, prove their fixture shape and digest integrity on both locked -toolchain pairs, and obtain fresh exact-SHA review. -At final acceptance all inherited gates are green and the M5 boundary remains -truthfully red for the missing daemon. No draft candidate from the unavailable -opening is eligible for acceptance or integration. - -M5 accepts three decisions before dependent work: - -| Decision | Owner and acceptance point | Effect | +Concept: [Non-goals](M5.md#concept-plan-non-goals). + +M5 waits on four decisions. Each is accepted before the implementation that +depends on it, not before unrelated work, and none may be outstanding at +closure. The repository status check reads the links in this section, so a +decision named only in prose declares nothing. + +| Decision | Acceptance point | What its acceptance settles | | --- | --- | --- | -| [**ADR 0031**](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Maintainer, before M5 acceptance; binds the local-adapter selection, its exact limits and the retirement procedure, and fixes the successor's selection procedure without running it | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and root retirement documented; the daemon-grade adapter, its experiments and migration reserved for the successor | -| [**ADR 0032**](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Maintainer, before M5 acceptance; must bind every residency number below, the generation-2-only negotiation rule, the marker-first startup order and the `session.list` page contract | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's daemon methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, race-free attach with at-least-once contiguous delivery, a resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages | -| [**ADR 0033**](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Maintainer, before M5 acceptance; must fix the lease terms below | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds the holder connection, held state, unexpired term and writer epoch, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | - -ADR 0031's daemon-grade adapter, contract experiments and migration belong to -the successor milestone and bind nothing in M5; only its local-adapter -selection and documented limits are M5 prerequisites. - -**Residency and lease profile (proposed, bound at acceptance).** 64 -attachments per session and 512 per daemon, refused independently; a -1,024-durable-event core queue per attachment and a 4 MiB encoded-byte -daemon-owned socket output buffer per connection, detaching at the last -completely emitted cursor before the next event would exceed either bound; a -4,096-event and 16 MiB encoded-byte daemon-owned resident window per session -with store replay behind it, which on the local adapter always succeeds; 512 -MiB total retained encoded durable-event bytes across all output buffers and -resident windows in one daemon, with pressure detached or evicted before that -total is exceeded; eviction after ten minutes without consumption, naming the -resumable cursor; `session.list` pages of at most 256 entries with an exact -continuation cursor; a thirty-second lease renewed every ten seconds, -takeover admitted at expiry with no further grace, release on orderly -disconnect; the ADR 0023 frame ceiling unchanged. These are retained-payload -ceilings, not an exact BEAM RSS promise. Measure and report actual process -RSS under the maximum attachment count and at payload pressure separately. - -**Daemon launch inputs.** State root, socket path, placement identity, policy -module with identity and revision, provider, executor, ArtifactStore and -project resource snapshot are fixed when the daemon starts. No connection -replaces any of them; a client may select admitted resources and answer -interactions exactly as under M4, and may acquire control only through the -lease. - -**Holder transactions.** M5 changes bytes that Closed gates bind in two -places, both after acceptance: - -| Artifact | Holders | Restriction today | Planned change | Phase | Route and checks | -| --- | --- | --- | --- | --- | --- | -| `apps/loopex/lib/mix/tasks/loopex.deps_budget.ex`, `apps/loopex/test/deps_budget_test.exs`, `apps/loopex_daemon` | M1 (the application is unbound M5 product) | Ten-application inventory after M4; the daemon application absent | Eleven-application inventory, the daemon as a client-role application depending inward on core, protocol and composition, negative tests, and the minimal application in the same proposal | B | One Closed-M1 v2 proposal `A` carrying M1's next gate generation, both dependency-oracle artifacts and the minimal application, following the M1 Amendment 7 pattern M4's phase B reuses; review and accept `A`; governance-only `R` | -| `VERSION`, application versions, and every version-aware runner and verifier M4's closure made version-aware | M1, M2, M3, M4 | 0.1.0 after M4 closure | 0.2.0 | C | Separately approved version transition; v2 for Closed M1, M2, M3 and M4 in register order, then Accepted M5 last through its own v1 amendment and rebind | - -`.tool-versions` is unchanged. The generation-2 schema and vectors are new -files; M4's bound generation-1 bytes are not touched, so M4 is not a holder -there. M5 adds no external dependency. Phase B and C bindings settle before -the rejoin or closure candidate that depends on them; closure cannot be -recorded while any is stale. - -M4 owns interactions, transfers, the foreground server and observability; an -inherited defect is reproduced at the exact base and repaired at its owner, -and a daemon workaround cannot conceal it. +| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 1 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and operator root-retirement procedure documented; the daemon-grade adapter, its experiments and its migration reserved for the successor milestone | +| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or the core attachment change lands, so before workstreams 2 and 4 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | +| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 3 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5 | The credential as a per-invocation input resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; no environment read in the adapter's call path; the re-pointed credential-plane proofs and the security review as acceptance points | + +ADR 0031's daemon-grade adapter, its contract experiments and its migration +belong to the successor milestone and bind nothing in M5; only its +local-adapter selection and documented limits are M5 prerequisites. + +M4 owns interactions, transfers, the foreground server and observability. An +inherited defect is reproduced at the exact base and repaired at its owner; a +daemon workaround cannot conceal one. ### Ownership, Decision Owners, and Rejoin Barriers @@ -88,206 +37,293 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, race-free attach barrier and cursor, independent concurrent attachments to the same session, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | -| `loopex_protocol` | Generation-2 DTOs, validators, schema and vectors | Daemon behaviour or lease semantics | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` refusal and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | -| `loopex_daemon` | Marker-first process and socket lifetime, peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session stop, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity or any durable record | +| `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session stop, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity or any durable record | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | -| TypeScript consumer | Socket connection, observer following and takeover presentation | Normative semantics | - -The ordered rejoin is prerequisite decisions → holder transaction for the one -minimal application → narrow core multi-attachment support → marker-first -daemon lifetime and socket over the local adapter → collaboration lease and -takeover → residency, replay and backpressure → two-process workflow with the -reference CLI and TypeScript consumer → integrated audit → independent -review. Prove lifetime, refusal of a second daemon at the marker, shutdown on -store loss, capacity refusal, reopening under the foreground server after an -orderly stop, independent simultaneous core attachments, -snapshot-then-contiguous delivery, stale-epoch refusal, takeover and -cross-process abort before the client workflow rejoins. - -Use the existing command identity for every mutating method; request -identities never enter journals. `session.create` has no existing session or -epoch to authorize: it creates an uncontrolled session, after which a client -may attach before or after acquiring control, while `session.resume` requires -acquiring control first. Existing-session mutation requires control. The -lease record lives in the daemon's memory, keyed by session, for the daemon -process's lifetime; one owner process per session serializes its lease -transitions with its admission handoff, and a restart of that owner leaves -the session uncontrolled. For every existing-session mutation, the daemon -checks the requesting connection identity, current epoch, held state and -unexpired term together before forwarding to core; an epoch alone is not -authority, and every epoch is minted fresh at grant so no earlier value can -match. Attach reuses the runtime's cursor transaction; the core keeps -attachments independent and its event-count queues, while the daemon -buffers encoded output, evicts above it and never reads coordinator state. -Cross-process abort forwards the existing durable `session.abort` command; -no daemon-side cancellation path exists. +| `loopex_llm_reqllm` | The credential handoff, its sender, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, or anything outside the adapter | +| `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | + +**Rejoin order.** Prerequisite decisions, then the one new application and the +narrow core attachment change, then marker-first daemon lifetime and the +socket over the local adapter, then collaboration and takeover on that base, +then residency, replay and backpressure, then the two-process workflow with +the reference CLI and the independent Node client, then the documentation and +the source-archive proof, then independent review of the closure candidate. + +Prove lifetime, refusal of a second daemon at the marker, shutdown on store +loss, capacity refusal, reopening under the foreground server after an orderly +stop, independent simultaneous core attachments, snapshot-then-contiguous +delivery, stale-epoch refusal, takeover and cross-process abort before the +client workflow rejoins. Workstream 5, the credential handoff, is independent +of every other workstream: it touches `apps/loopex_llm_reqllm` and the host +composition sites that read the credential variable, shares no file with the +daemon work, and may land at any point after ADR 0034 is accepted. + +Parallel writers take one worktree each over these non-overlapping paths, and +one integrator owns rejoin, conflicts and post-rejoin verification, as the +[milestone guide](../developer/milestones-technical.md#technical-milestones-develop) +sets out. + +**Semantics the rejoin must preserve.** Use the existing command identity for +every mutating method; request identities never enter journals. +`session.create` has no existing session or epoch to authorize: it creates an +uncontrolled session, after which a client may attach before or after +acquiring control, while `session.resume` requires acquiring control first. +Existing-session mutation requires control. The lease record lives in the +daemon's memory, keyed by session, for the daemon process's lifetime; one +owner process per session serializes its lease transitions with its admission +handoff, and a restart of that owner leaves the session uncontrolled. For +every existing-session mutation the daemon checks the requesting connection +identity, the current epoch, the held state and the unexpired term together +before forwarding to core; an epoch alone is not authority, and every epoch is +minted fresh at grant so no earlier value can match. Attach reuses the +runtime's cursor transaction; core keeps attachments independent and keeps its +event-count queues, while the daemon buffers encoded output, evicts above its +own bounds and never reads coordinator state. Cross-process abort forwards the +existing durable `session.abort` command; no daemon-side cancellation path +exists. ### Evidence Obligations and Mapping Concept: [Outcomes](M5.md#concept-plan-outcomes). -| Outcome | Mandatory proof beyond a unit test | +| Outcome | What must be proved, beyond ordinary unit tests | | --- | --- | -| 1 | Real daemon process per state root; sessions progress with zero attachments; orderly stop releases the writer marker and records nothing false; abrupt kill followed by restart recovers every session under the same placement identity with no duplicate effect; simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket; Store-child failure closes the listener and every connection before exit; a root driven to the 256 MiB log capacity refuses further mutation with `store_capacity_exceeded` while observers stay attached and an orderly stop still succeeds; `session.list` pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index; after an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay; session open and stop through the socket only | -| 2 | Raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its generation, and a generation-1-only initialize is refused with nothing created; identical durable identities for the same command corpus through facade, foreground server and socket; foreign-uid peer refused before initialize; frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons; client disconnect recorded as transport loss with no cancellation and no interaction change | -| 3 | One lease per session in daemon memory with observers attached; connection identity, epoch, held state and unexpired term checked together before core admission or durable write, including a known current epoch sent by an observer; takeover only after release or expiry with a fresh epoch minted before the successor's first command; killed controller fenced and its late commands refused; the per-session lease owner crashing and restarting while the daemon and client sockets survive, with the previous holder's delayed command refused and no epoch ever reused; daemon restart leaving every session uncontrolled with every earlier epoch refused; controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome; no control from content, metadata, answers or attachment order | -| 4 | Several core attachments to one session remain independent when one detaches or backpressures; snapshot anchored at the committed sequence then contiguous at-least-once buffered and live delivery across the window boundary with no gap; slow observer detached at its last emitted cursor while the controller and other attachments continue; per-session and per-daemon limits refusing independently; idle eviction and reconnect with no missing durable event and any duplicate deduplicated by session ID, sequence and event ID; retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings enforced in the daemon-owned stages, separately exercising 512 attachments and maximum-sized output records, with observed process RSS recorded; progress coalesced or dropped with counted drops and no journal delay | -| 5 | From a fresh extraction of the exact source candidate, an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the TypeScript consumer as observer, kills the controller, takes over from the observer and aborts cross-process work; the attended real-provider selector runs from the extracted tree; every daemon boundary emits ADR 0030 spans and a daemon-scoped trace session captures identities only; every operator and developer documentation file receives an exact-source final documentation audit and independent finding disposition; the full gate's staged source archive of the exact candidate, with source `VERSION` exactly `0.2.0`, extracts, compiles and carries the attended workflow, and its report is retained | - -| 6 | Provider child receives its credential over the bootstrap channel: the parent VM's environment holds no credential before, during or after a call (asserted on the parent and on a child probe); a child of one invocation cannot observe another invocation's credential when two run at once; the crash-report, late-delivery, sink-loss, rotation and version-refusal cases of `credential_plane_test.exs` pass against the channel handoff with their assertions unchanged in meaning; a security review of the handoff is recorded with the milestone; the provider suite runs its modules concurrently and its measured duration is recorded beside the M4-closure baseline (~250 s serial on the Mac) | - -The final documentation audit enumerates every tracked file beneath -`docs/operator/` and `docs/developer/` in the exact closure source tree, -including new, materially updated and reviewed-unchanged files. Retain one -row per file with path, source SHA, file SHA-256, role for its reader, audit -disposition and finding resolution. Inspect content for consistency with the -daemon, socket, controller and observer rules, residency, restart and -local-store limit behavior, the source-only `v0.2.0` release sequence, -current M5 information, relevance, working links and directory-index routing -where applicable, and stale foreground-only claims. -The exact seven-row Documentation Obligations table names required material -updates; this broader audit is required even for files outside that table. -Automated status and link checks contribute evidence but cannot replace the -per-file content judgment. The independent closure reviewer examines the -complete inventory and every finding disposition at the exact source SHA; -unresolved blocking or high-severity documentation findings block closure. - -The opening runner binds one real behavioral red for outcomes 1 and 2. Local -positive controls prove same-VM attachment replay and cross-process recovery -after Store release. Its fixture then starts a separate daemon operating-system -process through -`Loopex.Daemon.start_link(state_root: root, runtime_options: runtime_opts)`; -the daemon alone owns the session Store and session. The fixture root is short -enough for ADR 0032's default `/daemon.sock`. Two independent -client processes use only ADR 0023 JSONL over that socket: the first -initializes generation 2, creates an uncontrolled session, attaches, acquires -control and commits a deterministic turn with its writer epoch; the second -initializes and attaches while the daemon still owns the session. Its -correlated snapshot has top-level `event_cursor` equal to -`snapshot.event_sequence`, at or beyond the committed tail. On the opening -base no daemon start or socket exists, so the declared behavior is red. Green -requires that daemon-owned socket path and those correlated protocol records -to complete. Second-daemon writer exclusion is proved separately under -Outcome 1. Before acceptance, bind -that real opening red, the exact selectors and witness names, the -generation-2 schema and vector bytes, the client interpreter pins, the exact -residency, encoded-byte and lease numbers and the fail-closed routing. After -acceptance, implement the daemon, the CLI commands and the consumer workflow; -every lane must pass before closure. A daemon that proxies several socket -connections to one replaceable core attachment cannot pass, because -independent concurrent attachments, lifetime with zero attachments, fencing -after a real kill and cross-process abort are required. - -Every protected selector uses the existing authoritative standalone ExUnit -channel. Preserve the inherited repair manifest rather than re-listing old -case counts in this plan. The complete gate runs inherited predecessors, -protected selectors, whole suite, language clients and retained-evidence -validation, with M3-style checkpoint and full modes and one decisive named -witness per clause. Real provider cases live in separate files. Under the -same preparation rule M3 recorded, future test bodies are written with -implementation; a missing witness is never a pass. - -Apply the M3 integrated audit and the M4 self-audit to the daemon, the socket, -the CLI commands and the recovery path. Test every lifetime, lease and -residency cut and each decoder-side negative at the receiver. Run actual -Darwin floor/current and Linux current lanes early. A repeated finding class -triggers a full adjacent-path audit. Final exact-source evidence and -independent review remain mandatory; no fixed review-round limit or -retry-to-green rule. +| 1 | A real daemon operating-system process per state root. Sessions progress with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart recovers every session under the same placement identity with no duplicate effect. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses further mutation with `store_capacity_exceeded` while observers stay attached and an orderly stop still succeeds. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. Session open and stop through the socket only | +| 2 | A raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its own generation, and a generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 3 | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 4 | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 5 | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. Every daemon boundary emits its ADR 0030 spans and a daemon-scoped trace session captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | +| 6 | The parent VM's environment holds no credential under the adapter's name, and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment case in `m0_child_environment_conformance_test.exs` and the 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` carry over unchanged. A security review by someone other than the implementer is recorded. The provider suite's modules run concurrently and the measured duration is recorded beside the M4-closure baseline | + +**Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every +merge needs green in hosted CI, M5 selects exactly these, from the +[selection table](../developer/verification.md#concept-verification-selection): + +- generation 2's schema and vectors select the independent client workflows + (`--only node_client`, part of `bash scripts/check-release.sh`) and an + update to `docs/developer/compatibility-surfaces.md` in the same change; +- a new or changed operator command — `loopex daemon`, `loopex attach`, + `loopex sessions` — selects its operator page in the same change and its + workflow in the release check; +- Outcome 6 is provider and credential handling, so it selects + `bash scripts/check-release.sh` and its real-provider cases; +- Outcome 6 also changes an operating-system process boundary with the same + spawn, control-pipe and cleanup shape the executor's has, so the touched + cases run under `bash scripts/fixtures/pinned-load.sh` on a Linux host: + the test VM and eight busy-loop hogs pinned to four cores with + `taskset -c 0-3`, one process writing 8 MiB with `dd oflag=dsync` in a loop, + thirty runs, any run past its 60 s deadline counted as a hang, and no + failure and no hang admitted; +- the Store and recovery are touched only through the daemon's use of the + unchanged adapter, so nothing more runs and the review confirms the + fault-injection and old-reader cases still cover the change; +- `.tool-versions` and the toolchain floor are unchanged, so nothing selects + the floor row for that reason. + +**Closure runs.** At the candidate: hosted CI's green fast check on that +commit is the current-pair evidence; `bash scripts/check.sh` runs once under +the floor pair, `mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash +scripts/check.sh` with its own `MIX_BUILD_ROOT`; and +`bash scripts/check-release.sh` runs once on the current pair with the +provider credential and the pinned Node version in +`scripts/fixtures/m4/client-toolchain.txt`. Each run's revision, platform, +toolchain, result and measured duration is retained on +`docs/evidence/M5-closure-runs.md`, indexed in `docs/evidence/README.md`, +together with the Outcome 6 security review and the attended demonstration's +provider and model identities. Complete logs stay with the maintainer. + +**Documentation the milestone must update.** New: `docs/operator/daemon.md` +and the developer pair `docs/developer/daemon.md` and +`docs/developer/daemon-technical.md`. Materially updated: +`docs/operator/app-server.md`, `docs/operator/coding-sessions.md`, +`docs/operator/runtime.md`, `docs/operator/observability.md`, +`docs/operator/tools-and-policy.md`, the operator pair +`docs/operator/how-a-run-works.md` and +`docs/operator/how-a-run-works-technical.md`, the developer pairs +`docs/developer/app-server-protocol.md` and its companion, +`docs/developer/observability.md` and its companion, +`docs/developer/architecture.md` and its companion, +`docs/developer/runtime-and-embedding.md`, +`docs/developer/agent-loop-and-tools.md`, +`docs/developer/compatibility-surfaces.md`, +`docs/developer/agent-context-map.md`, the indexes +`docs/operator/README.md`, `docs/developer/README.md`, `docs/README.md` and +`README.md`, and `CHANGELOG.md`. Outcome 6 adds the operator's credential +sentence and the developer note on host composition to the pages that describe +provider configuration. Every other tracked file under `docs/operator/` and +`docs/developer/` is read at the candidate and left unchanged only +deliberately. + +**Test honesty.** Future test bodies are written with their implementation; a +missing witness is never a pass. Real-provider cases live in their own files +under the `real_provider` tag. A daemon that proxies several socket +connections to one replaceable core attachment cannot satisfy Outcome 4, +because independent concurrent attachments, lifetime with zero attachments, +fencing after a real kill and cross-process abort are each required +separately. Build the first integrated workflow early — one daemon process, +two independent socket clients, one creating and driving a session and one +attaching while the daemon still owns it, with the second client's correlated +snapshot carrying a top-level `event_cursor` equal to +`snapshot.event_sequence` at or beyond the committed tail — then add the +boundary and failure cases as the implementation reaches them. ### Compatibility -Concept: [Scope](M5.md#concept-plan-scope). +Concept: [Rollout and compatibility](M5.md#concept-plan-rollout). The `v0.2.0` source tag identifies a numbered release, not a compatibility -freeze. All surfaces remain experimental. The socket reuses ADR 0023's -framing, handshake, records and limits unchanged; generation 2 is additive -over generation 1's method set with the exact-generation rule, a -generation-1 client sees no daemon method and no lease field, the daemon -refuses a generation-1-only initialize, and the foreground server keeps -serving generation 1 unchanged. The private journal, its adapter and its -format are unchanged; the embedded API, public events, snapshots, artifact -formats and executor protocol are unchanged. Source VERSION is distinct from -protocol generation, provider build and schema digest. +freeze; all surfaces remain experimental. The socket reuses ADR 0023's +framing, handshake, records and limits unchanged. Generation 2 is additive +over generation 1's method set under the exact-generation rule: a generation-1 +client sees no daemon method and no lease field, the daemon refuses a +generation-1-only initialize, and the foreground server keeps serving +generation 1 unchanged. No mixed-generation stream is promised. The private +journal, its adapter and its format are unchanged; the embedded API, public +events, snapshots, artifact formats and the executor protocol are unchanged. +Source `VERSION` is distinct from protocol generation, provider build and +schema digest. + +Outcome 6 changes no public surface. The `Loopex.Model` callbacks, the private +provider codec's version and frame kinds, the build manifest and ADR 0019's +process topology are all unchanged. Its one compatibility effect is on host +composition: an embedder that relied on the adapter reading the environment +for it supplies a credential reference with the call instead, and gets the +adapter's ordinary refusal to dispatch rather than a silent fallback if it +does not. ### Migration and Rollback -Concept: [Scope](M5.md#concept-plan-scope). +Concept: [Rollout and compatibility](M5.md#concept-plan-rollout). No journal migration exists in M5. The daemon reads and writes the same local -log the M4 foreground server and CLI write, under the same placement -identity, so a state root moves between the daemon and the foreground -surfaces by stopping one and starting the other. Prove that an orderly daemon -stop releases the writer marker and that the foreground server and the CLI -then resume a daemon-created session with identical replay. A root that -reaches the local log's 256 MiB capacity is retired, not migrated: stop the -daemon, move the root aside, start a fresh root; a session in a retired root -is resumed only by reopening that root. Rollback is stopping the daemon: -removing it restores the M4 foreground server and CLI on the same root with -no durable dependency on residency, index or lease state. Restore floor, -version and inventory protections through governed transactions. No in-place -downgrade, installed-data migration or service-manager claim. +log the M4 foreground server and the CLI write, under the same placement +identity, so a state root moves between the daemon and the foreground surfaces +by stopping one and starting the other. Prove that an orderly daemon stop +releases the writer marker and that the foreground server and the CLI then +resume a daemon-created session with identical replay. + +A root that reaches the local log's 256 MiB capacity is retired, not migrated: +stop the daemon, move the root aside, start a fresh root. A session in a +retired root is reached only by reopening that root. + +Rollback to `0.1.0` is stopping the daemon. Removing it restores the M4 +foreground server and the CLI on the same root with no durable dependency on +residency, index or lease state, because none of those is persisted. A +daemon-owned root is an ordinary local root the moment the daemon releases its +writer marker; a root whose marker is still held by a dead daemon is released +by the adapter's existing liveness-probe discipline and its +`store_writer_active` and `store_writer_unverifiable` refusals, which M5 does +not change. Outcome 6's rollback is reverting the adapter change; nothing +durable records which mechanism delivered a credential to a process that has +since exited. No in-place downgrade, installed-data migration or +service-manager claim exists. ### Packaging -Concept: [Scope](M5.md#concept-plan-scope). +Concept: [Rollout and compatibility](M5.md#concept-plan-rollout). Add exactly one application: `loopex_daemon`, the eleventh, with role `:client`, depending inward on core, protocol and composition and reusing the -foreground server's protocol mapping. The application inventory and role -rules in `loopex.deps_budget.ex` change under M1's transaction. M5 adds no -external dependency. No transport library, socket abstraction layer or -service-manager integration enters any application; the socket is the +foreground server's protocol mapping. The application inventory and the role +rules in `apps/loopex/lib/mix/tasks/loopex.deps_budget.ex` and its cases in +`apps/loopex/test/deps_budget_test.exs` change in the same reviewed change +that adds the application, and `mix loopex.deps_budget` proves the direction. +M5 adds no external dependency. No transport library, socket abstraction layer +or service-manager integration enters any application; the socket is the runtime's own `gen_tcp` local address family. -Supply `loopex daemon`, `loopex attach` and `loopex sessions` in the -reference CLI, extend the TypeScript consumer to connect over the socket and -to follow and take over, and reuse the M4 Elixir and Python conformance -clients for generation 2. Pin Node and Python execution versions in -`scripts/fixtures/m5/client-toolchain.txt`; the runner verifies the pinned -executables before any client lane and reports absence or mismatch as -UNAVAILABLE. At the separately approved version transition set source -VERSION and application versions to 0.2.0; the full gate's report validator -accepts exactly `0.2.0` and nothing else. The full gate stages a tar source -archive from its exact committed candidate, extracts it outside the checkout, -compiles it, and runs the attended two-process selector from the extracted -tree following the operator guide; that staged, release-ready archive report -is the last Purpose obligation. Gate green and independent exact-SHA closure -review precede an explicit combined closure and release/tag disposition. -Record the closure transition under that authority, obtain its required -read-only exact-SHA review, and integrate that same reviewed commit to -`main` without rewrite. Release completion then follows closure: create one -annotated `v0.2.0` tag on precisely that integrated commit, and run the -post-tag check, which verifies the tag object is annotated, `v0.2.0^{commit}` -is the reviewed integration commit and is reachable from `main`, that -`git show :VERSION` is exactly `0.2.0`, and that the source -archive was generated from that commit; retain the archive SHA-256, source -commit and tree, and tag object identity. That completion is required by -this plan and is not a closure condition. Do not move the tag or publish -packages, binaries, installers or service units. +Supply `loopex daemon`, `loopex attach` and `loopex sessions` in the reference +CLI, and extend the client in `clients/node` to connect over the socket, to +follow as an observer and to take over. It stays a plain client with no build +step, package manifest or dependency, as the maintainer decided for M4 on +2026-09-15. The Node version stays pinned in +`scripts/fixtures/m4/client-toolchain.txt` and `scripts/check-release.sh` +continues to verify it before any client runs; the release check's application +list gains `loopex_daemon` in the same change that adds its release cases. + +`VERSION` and the application versions move to `0.2.0` in an ordinary +reviewed commit before closure, as the +[milestone guide](../developer/milestones-technical.md#technical-milestones-release) +sets out; every application reads it at compile time. The release-ready source +archive is staged from the exact committed candidate with `git archive`, +extracted outside the checkout, compiled, and used to run the two-process +workflow from the extraction following the operator guide; its SHA-256, source +commit and tree are retained with the closure runs. The release itself is one +annotated `v0.2.0` tag on the integrated closure commit, created on the +maintainer's separate decision, after which the tag object is verified +annotated, `v0.2.0^{commit}` is the reviewed integration commit and reachable +from `main`, and `git show :VERSION` is exactly `0.2.0`. Do not +move the tag, and publish no package, binary, installer or service unit. ### Proportional Minimalism Budget Concept: [Scope](M5.md#concept-plan-scope). -One application, one socket listener, one narrow core concurrent-attachment -change, one in-memory lease record and admission check, one resident window -and eviction policy, one per-connection output buffer, one session index -with bounded pages, three CLI commands and the consumer's socket mode -justify growth. No lease, transport, byte limit or residency policy in core; -no second loop, event dispatcher, cancellation path or protocol codec; no +The smallest sufficient system wins, and each addition below names what it +unifies and why direct code is insufficient. One application, because a +daemon is a host and a host is an application. One socket listener, one narrow +core concurrent-attachment change, one in-memory lease record and one +admission check, one resident window and eviction policy, one per-connection +output buffer, one session index with bounded pages, three CLI commands and +the Node client's socket mode. Outcome 6 adds no module and no abstraction: it +changes where one value is resolved and deletes an environment read. + +Nothing else. No lease, transport, byte limit or residency policy in core; no +second loop, event dispatcher, cancellation path or protocol codec; no transport registry, plugin socket layer, generic service framework, store -adapter, control store or durable daemon record; no daemon-side session -state beyond the lease, index and residency facts it holds in memory. -Implement lifetime, transport and collaboration once against the local -adapter. Raw line count is a review signal; behaviour and measured limits -govern. - +adapter, control store or durable daemon record; no daemon-side session state +beyond the lease, the index and the residency facts it holds in memory. +Implement lifetime, transport and collaboration once, against the local +adapter. + +**The numbers M5 commits to.** Every one comes from an accepted or proposed +decision named above; M5 introduces none of its own. + +| Ceiling | Value | Source | +| --- | --- | --- | +| Log capacity per state root | 256 MiB, refused as `store_capacity_exceeded` | ADR 0031 | +| Frame ceiling on any single store record | 4 MiB | ADR 0031 | +| Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | +| Attachments per session | 64 | ADR 0032 | +| Attachments per daemon | 512 | ADR 0032 | +| Core event-count queue per attachment | 1,024 events | ADR 0032 | +| Daemon socket output buffer per connection | 4 MiB encoded | ADR 0032 | +| Resident window per session | 4,096 events and 16 MiB encoded | ADR 0032 | +| Aggregate retained encoded events per daemon | 512 MiB | ADR 0032 | +| Idle time before eviction | 10 minutes | ADR 0032 | +| `session.list` page | at most 256 entries, `limit` in 1 to 256 | ADR 0032 | +| Socket path bound | the platform's, 104 bytes on Darwin and 108 on Linux, refused at start as `socket_path_too_long` | ADR 0032 | +| Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | +| Lease term | 30 seconds | ADR 0033 | +| Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | +| Takeover grace beyond expiry | none | ADR 0033 | +| Writer epoch | opaque, at most 64 bytes, at least 128 bits of fresh randomness, minted per grant | ADR 0033 | +| Credential size | 1 to 65,536 bytes | ADR 0019, unchanged by ADR 0034 | +| Credential frame cap | 69,632 bytes | ADR 0019, unchanged by ADR 0034 | + +Count and byte ceilings apply together: an event that would exceed either +triggers the stated detachment, eviction or refusal before the ceiling is +crossed. These are retained-payload ceilings, not an exact BEAM RSS promise; +measure and report actual process RSS under the maximum attachment count and +at payload pressure separately. + +**Verification cost.** The +[verification guide](../developer/verification.md#concept-verification-speed) +sets the target that checking work takes a small share of development time +while every real guarantee keeps a check that would fail if it were broken. M5 +adds one application's suite to the fast check and must not lengthen the +critical path: `loopex_llm_reqllm` was that path at M4 closure, and Outcome 6 +is what unpins it. New daemon tests that wait on a real-time bound inject that +bound where it is armed and assert the production default once, as M4's speed +work established; a test whose claim is the real duration is tagged +`long_bound` and moves to the release check. Raw line count is a review +signal; behaviour and the measured limits above govern. diff --git a/docs/plans/M5.md b/docs/plans/M5.md index f299ce119..facfcb0ef 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -3,57 +3,58 @@ Technical depth: [Durable service mechanics](M5-technical.md#technical-depth). - -## Normative Concept Envelope - ### Purpose -Let independent client processes share one durable session without any of -them owning its lifetime. A local daemon owns every session in a state root: -it keeps sessions running while no client is connected, serves several client +Let independent client processes share one durable session without any of them +owning its lifetime. A local daemon owns every session in a state root: it +keeps sessions running while no client is connected, serves several client processes over a Unix-domain socket with the same protocol the M4 foreground -server speaks, lets exactly one client drive while others observe, survives -the driver's crash with an explicit takeover, replays snapshot and cursor to a -reconnecting client contiguously and at least once with no gap, cancels work -across processes, and does all of it on the existing local store adapter, -which the daemon holds for its process's lifetime within that adapter's +server speaks, lets exactly one client drive while the others observe, +survives the driver's crash with an explicit takeover, replays snapshot and +cursor to a reconnecting client contiguously and at least once with no gap, +cancels work across processes, and does all of it on the existing local store +adapter, which it holds for its process's lifetime within that adapter's documented limits. -Complete M5 as an operator-usable, source-only `0.2.0` release candidate: -from the exact source candidate, an operator follows the documented setup, -starts the daemon, and drives one session from two real client processes -with their own inputs, and the full gate proves a staged, release-ready -source archive of that candidate. Closure review and an explicit combined -closure and release/tag disposition then lead to an integrated closure -commit on `main`. Creating the annotated `v0.2.0` tag on that commit and -verifying its archive is the release completion this plan requires after -closure; it is not a closure condition, because closure cannot wait on a tag -that closure itself authorizes. + +Finish M5 as an operator-usable, source-only `0.2.0` release candidate. From a +fresh extraction of the exact closure candidate an operator follows the +documented setup, starts the daemon, and drives one session from two real +client processes with their own inputs; a release-ready source archive of that +candidate extracts, compiles and carries that same workflow. The release +itself — one annotated `v0.2.0` tag on the integrated closure commit — is the +maintainer's separate decision after closure, as the +[milestone guide](../developer/milestones.md#concept-milestones-release) sets +out. It is not a closure condition, because closure cannot wait on a tag that +closure authorizes. + +M5 also settles one debt M4's verification work left explicitly open. The +provider adapter resolves its credential by reading a process-wide environment +variable inside each call, which is both a weaker property than the rest of +its credential plane and the reason twelve heavy provider test modules cannot +run concurrently. M5 moves that handoff onto the private per-invocation +channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above the core. The core's attachment machinery gains narrow support for several -independent attachments to one session; it gains no lease, transport or -second loop. No new store engine enters M5: ADR 0031 selects the existing -local adapter for this release, with its 256 MiB log ceiling, full-history -retention and root-retirement procedure documented, and reserves the -daemon-grade adapter, its selection experiments and migration for the -successor milestone. +independent attachments to one session; it gains no lease, transport or second +loop. ### Outcomes -| # | Outcome | Evidence class | Gate selector | +| # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root: sessions run while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon recovers every session under the same placement identity, a second daemon on the same root loses at the store writer marker before touching the socket, losing the store closes the socket and every connection, a root at the local log's capacity refuses further mutation truthfully while observers stay attached, sessions are listed in bounded pages, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault tests with real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | -| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated and a generation-1-only client refused, the same durable identities as facade and foreground server, owner-only peer access and the same framing refusals | Differential conformance across facade, foreground server and socket; negative transport and generation-2 Python-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_daemon/test/python_client_conformance_test.exs` | -| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Collaboration and fencing tests with real killed processes | `apps/loopex_daemon/test/collaboration_test.exs` | -| 4 | Several core attachments coexist without replacement; daemon attach, replay, residency and backpressure are race-free and bounded: snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with exact reconnect, retained encoded-event bytes within the daemon-owned bounds, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | -| 5 | From a clean source extraction and operator-supplied inputs, two real client processes, the reference CLI and the TypeScript consumer, drive one daemon-owned session through controller work, observer following, controller kill and takeover, with every daemon boundary emitting the accepted telemetry spans; a final exact-source audit covers every operator and developer documentation file, including relevant unchanged files, before closure review; and the full gate stages, extracts and proves a release-ready `0.2.0` source archive of the exact candidate | Operator setup smoke, integrated two-process workflow, attended real-provider demonstration, per-file final documentation audit with independent finding disposition, and the staged release-ready source archive report | `apps/loopex_daemon/test/multi_client_workflow_test.exs` | -| 6 | The provider adapter hands the credential to each provider child per invocation over the child's private bootstrap channel instead of the process-wide environment variable the child inherits today, so no provider child can receive another invocation's credential, the parent VM's environment never carries it, the existing credential-plane proofs (crash reports, late delivery, sink loss, rotation, version refusal) hold under the new handoff, and the provider test modules that today serialise on that one variable run concurrently | Credential-plane negative tests re-pointed at the channel handoff, an environment-scrub proof on parent and child, a security review of the handoff, and the measured provider suite with its modules concurrent | `apps/loopex_llm_reqllm/test/credential_plane_test.exs` | +| 1 | A daemon owns session lifetime for a state root: sessions run while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon recovers every session under the same placement identity, a second daemon on the same root loses at the store writer marker before touching the socket, losing the store closes the socket and every connection, a root at the local log's capacity refuses further mutation truthfully while observers stay attached, sessions are listed in bounded pages, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated and a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | +| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | +| 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with exact reconnect, retained encoded-event bytes within the daemon-owned bounds, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | +| 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with every daemon boundary emitting the accepted telemetry spans; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, compiles and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and the parent VM's environment never carries it; every existing credential-plane negative proof holds against the new handoff; and the provider test modules that serialise on that one variable today run concurrently | Negative tests for trust, a recorded security review, the real-provider lane in the release check, and the measured provider suite with its modules concurrent | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | -Technical depth: [Evidence mapping](M5-technical.md#technical-plan-evidence). +Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). ### Scope @@ -63,116 +64,85 @@ collaboration lease, its session index and the local store root it holds for its process's lifetime. Core owns durable session truth and supports several independent attachments to one session through its existing race-free attach barrier and dispatcher. Hosts still supply workspace, identity, policy, -provider configuration and project resources when the daemon starts; no -client connection replaces any of them, and the daemon's configuration may -narrow who may take control but never widens what host policy allows. +provider configuration and project resources when the daemon starts; no client +connection replaces any of them, and the daemon's configuration may narrow who +may take control but never widens what host policy allows. The socket reuses ADR 0023's framing, initialize handshake, request, admission, snapshot, event and progress records and limits unchanged, and serves generation `loopex.experimental/2` only, which adds `session.list`, -`session.stop`, `daemon.status`, the two control methods and the -writer-epoch field, and lifts the one-attachment-per-process rule to -residency limits. A client offering only generation 1 is refused at -initialize; generation-1 clients keep the M4 foreground server, whose wire -and behavior do not change. Attach is the runtime's race-free cursor -transaction, and delivery is contiguous and at least once: gaps are -forbidden, duplicates are permitted, and a client deduplicates by session -ID, event sequence and event ID as the vision requires. The daemon adds a -bounded resident window, daemon-owned bounded socket output buffers, -detachment at the last emitted cursor and idle eviction; on the local adapter -every durable event stays replayable until the operator retires the root, so -`cursor_expired` remains a defined protocol response no M5 path produces. -The credential handoff to a provider child moves from the process-wide -environment variable to the per-invocation bootstrap channel the launcher -already opens for the nonce and build manifest. The maintainer set this as an -M5 baseline on 2026-09-19: the environment handoff makes the twelve heavy -provider test modules serial, which pins the fast check near the provider -suite's length, and a credential that lives in the parent VM's environment is -a weaker property than one that exists only on a private channel to the child -that needs it. The change stays inside the credential plane: what a child may -receive, from whom and when does not widen; every negative proof M0–M2 -established is carried to the new mechanism, not relaxed. It is scheduled as -its own workstream with its own security review, and its measured result is -part of closure. -The residency and lease numbers are exact in the technical envelope and bound -at acceptance with the accepted ADRs 0032 and 0033: 64 attachments per -session, 512 per daemon, a 1,024-event core queue and 4 MiB socket output -buffer per attachment, a 4,096-event and 16 MiB per-session resident window, -512 MiB of aggregate retained encoded event bytes, ten idle minutes, 256 -sessions per list page, and a thirty-second lease renewed every ten seconds. - -Session creation makes an uncontrolled session; a client then acquires -control before existing-session mutation. Exactly one controller holds a -daemon-owned lease per session; every other attachment is read-only. For an -existing session, the daemon admits a mutation only when its requesting -connection is the holder of a held, unexpired lease and carries its current -writer epoch. Takeover is explicit, only after release or expiry, and mints -a fresh epoch before the successor's first command. The lease lives in the -daemon's memory for the daemon process's lifetime, never in the session -journal or any durable record; every writer epoch is minted fresh and never -reused, so a restart of the daemon or of a session's lease owner leaves that -session uncontrolled with every earlier epoch stale, and the core keeps -mandating no lease. Cancellation crosses processes because the core owns -dispatch: the current controller's `session.abort` cancels work an earlier -controller started, with the truthful two-phase outcome the core already -commits. +`session.stop`, `daemon.status`, the two control methods and the writer-epoch +field, and lifts the one-attachment-per-process rule to residency limits. A +client offering only generation 1 is refused at initialize; generation-1 +clients keep the M4 foreground server, whose wire and behavior do not change. +Attach is the runtime's race-free cursor transaction, and delivery is +contiguous and at least once: gaps are forbidden, duplicates are permitted, +and a client deduplicates by session ID, event sequence and event ID as the +vision requires. The daemon adds a bounded resident window, daemon-owned +bounded socket output buffers, detachment at the last emitted cursor and idle +eviction; on the local adapter every durable event stays replayable until the +operator retires the root, so `cursor_expired` remains a defined protocol +response no M5 path produces. + +Session creation makes an uncontrolled session; a client then acquires control +before existing-session mutation. Exactly one controller holds a daemon-owned +lease per session; every other attachment is read-only. For an existing +session, the daemon admits a mutation only when its requesting connection is +the holder of a held, unexpired lease and carries its current writer epoch. +Takeover is explicit, only after release or expiry, and mints a fresh epoch +before the successor's first command. The lease lives in the daemon's memory +for the daemon process's lifetime, never in the session journal or any durable +record; every writer epoch is minted fresh and never reused, so a restart of +the daemon or of a session's lease owner leaves that session uncontrolled with +every earlier epoch stale, and the core keeps mandating no lease. Cancellation +crosses processes because the core owns dispatch: the current controller's +`session.abort` cancels work an earlier controller started, with the truthful +two-phase outcome the core already commits. The daemon runs every session on the existing local store adapter, selected -for this release by ADR 0031: one state root, the local log the M4 -foreground server and CLI already write, and the local writer marker held by -the daemon from before the socket is bound until the daemon exits. The -adapter's limits are the daemon's limits and the operator documentation -states them: a hard 256 MiB log capacity refused as `store_capacity_exceeded`, -a 4 MiB frame ceiling, full-history retention with no compaction, and full -replay at open; a root at capacity is retired by stopping the daemon, moving -the root aside and starting a fresh root. No new store adapter, journal -format version, migration or backup tooling enters M5. After an orderly -daemon stop the foreground server and the CLI reopen the same root and -sessions under the same placement identity, which is also M5's rollback. The -daemon-grade adapter, its selection experiments and its migration are the -successor milestone's first decision under the same ADR. +for this release by ADR 0031: one state root, the local log the M4 foreground +server and CLI already write, and the local writer marker held by the daemon +from before the socket is bound until the daemon exits. The adapter's limits +are the daemon's limits and the operator documentation states them: a hard +256 MiB log capacity refused as `store_capacity_exceeded`, a 4 MiB frame +ceiling, full-history retention with no compaction, and full replay at open. A +root at capacity is retired by stopping the daemon, moving the root aside and +starting a fresh root. No new store adapter, journal format version, migration +or backup tooling enters M5. + +The credential handoff to a provider child moves from the process-wide +environment variable the adapter reads inside each call to the per-invocation +private channel the launcher already opens for the nonce and the build +manifest. The maintainer set this as an M5 outcome on 2026-09-19 for two +reasons. A credential that must sit in the parent VM's environment for the +duration of every call is a weaker property than one that exists only on a +private channel to the child that needs it; and that shared slot is what makes +the twelve heavy provider test modules serial, which leaves the provider suite +as the fast check's critical path. The change stays inside the credential +plane: what a child may receive, from whom and when does not widen, and every +negative proof M0 to M2 established is carried to the new mechanism rather +than relaxed. It is its own workstream with its own security review, and its +measured result is part of closure. M4's observability continues without change: every daemon boundary emits the ADR 0030 spans, and a trace session scoped to the daemon's runtime captures identities only. The socket path is bounded by the platform and refused when too long; the socket is owner-only and a foreign peer is refused before -initialize; the daemon never runs as a service manager unit by itself and the -documented launch is a foreground command an operator or their service -manager runs. - -The release is one annotated `v0.2.0` tag on the exact reviewed closure -integration commit on `main`, and a source archive of that tagged commit. The -full gate retains a report for a staged candidate archive, extracts it, -compiles it and runs the attended two-process workflow from that extraction; -that staged proof is the last Purpose obligation. After gate green and -independent closure review, a combined explicit closure and release/tag -disposition authorizes the closure transition, integration, tag creation and -post-tag archive verification. The tag and its verification complete the -release after closure; the full gate cannot claim the future tag exists, and -closure does not wait for it. The release publishes no Hex package, binary, -installer or service unit and freezes no public protocol or embedded API. - -At the final source candidate, audit every tracked file under -`docs/operator/` and `docs/developer/` for consistency with M5, relevance, -links and indexing where applicable, and stale foreground-only claims. New, -materially updated -and reviewed-unchanged files all receive a recorded per-file disposition; -the independent closure reviewer examines the inventory and any finding -resolution. The seven-row gate table still names the exact files M5 must -materially update. Release instructions describe the required `v0.2.0` tag -and archive workflow without claiming a tag before it exists. +initialize; the daemon never runs as a service-manager unit by itself, and the +documented launch is a foreground command an operator or their service manager +runs. -Technical depth: [Prerequisites](M5-technical.md#technical-plan-prerequisites). +At the closure candidate, every tracked file under `docs/operator/` and +`docs/developer/` is read for consistency with M5, for relevance, links and +indexing, and for stale foreground-only claims — including the files M5 leaves +unchanged. The documentation the milestone changed is part of the closure +candidate, as it is for every milestone. -Technical depth: [ownership](M5-technical.md#technical-plan-ownership). +Technical depth: [Prerequisites and acceptance points](M5-technical.md#technical-plan-prerequisites). -Technical depth: [compatibility](M5-technical.md#technical-plan-compatibility). +Technical depth: [Ownership and rejoin order](M5-technical.md#technical-plan-ownership). -Technical depth: [rollback](M5-technical.md#technical-plan-migration). - -Technical depth: [packaging](M5-technical.md#technical-plan-packaging). - -Technical depth: [minimalism](M5-technical.md#technical-plan-minimalism). +Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan-minimalism). ### Non-Goals @@ -187,34 +157,186 @@ transport; no multi-host or multi-user identity, tenancy or authorization beyond the socket's owner-only peer rule; no trusted extension activation, isolated hands, ACP mapping, public-protocol freeze, hosted store, Hex package, binary, installer or service-manager integration. Generation 2 adds -daemon methods and lease fields only; no other protocol breadth. Those -capabilities retain their vision barriers and require their own evidence. +daemon methods and lease fields only; no other protocol breadth. Outcome 6 +changes where a credential is resolved and nothing about what a child may do +with it: no new credential scope, no host credential store, no change to the +`Loopex.Model` callbacks or to ADR 0019's process topology. Those capabilities +retain their vision barriers and require their own evidence. + +Technical depth: [Deferral acceptance points](M5-technical.md#technical-plan-prerequisites). -Technical depth: [Acceptance boundaries](M5-technical.md#technical-plan-prerequisites). - + +### Design Decisions + +Four decisions are proposed with this plan. Each is accepted before the +implementation that depends on it, not before unrelated work. + +| Decision | What it settles | Outcomes that wait on it | +| --- | --- | --- | +| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and operator root-retirement procedure documented; the daemon-grade adapter, its selection experiments and its migration are the successor milestone's | 1, 5 | +| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | +| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the adapter reads no environment variable for it | 6 | + +Three decisions of M4's remain load-bearing and are not reopened: ADR 0023 +fixes the protocol M5's generation 2 extends, ADR 0030 fixes the telemetry +inventory every daemon boundary emits, and ADR 0019 fixes the provider process +topology ADR 0034 refines. + + +### How Each Outcome Is Verified + +M5 runs through the three stages in the +[verification guide](../developer/verification.md#concept-verification-stages); +it adds no per-milestone runner and no check of its own. + +**Change.** Every merge to `main` needs `bash scripts/check.sh` green in +hosted CI on that branch and an independent read of the diff. The fast check +is credential-free and needs no network, so it is what proves outcomes 1, 2, 3 +and 4 in full — daemon lifetime and store fault injection on real local +processes, socket framing and generation negotiation, lease admission and +fencing after real kills, and the residency and delivery bounds — and it +proves the parent-environment, concurrency-independence and re-pointed +negative cases of Outcome 6. Beyond the fast check, a change selects only what +its boundary asks for: + +| The change touches | What it selects in addition | +| --- | --- | +| The wire protocol: generation 2's schema and vectors | The independent client workflows (`--only node_client`, part of the release check), and `docs/developer/compatibility-surfaces.md` updated in the same change | +| The CLI or the operator-facing daemon commands | The operator page that describes the behavior updated in the same change; a changed operator command also selects its workflow in the release check | +| Provider or credential handling: Outcome 6 | `bash scripts/check-release.sh`, the real-provider cases | +| The provider launcher's operating-system boundary: the child's spawn, its control pipe and its cleanup | `bash scripts/fixtures/pinned-load.sh` over the touched cases on a Linux host: thirty runs under four pinned cores and load, no failure and no hang | +| Durable records, the Store, recovery | Nothing more to run; the review confirms the fault-injection and old-reader cases still cover the change | +| A port behaviour or an adapter of one | Nothing more to run; the review confirms the port's conformance suite still runs against every adapter | +| Documentation only | `bash scripts/check.sh --docs` | + +The toolchain floor and `.tool-versions` are unchanged by M5, so no change +selects the floor row for that reason. + +**Close.** At one commit on `main` where every outcome maps to tests, retained +evidence or a demonstration: hosted CI's green run on that candidate is the +current-pair fast check; `bash scripts/check.sh` runs once under the floor +toolchain pair; `bash scripts/check-release.sh` runs once with the provider +credential and pinned Node, which is where the attended two-process +demonstration of Outcome 5, the fresh-source build and Outcome 6's +real-provider lane are proved. Each run's revision, platform, toolchain, +result and measured duration is retained on `docs/evidence/M5-closure-runs.md` +with the security review of Outcome 6. An independent reviewer reads the +candidate; the maintainer closes it. + +**Release.** The release is one annotated `v0.2.0` tag on the exact integrated +closure commit, reusing the closure evidence because the source is unchanged, +plus a verified source archive of that commit. It publishes no Hex package, +binary, installer or service unit, and freezes no public protocol or embedded +API. + + +### Rollout and Compatibility + +`v0.2.0` identifies a numbered source release, not a compatibility freeze; all +surfaces stay experimental. Generation 2 is additive over generation 1's +method set under ADR 0023's exact-generation rule: the daemon serves +generation 2 only and refuses a generation-1-only initialize with nothing +created, while the foreground server keeps serving generation 1 with its +wire, its one-attachment rule and its behavior unchanged. No mixed-generation +stream is promised. + +An operator running `0.2.0` runs the daemon on the local adapter and lives +within its limits: 256 MiB of log per state root, a 4 MiB frame ceiling, full +history with no compaction and full replay at open. Reaching capacity is a +truthful `store_capacity_exceeded` refusal, never silent loss, and the +documented recovery is to retire the root — stop the daemon, move the root +aside, start a fresh one — after which a session in the retired root is +reached only by reopening that root. + +The private journal, its adapter and its format are unchanged, so moving a +state root between the daemon and the foreground surfaces is stopping one and +starting the other. That is also the rollback: dropping back to `0.1.0` means +stopping the daemon and using the M4 foreground server and CLI on the same +root, which nothing durable prevents, because no journal record depends on the +lease, the session index or any residency state. Outcome 6 changes no public +or durable surface at all; its one visible effect is that a host composing +this adapter supplies a credential reference with the call. + +Technical depth: [Compatibility mechanics](M5-technical.md#technical-plan-compatibility). + +Technical depth: [Migration and rollback](M5-technical.md#technical-plan-migration). + +Technical depth: [Packaging mechanics](M5-technical.md#technical-plan-packaging). ## Workstreams -After M4 closes, reconstruct M5's valid opening checkpoint and settle the -three prerequisite decisions before M5 acceptance. After acceptance, land the -one application through its holder transaction and the narrow core -attachment change, then build daemon lifetime and socket over the local -adapter, prove collaboration and replay on that base, and join the -two-process workflow with the reference CLI and the TypeScript consumer -before method breadth. Reuse M4's focused checkpoints, clause witnesses and -integrated self-audit; full inherited checks remain at contract moments and -scheduled CI. No second loop, lease in core or transport registry. +Six workstreams. The first four are ordered by what each needs to exist +before it can be proved; the fifth is independent of all of them; the sixth +runs last because it describes what the others built. + +1. **The daemon.** One new application, `loopex_daemon`: marker-first startup + on the local adapter, session lifetime with zero attachments, orderly stop + and abrupt death, restart recovery under the same placement identity, the + session index and its bounded pages, shutdown on store loss, capacity + refusal, and reopening under the foreground server after an orderly stop. +2. **The socket transport.** The listener, its owner-only peer check and path + bound, ADR 0023's framing and records reused, generation 2's schema and + vectors beside generation 1's, negotiation and the generation-1-only + refusal, and the differential conformance that the facade, the foreground + server and the socket produce the same durable identities. +3. **The collaboration lease.** The in-memory lease record, the per-session + owner that serializes lease transitions with admission handoff, the + combined holder, epoch, state and term check, explicit takeover with a + fresh epoch, fencing after a real kill, and cross-process abort through the + core's existing durable command. +4. **Core concurrent attachments.** The narrow core change that lets distinct + attachments to one session coexist without implicit replacement, and the + daemon-side residency above it: the resident window, per-connection output + buffers, detachment at the last emitted cursor, idle eviction and the + aggregate byte ceiling. +5. **The credential handoff.** ADR 0034's change to the provider adapter, the + re-pointed credential-plane proofs, the two new proofs, its own security + review by someone other than its implementer, and the measured effect on + the provider suite once its modules can run concurrently. It touches no + daemon code and shares no file with the other workstreams. +6. **Documentation and the `0.2.0` release candidate.** The operator daemon + guide and the developer daemon pair, the updates M5 forces on the existing + operator and developer pages, the changelog and the indexes, the `VERSION` + change to `0.2.0`, and the release-ready source archive proved by extracting + it, compiling it and running the two-process workflow from the extraction. + +Parallel work uses one worktree per writer over the non-overlapping paths the +technical companion assigns, with one integrator owning the rejoin. + +## Progress and Evidence + +The register in [docs/plans/README.md](README.md) owns M5's lifecycle state, +and each transition records exactly one thing: `Open` records that this pair +exists and is indexed with every row below reading `Open`; `Open` to +`Accepted` records the maintainer's disposition in the Acceptance row — +authority, durable authority evidence and the accepted candidate; `Accepted` +to `In progress` records that implementation has begun against the accepted +pair, after which these rows change as outcomes are proved; `In progress` to +`In review` records that a closure candidate exists and an independent +reviewer is reading that exact candidate; `In review` to `Closed` records the +maintainer's closure disposition in the Closure row, naming the reviewed +candidate, with every row below resolved. A row is updated in the same change +that adds the tests it names. + +| # | State | Evidence | +| --- | --- | --- | +| 1 | Open | No daemon exists. Session lifetime with zero attachments, marker-first startup, store-loss shutdown, capacity refusal, bounded listing and reopening under the foreground server are its separate witnesses | +| 2 | Open | No socket transport exists; generation 2 has no schema or vectors yet | +| 3 | Open | No controller lease, writer epoch or takeover exists above core | +| 4 | Open | Core replaces an existing same-session attachment today; no independent concurrent attachments, resident window, socket output buffer or eviction exists | +| 5 | Open | No two-process workflow, daemon operator guide or `0.2.0` source archive exists | +| 6 | Open | The adapter resolves the credential from the parent VM's environment inside each call, and the twelve heavy provider modules declare `async: false` for that reason | **Revision of 2026-09-14 (first).** On the independent review of -`dc81212360327caa7e8b0ed371cb5ed531b960d9`, the maintainer decided to narrow -this Open plan in three ways. The daemon-grade store, its selection -experiments and its migration leave M5 for the successor milestone, so M5 -adds one application. The daemon serves generation 2 only, so no -generation-1 exclusive lease exists. The controller lease is daemon memory, -so no durable daemon-control store exists. The rung question needs none of -the three, each doubled evidence without adding a proved capability, and the -daemon on the local adapter already reopens under the foreground server after -an orderly stop. +`dc81212360327caa7e8b0ed371cb5ed531b960d9`, the maintainer narrowed this plan +in three ways. The daemon-grade store, its selection experiments and its +migration leave M5 for the successor milestone, so M5 adds one application. +The daemon serves generation 2 only, so no generation-1 exclusive lease +exists. The controller lease is daemon memory, so no durable daemon-control +store exists. The rung question needs none of the three, each doubled evidence +without adding a proved capability, and the daemon on the local adapter +already reopens under the foreground server after an orderly stop. **Revision of 2026-09-14 (second).** On the independent review of `6e8319da299dc92ef0c2441da8e0443262292fb8`, the maintainer accepted every @@ -224,45 +346,38 @@ promise would contradict the vision and no other surface honors it. ADR 0031 returns as an M5 prerequisite, selecting the existing local adapter with its 256 MiB ceiling, full retention and root-retirement procedure documented, rather than being deferred outright: the reference daemon runs on an -ADR-selected store and the roadmap ties operational claims to store -selection, so the daemon needs a recorded selection even when the selected -adapter is the existing one; the daemon-grade adapter and migration stay with -the successor. The closure and release cycle is broken by ending the last -Purpose outcome at the staged, release-ready source archive and making the -tag a post-closure release completion. The `cursor_expired` witness is -removed because the local adapter retains everything until the root is -retired, so no truthful path reaches it. `session.list` is kept with an exact -bounded page contract over a daemon-owned index, because observers without -filesystem access to the root would otherwise have no discovery; removal was -the cheaper alternative and was rejected for that reason. Writer epochs are -minted fresh per grant so a lease-owner restart can never reuse one; startup -acquires the store writer marker before touching the socket and store loss -closes the listener; byte limits live in daemon-owned socket output buffers -while core keeps its event-count queues; the report validator requires -exactly `0.2.0`; and wording now says the daemon process's lifetime and -names the reused and added protocol parts precisely. - -These Open M5 planning bytes were drafted on branch `m5` from the integrated -M4 acceptance checkpoint `6f973f774a403f76330058e3d0a59f7b83e038f1`. -M4 is Accepted and remains the sole implementation authority; these bytes -grant no M5 implementation authority and do not establish a valid lookahead -opening. The inherited M1 and M2 gates were unavailable on this base, and -the M4-specific waiver and deferral do not authorize an M5 exception. Before -M5 acceptance, reconstruct its branch-only opening checkpoint on M4's exact -Closed, integrated, inherited-green product base, re-prove every inherited -gate green and M5's distinct behavioral red, settle prerequisites, and obtain -fresh exact-SHA review. No candidate produced by this unavailable opening is -eligible for acceptance or integration. - -## Progress and Evidence - -| # | State | Evidence | -| --- | --- | --- | -| 1 | Open | No daemon exists; the opening probe observes that independent socket clients cannot initialize and attach to a daemon-owned live session. Marker-first startup, store-loss shutdown, capacity refusal, bounded listing and reopening under the foreground server are separate Outcome 1 witnesses | -| 2 | Open | No socket transport exists; generation 2 is not defined in canonical bytes | -| 3 | Open | No controller lease, writer epoch or takeover exists above core | -| 4 | Open | Core currently replaces an existing same-session attachment; no independent concurrent attachments, resident window, socket output buffer or eviction exists | -| 5 | Open | No two-process workflow, daemon operator guide or staged `0.2.0` candidate archive exists | +ADR-selected store and the roadmap ties operational claims to store selection, +so the daemon needs a recorded selection even when the selected adapter is the +existing one. The closure and release cycle is broken by ending the last +Purpose obligation at the release-ready source archive and making the tag a +post-closure release completion. The `cursor_expired` witness is removed +because the local adapter retains everything until the root is retired, so no +truthful path reaches it. `session.list` is kept with an exact bounded page +contract over a daemon-owned index, because observers without filesystem +access to the root would otherwise have no discovery; removal was the cheaper +alternative and was rejected for that reason. Writer epochs are minted fresh +per grant so a lease-owner restart can never reuse one; startup acquires the +store writer marker before touching the socket and store loss closes the +listener; byte limits live in daemon-owned socket output buffers while core +keeps its event-count queues; and the wording now says the daemon process's +lifetime and names the reused and added protocol parts precisely. + +**Outcome of 2026-09-19.** The maintainer added Outcome 6, the provider +credential handoff, with its own workstream, its own security review as an +acceptance point, and its measured concurrency result as part of closure. It +is proposed as [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept). + +**Restated for the post-M4 structure, 2026-09-19.** M4 closed and `v0.1.0` is +tagged, so the conditions this plan carried about reconstructing an opening on +a closed M4 base are spent and are removed. The per-milestone verification +machinery M0 to M4 ran under was retired with M4, and this pair was rewritten +to the structure the +[milestone guide](../developer/milestones.md#concept) and the +[verification guide](../developer/verification.md#concept) now define: the +plan says what will be proved and by which tests, the current suite proves it, +and the two check commands and the maintainer decide. The purpose, the +outcomes and the scope are unchanged by that rewrite except for Outcome 6, +which the maintainer added on the same day. ## Governance Records diff --git a/docs/plans/README.md b/docs/plans/README.md index bafd493f2..ff2cb422f 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -22,9 +22,9 @@ its last `Closed` row identifies the last closed product baseline. | --- | --- | | Integrated phase | Closed milestone product baseline | | Last closed product checkpoint | `M4` — 2026-09-19 | -| Blockers | `M5` is open and not accepted; the maintainer must accept its plan pair; `M5` waits on ADR 0031, ADR 0032, and ADR 0033 before the outcomes that depend on them | +| Blockers | `M5` is open and not accepted; the maintainer must accept its plan pair; `M5` waits on ADR 0031, ADR 0032, ADR 0033, and ADR 0034 before the outcomes that depend on them | | Authorized work | Explicitly authorized planning, ADR, bootstrap, and review work only; no product implementation | -| Next maintainer decision | Accept or reject the `M5` plan pair; disposition [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept), [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept), and [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | +| Next maintainer decision | Accept or reject the `M5` plan pair; disposition [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept), [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept), [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept), and [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | | Next transition | Record the acceptance governance row and move `M5` to Accepted | | Validation | `bash scripts/check-bootstrap.sh` | From d40c71c35466954ea2acbd88078830841115a78c Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:43:07 -0700 Subject: [PATCH 005/585] docs(M5): correct the roadmap's projection of M5 The durable-service rung still said M5 delivers a daemon-grade store. The maintainer moved that adapter, its selection experiments and its migration to the successor milestone on 2026-09-14, and ADR 0031 now records the 0.2 selection as the existing local adapter with its limits documented. The rung and its technical row say that, and the decision-order row splits selection from migration. The rung and the decision order also name Outcome 6, the provider credential handoff, which the maintainer added on 2026-09-19. The roadmap stays a projection and authorizes nothing. --- docs/roadmap-technical.md | 5 +++-- docs/roadmap.md | 10 +++++++--- 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/docs/roadmap-technical.md b/docs/roadmap-technical.md index 0edf3a023..b5dc1bd7b 100644 --- a/docs/roadmap-technical.md +++ b/docs/roadmap-technical.md @@ -23,7 +23,7 @@ Concept: [Capability ladder](roadmap.md#concept-roadmap-ladder) | [Foreground coding harness — M2 candidate](roadmap.md#concept-roadmap-foreground-harness) | Multi-turn loop over committed conversation history with real tool results returned to the model; runtime-scoped tool registry with recorded definition generations; the `read`, `write`, `edit`, and `bash` bootstrap profile under one shared conformance suite; host policy that refuses before any process starts; truthful same-process cancellation; streaming progress; session discovery and resume; a one-page embedded composition; a `loopex` terminal command; an attended real-provider coding demonstration. Closed M2 and its integrated post-closure repair line supply this rung's source proof. | The annotated `v0.0.0-m2` tag identifies that exact integrated repaired source snapshot. It publishes no package, freezes no surface, and makes no compatibility claim. | | [Extensible local foundations — M3 closed](roadmap.md#concept-roadmap-kernel-consolidation) | Closed and integrated proof: pinned Git/project-only skills, operator pre-run admission/selection and unchanged authority; required-only admission, dispatcher availability and permit retirement; skill/tool/artifact workflow, stable witnesses and acyclic inherited enforcement. | Experimental local additions; no release or freeze. | | [Headless external consumption — M4 closed](roadmap.md#concept-roadmap-session-protocol) | Observability first: runtime-owned isolated OTP trace sessions with identity-only default capture and telemetry spans at every port and transaction boundary; core durable interactions and bounded ArtifactStore transfers; floor refresh across all actual Closed holders; foreground stdio JSONL and exact schema/capability negotiation; facade-only mapping of shared resources, interactions and commands; a plain-JavaScript skill/interaction/tool/artifact/restart workflow from a fresh source extraction with operator-supplied inputs; independent vectors, malformed input and slow-reader proof. The [Closed M4 plan](plans/M4.md#concept) records the outcomes and their evidence; the runs are in [M4 closure runs](evidence/M4-closure-runs.md). | Source `VERSION` is `0.1.0`; the annotated `v0.1.0` tag on the exact integration commit on `main` awaits separate release authority. No Hex package, binary, installer or public freeze. | -| [Durable service — v0.2 candidate](roadmap.md#concept-roadmap-durable-service) | M5: daemon-owned session lifetime, Unix-domain-socket transport, concurrent independent clients, one-controller/many-observer collaboration with stale-controller fencing and crash takeover, race-free snapshot and cursor replay, backpressure, residency and eviction, an ADR-selected daemon-grade store with migration, cross-process cancellation. | No public freeze; the protocol remains experimental. | +| [Durable service — v0.2 candidate](roadmap.md#concept-roadmap-durable-service) | M5: daemon-owned session lifetime, Unix-domain-socket transport, concurrent independent clients, one-controller/many-observer collaboration with stale-controller fencing and crash takeover, race-free snapshot and cursor replay, backpressure, residency and eviction, cross-process cancellation, and the provider credential handed over the child's private channel instead of the parent VM's environment. The store is ADR-selected: the existing local adapter with documented limits, the daemon-grade adapter and its migration deferred to the successor. | No public freeze; the protocol remains experimental. | | [Governed extension runtime — v0.3 candidate](roadmap.md#concept-roadmap-governed-extension-runtime) | Extension manifest and namespaces, quiescent activation, state upgrade/downgrade fixtures, exact rollback. | Public-protocol release candidate and extension contribution API, each only if separately accepted after activation proof. | | [Isolated hands — v0.4 candidate](roadmap.md#concept-roadmap-isolated-hands) | Executor gateway to an OS-isolated hand, promotion path, local and isolated conformance. | Executor protocol for proven local/isolated transports. | | [Remote ecosystem — v0.5 candidate](roadmap.md#concept-roadmap-remote-ecosystem) | Broker, trusted-gateway distribution, ACP adapter, secured sample host, remote reconciliation. | Executor protocol for a proven remote transport; ACP mapping. | @@ -93,9 +93,10 @@ accepted or the implementation that depends on it begins. | Bounded artifact retrieval and floor refresh | `M4` | ADRs 0028/0026 settle transfer integrity/work budgets and the protocol codec floor; all affected Closed holders retain transactions. | | Public DTO and schema bundle, versioning, and capability negotiation | `M4` | A published wire boundary needs its exact schema bytes, version identity, unknown-field rule, and negotiation handshake before independent clients depend on it. | | Durable interaction identity | `M4`, core before wire | ADR 0024 assigns session-owned identity and answer/policy/intent order, proved locally before protocol mapping. | -| Store selection and migrations | `M5` | A service makes operational and compatibility claims that the bootstrap adapters do not. | +| Store selection and migrations | `M5` selects, the successor migrates | A service makes operational and compatibility claims that the bootstrap adapters do not. ADR 0031 records the `0.2` selection and its limits; the daemon-grade engine and its migration wait for the experiments that choose them. | | Attachment delivery, cursor replay, and residency | `M5` | Snapshot-first attach, replay position, and eviction decide what a reconnecting client is owed, and they precede a protocol release candidate. | | Collaboration policy: controller leases, observers, and takeover | `M5` | Concurrent clients need one fencing and takeover rule before a daemon claims multi-client truth. | +| Provider credential handoff | `M5` | ADR 0034 makes the credential a per-invocation input on the child's private channel; a process-wide environment read is both the weaker property and what keeps the provider suite serial. | | Extension activation and rollback | Governed extension runtime | Quiescence, atomic module-set loading, and exact A→B→A rollback define the capability. | | Extension packaging, acquisition, and installation | Whichever comes first: the first out-of-repository extension, or the first published package | Distinct from activation. [ADR 0003](adr/0003-extension-contract-boundary.md#concept) fixes the contributor-facing boundary and defers the installation pipeline, closure conflict resolution, signing and provenance formats, host configuration schema, and registry acquisition until a runtime and manifest implementation supply the evidence. | | Isolated-hand threat model and sandbox backend | Isolated hands | Nothing may claim OS isolation before the backend is chosen and reviewed. | diff --git a/docs/roadmap.md b/docs/roadmap.md index 00792a035..42caae3c2 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -109,9 +109,13 @@ Technical depth: [External-consumer candidate proof](roadmap-technical.md#techni Can independent clients attach, recover, and agree on one protocol candidate without owning session lifetime? M5 carries this rung: daemon-owned session lifetime, a local socket transport, concurrent independent clients, -collaboration with crash takeover, snapshot and cursor replay, residency limits, -a daemon-grade store, and cancellation that crosses processes. The protocol -still remains experimental. +collaboration with crash takeover, snapshot and cursor replay, residency +limits, and cancellation that crosses processes, all on an ADR-selected store. +For `0.2` that store is the existing local adapter with its limits and its +root-retirement procedure documented; the daemon-grade adapter and its +migration are the successor milestone's. M5 also moves the provider +credential off the parent VM's environment onto the private per-invocation +channel. The protocol still remains experimental. Technical depth: [Durable-service candidate proof](roadmap-technical.md#technical-roadmap-durable-service) From b29c54cf26ec783c8ffbcdd5497809b5c43bbdd8 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:44:08 -0700 Subject: [PATCH 006/585] plan(M5): make the rejoin order and the decision provenance exact Two corrections found reading the pair back. The rejoin order named the workstreams in a sequence that did not match their numbering, and did not say that the narrow core attachment change has to land before the daemon's attach path can be proved; it now names each workstream at the point it rejoins. And the Concept plan attributed ADR 0019 to M4; it is the post-M2 provider protection decision that ADR 0034 refines. --- docs/plans/M5-technical.md | 17 +++++++++++------ docs/plans/M5.md | 8 ++++---- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0c6f8780d..c12614f76 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -46,12 +46,17 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex_llm_reqllm` | The credential handoff, its sender, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, or anything outside the adapter | | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | -**Rejoin order.** Prerequisite decisions, then the one new application and the -narrow core attachment change, then marker-first daemon lifetime and the -socket over the local adapter, then collaboration and takeover on that base, -then residency, replay and backpressure, then the two-process workflow with -the reference CLI and the independent Node client, then the documentation and -the source-archive proof, then independent review of the closure candidate. +**Rejoin order.** Prerequisite decisions first. Then the new application with +its dependency-budget change, and the narrow core attachment change, which the +daemon's attach path needs before it can be proved. Then marker-first daemon +lifetime and the socket over the local adapter, workstreams 1 and 2, which may +run together once the application exists. Then the collaboration lease, +workstream 3, on that base. Then the daemon-side residency, replay and +backpressure that sit above the core change, the rest of workstream 4. Then +the two-process workflow with the reference CLI and the independent Node +client. Then the documentation and the source-archive proof, workstream 6, at +the end because it describes what the others built. Then independent review of +the closure candidate. Prove lifetime, refusal of a second daemon at the marker, shutdown on store loss, capacity refusal, reopening under the foreground server after an orderly diff --git a/docs/plans/M5.md b/docs/plans/M5.md index facfcb0ef..2634993f0 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -178,10 +178,10 @@ implementation that depends on it, not before unrelated work. | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the adapter reads no environment variable for it | 6 | -Three decisions of M4's remain load-bearing and are not reopened: ADR 0023 -fixes the protocol M5's generation 2 extends, ADR 0030 fixes the telemetry -inventory every daemon boundary emits, and ADR 0019 fixes the provider process -topology ADR 0034 refines. +Three accepted decisions remain load-bearing and are not reopened: M4's +ADR 0023 fixes the protocol M5's generation 2 extends and M4's ADR 0030 fixes +the telemetry inventory every daemon boundary emits, while the post-M2 +ADR 0019 fixes the provider process topology ADR 0034 refines. ### How Each Outcome Is Verified From dd35ed821f3c29f5381bbd6781aa9d4dafc735e6 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:46:52 -0700 Subject: [PATCH 007/585] docs(M5): point the plans index at the guide for a pair's shape The index still carried the gate-era plan skeleton with its envelope markers while the milestone guide defines the sections a pair carries now and M5 is the first pair written to it. The index points at the guide, says the envelope markers in the M0-M4 pairs are read as written, and repeats nothing. --- docs/plans/README.md | 155 ++++--------------------------------------- 1 file changed, 12 insertions(+), 143 deletions(-) diff --git a/docs/plans/README.md b/docs/plans/README.md index ff2cb422f..71a07f367 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -196,8 +196,8 @@ Empty governance slots may be filled only from an explicit disposition; a completed governance row is a record of a decision that was made. A conflict between the pair blocks acceptance and closure. -Every Concept plan contains a `## Governance Records` table outside its -envelope: +Every Concept plan contains a `## Governance Records` table outside its other +sections: | Decision | Authority | Authority evidence | Bound bytes | | --- | --- | --- | --- | @@ -218,147 +218,16 @@ it may not be supplied or inferred. An independent reviewer reads the exact candidate before either transition, and the transition itself changes only the governance row, the disposition it names, and the derived status blocks. -The exact skeletons are below. Neither file has an H1 because the filename and -register own identity. Replace `` with the registered milestone name. - -Concept plan, `docs/plans/.md`: - -```markdown - -## Concept - -Technical depth: [Milestone mechanics](-technical.md#technical-depth). - - -## Normative Concept Envelope - - -### Purpose - - - - -### Outcomes - -| # | Outcome | Evidence class | Verification | -| --- | --- | --- | --- | -| 1 | | | | - -Technical depth: [Evidence obligations and mapping](-technical.md#technical-plan-evidence). - - -### Scope - - - -Technical depth: [Prerequisites and acceptance points](-technical.md#technical-plan-prerequisites). - -Technical depth: [Ownership and rejoin barriers](-technical.md#technical-plan-ownership). - -Technical depth: [Packaging mechanics](-technical.md#technical-plan-packaging). - -Technical depth: [Proportional minimalism budget](-technical.md#technical-plan-minimalism). - -Technical depth: [Compatibility mechanics](-technical.md#technical-plan-compatibility). - -Technical depth: [Migration and rollback](-technical.md#technical-plan-migration). - - -### Non-Goals - - - -Technical depth: [Deferral acceptance points](-technical.md#technical-plan-prerequisites). - - -## Workstreams - - - -## Progress and Evidence - -| # | State | Evidence | -| --- | --- | --- | -| 1 | Open | — | - -## Governance Records - -| Decision | Authority | Authority evidence | Bound bytes | -| --- | --- | --- | --- | -| Acceptance | — | — | — | -| Closure | — | — | — | -``` - -Technical depth plan, `docs/plans/-technical.md`: - -```markdown - -## Technical depth - -Concept: [Milestone purpose and outcomes](.md#concept). - - -## Normative Technical Envelope - - -### Prerequisites and Acceptance Points - -Concept: [Milestone scope](.md#concept-plan-scope). - -Concept: [Milestone non-goals](.md#concept-plan-non-goals). - - - - -### Ownership, Decision Owners, and Rejoin Barriers - -Concept: [Milestone scope](.md#concept-plan-scope). - - - - -### Evidence Obligations and Mapping - -Concept: [Milestone outcomes](.md#concept-plan-outcomes). - - - - -### Compatibility - -Concept: [Milestone scope](.md#concept-plan-scope). - - - - -### Migration and Rollback - -Concept: [Milestone scope](.md#concept-plan-scope). - - - - -### Packaging - -Concept: [Milestone scope](.md#concept-plan-scope). - - - - -### Proportional Minimalism Budget - -Concept: [Milestone scope](.md#concept-plan-scope). - - - -``` - -Both marked normative envelopes record what the maintainer accepted: purpose, -outcomes, scope, and the constraints the work runs under. Workstreams, progress, -resolved outcome state, and evidence links stay outside them and are updated as -the work proceeds. Changing an accepted purpose, outcome, or scope is a new -maintainer decision, recorded in the plan where the change lands; independent -review decides whether the pair is clear, consistent, and adequate. +The sections a plan pair carries, and what each states, are defined once in +the [milestone guide](../developer/milestones-technical.md#technical-milestones-agree); +this index does not repeat the skeleton. Neither file has an H1, because the +filename and the register own identity, and the Concept file's `## Governance +Records` table stays outside every other section. The `loopex:plan-*-envelope` +markers and the `Normative ... Envelope` headings in the M0–M4 pairs belonged +to the retired gate structure and are read as written in those records; a new +pair does not carry them. Changing an accepted purpose, outcome, or scope is a +new maintainer decision, recorded in the plan where the change lands; +independent review decides whether the pair is clear, consistent, and adequate. Evidence links live in the Concept plan's Progress and Evidence table, and the Outcomes rows name how each outcome is verified. Do not add an evidence sidecar From ab071272242cdbfeb747b789e53120d6c1dca00d Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 17:58:06 -0700 Subject: [PATCH 008/585] plan(M5): apply the nine findings from the independent review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit All nine are document fixes across the plan pair and ADRs 0031 to 0034. They land together because six of them touch the same two files and the pair is one review unit. A. The 65,536-byte ceiling case in provider_retainer_boundaries_test.exs was listed as carrying over unchanged. It cannot: that module writes the credential with System.put_env in its setup and again in the case body. It joins the re-pointed set, supplying the oversized value as that invocation's reference. B. The child-environment claim named m0_child_environment_conformance_test, whose sentinel is synthetic and proves something else entirely. The real witness is the entry-env marker inside the version-refusal and bootstrap-refusal cases of credential_plane_test; those assertions survive the re-pointing unchanged, and the m0 case is now named for what it proves. C. adapter_test pins the exact System.get_env literals per library file and proves the missing-credential refusal by deleting the variable. Both change. ADR 0034 requires that drift-protection case to survive strengthened, with an empty allowlist for provider_bridge.ex, and records that the literal lives in provider_bridge.ex while credential_variable/0 lives in req_llm.ex, so the surviving pin is on the host-facing accessor. D. ADR 0031 said its own still-Proposed bytes would be revised to name the successor's engine. Accepted bytes are anchored and replaced additively, and its one Acceptance row binds the M5 selection. Both files now route the successor selection to a new ADR superseding 0031's successor half. E. Outcome 6 made "the modules run concurrently" a closure condition while the ADR called it evidence. The plan states the ADR's standard: converted one at a time, kept while green, a module that stays serial keeps its reason, and the measurement is evidence rather than a threshold. F. ADRs 0031, 0032 and 0033 said "Prerequisite for: M5 acceptance". They now name the outcomes and the workstream each blocks, as the guide, the plan and ADR 0034 already do. G. The plan let a client attach before or after acquiring control while ADR 0033 fixed one order. The decision is settled once in ADR 0033 — the two calls are order-independent, the constraint is on the first mutation — its evidence asks for both orders, and the plan follows. H. The selection mapping existed twice. The mechanics stay in the technical companion; the Concept plan names the five rows M5 reaches and points at the verification guide and the companion. I. The technical evidence table named test files for two outcomes only. It now carries a Witness column for all six, so the companion is complete on its own. Two honesty additions the review verified: loopex_daemon joins the release check's release_apps and not long_bound_apps, because every release_apps lane already passes --include long_bound; and store_log_too_large, the local adapter's at-open refusal for a log already past the ceiling, is named wherever the plan and ADR 0031 list that adapter's refusals, because an operator meets it. --- ...store-selection-and-migration-technical.md | 21 ++++--- ...mon-grade-store-selection-and-migration.md | 41 +++++++++----- ...-daemon-attachment-residency-and-replay.md | 4 +- ...controller-lease-and-takeover-technical.md | 16 ++++-- ...aboration-controller-lease-and-takeover.md | 19 +++++-- ...andoff-over-bootstrap-channel-technical.md | 56 ++++++++++++++++--- docs/plans/M5-technical.md | 45 +++++++++------ docs/plans/M5.md | 48 ++++++++-------- 8 files changed, 169 insertions(+), 81 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index f8f2082b4..283083e3a 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -120,12 +120,14 @@ accepted product bytes. Both run: public sequence intact and the integrity check clean. Record each experiment's exact candidate SHA, commands, platform and measured -results in the decision packet. Revise this still-Proposed pair to name the -winner, both experiment SHAs, its evidence and any packaging cost; -independently review that candidate before the maintainer accepts it. -Selection does not itself accept the successor milestone. Product -implementation of the adapter starts only after this revised pair and that -milestone's plan are accepted. +results in the decision packet. The winner, both experiment SHAs, its +evidence and any packaging cost are then written into a new ADR that declares +`Supersedes: 0031` for this successor half, not into these bytes: once this +pair is accepted as an M5 prerequisite it is anchored, and its one Acceptance +row already binds the M5 local-adapter selection. That successor ADR is +independently reviewed and accepted on its own. Selection does not itself +accept the successor milestone. Product implementation of the adapter starts +only after that successor ADR and that milestone's plan are accepted. ### Migration @@ -180,6 +182,7 @@ restore reopens the copy under the same placement identity and refuses a placement mismatch exactly as resume does today. Acceptance of the M5 selection binds this pair at the exact candidate the -maintainer names in the governance record. The successor selection is a second -disposition on the revised pair, recorded the same way once its experiment -evidence exists. +maintainer names in the governance record, and that is the only disposition +this pair carries. The successor selection is a separate disposition on a +separate ADR that supersedes this one's successor half, recorded the same way +once its experiment evidence exists; this pair is not edited again. diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 642f3f8af..806dee56f 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -7,9 +7,10 @@ Technical depth: [Daemon-grade store mechanics](0031-daemon-grade-store-selectio - **Date:** 2026-09-14 - **Decision owner:** Maintainer - **Supersedes:** nothing; refines the store posture in vision §12.2 -- **Prerequisite for:** M5 acceptance, for the local-adapter selection and - its documented limits; the successor milestone that adopts the daemon-grade - adapter, for the selection experiment and migration +- **Prerequisite for:** M5 outcomes 1 and 5, accepted before the daemon opens + a state root — that is, before M5's workstream 1 lands — for the + local-adapter selection and its documented limits. Its successor half binds + nothing in M5; see the note on supersession below. ### Context and Decision @@ -35,10 +36,12 @@ with a hard 256 MiB capacity, a 4 MiB frame ceiling, full-history retention with no compaction, full replay at open, and one writer per root. Reaching capacity is a truthful refusal, never a silent loss: the adapter answers `store_capacity_exceeded`, the daemon refuses further mutation with that -reason while observers stay attached and an orderly stop still succeeds, and -the operator retires the root by stopping the daemon, moving the root aside -and starting a fresh root. Sessions in a retired root are resumable only by -reopening that root. This is a bounded, experimental selection made on +reason while observers stay attached and an orderly stop still succeeds, and a +log already past the bound is refused at open as `store_log_too_large` rather +than opened and truncated. The operator retires the root by stopping the +daemon, moving the root aside and starting a fresh root. Sessions in a retired +root are resumable only by reopening that root. +This is a bounded, experimental selection made on evidence the local adapter already carries; it is not a daemon-grade store, and the 0.2.0 daemon's operator documentation states these limits and the retirement procedure. The maintainer chose this on 2026-09-14 over deferring @@ -53,13 +56,23 @@ unchanged private session Store ports. After M5 closes, isolated, disposable contract experiments in their own worktrees compare a BEAM-native segmented log and a SQLite-backed NIF adapter against the same conformance and fault-injection suites. Neither experiment becomes product implementation or -merges to `main`. This pair is then revised to name the selected engine, both -exact experiment revisions and their measured evidence, before independent -review and acceptance of those exact bytes. The current recommendation is the -BEAM-native adapter because it avoids a compiled dependency and VM-level NIF -risk while reusing proven local framing and repair; these are hypotheses to -test, not a categorical veto of SQLite. Any candidate that fails a required -fault case is ineligible. +merges to `main`. The current recommendation is the BEAM-native adapter +because it avoids a compiled dependency and VM-level NIF risk while reusing +proven local framing and repair; these are hypotheses to test, not a +categorical veto of SQLite. Any candidate that fails a required fault case is +ineligible. + +**Where the selection is recorded.** Not here. Once this pair is accepted as +an M5 prerequisite its bytes are anchored: a decision is replaced additively, +by a successor that declares `Supersedes: 0031`, and the predecessor stays +exactly as accepted. This pair's single Acceptance row binds one disposition, +and that disposition is the M5 local-adapter selection. So the successor +milestone's engine, the two exact experiment revisions, their measured +evidence and the migration are recorded in a **new ADR superseding this one's +successor half**, proposed when the experiments have run and accepted on its +own review. What this pair decides now, and all it decides now, is the M5 +selection and the procedure the successor's experiments must follow; nothing +in the successor half binds M5. **Alternatives rejected.** Deferring this decision out of M5 entirely was rejected on 2026-09-14: the reference daemon still needs a recorded store diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 8f3ddc4a6..c2636b96b 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -7,7 +7,9 @@ Technical depth: [Attachment residency mechanics](0032-daemon-attachment-residen - **Date:** 2026-09-14 - **Decision owner:** Maintainer - **Supersedes:** nothing; ADR 0023's one-attachment-per-foreground-process rule and generation-1 wire remain in force on the foreground server -- **Prerequisite for:** M5 acceptance +- **Prerequisite for:** M5 outcomes 1, 2 and 4, accepted before the socket is + bound or the core attachment change lands — that is, before M5's workstreams + 2 and 4 ### Context and Decision diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 58a474259..be2bba846 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -78,9 +78,14 @@ the local store's writer marker, unchanged. before core admission and before a session write; an observer who copied the visible current epoch still refuses. Queries and attach carry no epoch. - `session.create` has no `writer_epoch` because the session lease does not - exist. It creates an uncontrolled session. The caller must attach, acquire - control explicitly, and use the returned epoch for its first session - command. Creation never implicitly grants control. + exist. It creates an uncontrolled session, and creation never implicitly + grants control. The caller must acquire control explicitly and use the + returned epoch for its first session command. Acquire and attach may be + sent in either order, because acquire is keyed by session ID and validates + only durable session existence; the constraint is on the first mutation, + not on the two calls that precede it, and that mutation refuses unless the + sending connection is the holder, the epoch matches and the connection + holds a controller-capable attachment. - An orderly connection close by the holder releases the lease; an abrupt loss leaves it to expire. @@ -131,8 +136,9 @@ through content, metadata, answers or order; after a daemon restart every session uncontrolled, an epoch from before the restart refused, and the first acquire granting a fresh epoch; forward and backward wall-clock jumps not changing live admission or takeover timing; creation yielding an -uncontrolled session and requiring attach plus explicit acquire before -prompt; a dormant session acquired by ID, then resumed with epoch and +uncontrolled session and requiring both attach and explicit acquire before +prompt, proved in both orders, with the prompt refused while either is +missing; a dormant session acquired by ID, then resumed with epoch and attached. ### Alternatives diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index f59f22502..665b2d1fa 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -7,7 +7,8 @@ Technical depth: [Collaboration mechanics](0033-collaboration-controller-lease-a - **Date:** 2026-09-14 - **Decision owner:** Maintainer - **Supersedes:** nothing; the core keeps the vision §11.6 rule that it mandates no controller lease -- **Prerequisite for:** M5 acceptance +- **Prerequisite for:** M5 Outcome 3, accepted before any admission check is + written — that is, before M5's workstream 3 ### Context and Decision @@ -32,10 +33,18 @@ attachment has command capability. The daemon checks those facts together before core admission and serializes that handoff with lease changes; an observer cannot reuse an epoch it learned from a result or status. `session.create` is the one exception because no session lease exists yet: -it creates an uncontrolled session, after which the client attaches and -explicitly acquires control before its first session command. For a known -dormant session, a client may acquire control by session ID before -`session.resume`, then resume with the granted epoch and attach. A +it creates an uncontrolled session, and control over it is never implicit. + +Attach and acquire are independent of each other and their order is not +fixed. A connection may acquire control of any session that durably exists, +by session ID, before or after it attaches to that session; what is fixed is +that no existing-session mutation is admitted until the lease is held by the +sending connection, its epoch matches, and — with the single exception of +`session.resume` on a verified dormant session — that connection holds a +controller-capable attachment. So a newly created session is driven by +attaching and acquiring in either order and then sending the first command +with the granted epoch, and a known dormant session is driven by acquiring +by ID, resuming with the granted epoch and attaching. A controller renews its lease while it lives and releases it on an orderly disconnect; a lease that is not renewed expires. Takeover is explicit: an observer asks for control and receives it only when the lease is released or diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index eaf97edb6..e322a7dde 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -101,15 +101,30 @@ credential — and each must hold with its assertion unchanged in meaning: | Child Logger forms and metadata | `ordinary and split actual child Logger messages cannot expose the credential`, `all actual child Logger message forms and metadata stay private`, `repeated credential bytes in actual child metadata cannot reach host channels`, `credential-bearing child metadata keys cannot reach host channels` | | Crash reports | `a provider request adapter that throws cannot put the credential in a stream-server crash report`, `a provider request adapter that exits cannot put the credential in a stream-server crash report`, `an actual child report containing its own request credential stays private`, `an actual child StreamServer termination cannot forward its credential` | -Two cases carry over unchanged from elsewhere and are not re-pointed: the -child-environment conformance case in -`apps/loopex_llm_reqllm/test/m0_child_environment_conformance_test.exs`, which -reads the child's recorded entry environment and refutes the credential name, -and the size-bound case in +Two of those cases also carry the child-environment witness, and it survives +the re-pointing unchanged: the version-refusal case at +`credential_plane_test.exs:117` and the bootstrap-refusal case at `:567` each +read the child's recorded `entry-env` marker and refute +`Adapter.credential_variable()` in it. Both assertions stay exactly as they +are and mean more afterwards, because the name they refute in the child is by +then absent from the parent as well. The child-environment conformance case in +`apps/loopex_llm_reqllm/test/m0_child_environment_conformance_test.exs` is a +different proof and is untouched by this decision: its sentinel +`LOOPEX_M0_CHILDENV_PARENT_ONLY` is synthetic, so what it proves is that no +parent environment name at all reaches the child, not anything about the +credential name. + +One case outside `credential_plane_test.exs` must be re-pointed too, and +cannot carry over unchanged. The size-bound case in `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, which -drives the 65,536-byte ceiling. +drives the 65,536-byte ceiling, delivers its credential through +`System.put_env(Adapter.credential_variable(), …)` in that module's `setup` +and again in the case body. Both writes go: the module's fixtures carry their +own credential reference, and the case supplies the 65,536-byte value as that +invocation's reference rather than writing it into the VM. The ceiling it +proves, and the refusal above the ceiling, are unchanged. -Two proofs are new: +Three proofs are new: - **Parent environment.** Before, during and after a call, the parent VM's environment holds no credential under the adapter's name or any value equal @@ -118,8 +133,31 @@ Two proofs are new: - **Concurrent independence.** Two invocations with distinct credentials run at once and each child records only its own; neither child, nor either child's diagnostics, ever sees the other's. - -Both belong in `credential_plane_test.exs` beside the cases they generalise. +- **No credential environment read in the adapter's lib tree.** The existing + drift-protection case in `apps/loopex_llm_reqllm/test/adapter_test.exs` — + `the adapter reads exactly one credential environment variable` — pins the + exact `System.get_env` arguments per library file, including + `"provider_bridge.ex" -> ["\"LOOPEX_PROVIDER_API_KEY\""]`. That case must + survive, strengthened rather than deleted: the expected list for + `provider_bridge.ex` becomes `[]`, so the case then proves that no file in + the adapter's library tree reads any environment variable for a credential + at all, which is a stronger claim than the one it makes today. + +The first two belong in `credential_plane_test.exs` beside the cases they +generalise; the third stays where it is. + +Two details of that case matter to whoever writes the change. The literal +`"LOOPEX_PROVIDER_API_KEY"` it pins today lives in +`provider_bridge.ex:401`, inside the credential sender, while +`credential_variable/0` and its module attribute live in `req_llm.ex:49` and +`:149-150`; only the first disappears. So `adapter_test.exs:50`'s +`assert variable == "LOOPEX_PROVIDER_API_KEY"` is, afterwards, a pin on the +host-facing accessor — the one name an operator configures — and that is what +it should say it is. The neighbouring case `a missing credential is reported +before any provider is called` proves the refusal today by deleting the +variable from the VM; under this decision it proves the same refusal by +supplying no credential reference with the call, which is the path that +replaces it. ### Security review diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index c12614f76..ac21d7c4e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -39,7 +39,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | --- | --- | --- | | `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | -| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` refusal and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | +| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session stop, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity or any durable record | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | @@ -75,10 +75,13 @@ sets out. **Semantics the rejoin must preserve.** Use the existing command identity for every mutating method; request identities never enter journals. `session.create` has no existing session or epoch to authorize: it creates an -uncontrolled session, after which a client may attach before or after -acquiring control, while `session.resume` requires acquiring control first. -Existing-session mutation requires control. The lease record lives in the -daemon's memory, keyed by session, for the daemon process's lifetime; one +uncontrolled session and grants nothing. Attach and acquire are independent +and their order is not fixed, as ADR 0033 settles it: the constraint is on the +first mutation, which is admitted only when the sending connection holds the +lease, its epoch matches and that connection holds a controller-capable +attachment. The single exception is `session.resume` on a verified dormant +session, which the holder may send before attaching. The lease record lives +in the daemon's memory, keyed by session, for the daemon process's lifetime; one owner process per session serializes its lease transitions with its admission handoff, and a restart of that owner leaves the session uncontrolled. For every existing-session mutation the daemon checks the requesting connection @@ -96,14 +99,16 @@ exists. Concept: [Outcomes](M5.md#concept-plan-outcomes). -| Outcome | What must be proved, beyond ordinary unit tests | -| --- | --- | -| 1 | A real daemon operating-system process per state root. Sessions progress with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart recovers every session under the same placement identity with no duplicate effect. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses further mutation with `store_capacity_exceeded` while observers stay attached and an orderly stop still succeeds. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. Session open and stop through the socket only | -| 2 | A raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its own generation, and a generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. Every daemon boundary emits its ADR 0030 spans and a daemon-scoped trace session captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | -| 6 | The parent VM's environment holds no credential under the adapter's name, and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment case in `m0_child_environment_conformance_test.exs` and the 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` carry over unchanged. A security review by someone other than the implementer is recorded. The provider suite's modules run concurrently and the measured duration is recorded beside the M4-closure baseline | +Concept: [Verification stages](M5.md#concept-plan-verification). + +| Outcome | Witness | What must be proved, beyond ordinary unit tests | +| --- | --- | --- | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. Sessions progress with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart recovers every session under the same placement identity with no duplicate effect. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses further mutation with `store_capacity_exceeded` while observers stay attached and an orderly stop still succeeds, and a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. Session open and stop through the socket only | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its own generation, and a generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. Every daemon boundary emits its ADR 0030 spans and a daemon-scoped trace session captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | The parent VM's environment holds no credential under the adapter's name, and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an empty expected list for `provider_bridge.ex`, so it proves the adapter's library tree reads no environment variable for a credential at all. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -136,7 +141,12 @@ the floor pair, `mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh` with its own `MIX_BUILD_ROOT`; and `bash scripts/check-release.sh` runs once on the current pair with the provider credential and the pinned Node version in -`scripts/fixtures/m4/client-toolchain.txt`. Each run's revision, platform, +`scripts/fixtures/m4/client-toolchain.txt`. `loopex_daemon` joins that +script's `release_apps` list in the change that adds its first release case, +and only that list: every `release_apps` lane already runs +`--include long_bound`, so the daemon's long-duration bound tests are carried +there and the application does not also join `long_bound_apps`, which exists +for applications with no other release test. Each run's revision, platform, toolchain, result and measured duration is retained on `docs/evidence/M5-closure-runs.md`, indexed in `docs/evidence/README.md`, together with the Outcome 6 security review and the attended demonstration's @@ -215,7 +225,10 @@ releases the writer marker and that the foreground server and the CLI then resume a daemon-created session with identical replay. A root that reaches the local log's 256 MiB capacity is retired, not migrated: -stop the daemon, move the root aside, start a fresh root. A session in a +stop the daemon, move the root aside, start a fresh root. A root already past +that bound refuses at open with `store_log_too_large`, which is the message +the operator page must explain, because it is what an operator meets when a +root grew past the ceiling under an earlier process. A session in a retired root is reached only by reopening that root. Rollback to `0.1.0` is stopping the daemon. Removing it restores the M4 @@ -295,7 +308,7 @@ decision named above; M5 introduces none of its own. | Ceiling | Value | Source | | --- | --- | --- | -| Log capacity per state root | 256 MiB, refused as `store_capacity_exceeded` | ADR 0031 | +| Log capacity per state root | 256 MiB; an append past it refused as `store_capacity_exceeded`, a log already past it refused at open as `store_log_too_large` | ADR 0031 | | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | | Attachments per session | 64 | ADR 0032 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 2634993f0..db069c321 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -52,7 +52,7 @@ loop. | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with exact reconnect, retained encoded-event bytes within the daemon-owned bounds, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with every daemon boundary emitting the accepted telemetry spans; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, compiles and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and the parent VM's environment never carries it; every existing credential-plane negative proof holds against the new handoff; and the provider test modules that serialise on that one variable today run concurrently | Negative tests for trust, a recorded security review, the real-provider lane in the release check, and the measured provider suite with its modules concurrent | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and the parent VM's environment never carries it; every existing credential-plane negative proof holds against the new handoff; and the adapter's library tree is proved to read no environment variable for a credential at all. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -104,10 +104,11 @@ for this release by ADR 0031: one state root, the local log the M4 foreground server and CLI already write, and the local writer marker held by the daemon from before the socket is bound until the daemon exits. The adapter's limits are the daemon's limits and the operator documentation states them: a hard -256 MiB log capacity refused as `store_capacity_exceeded`, a 4 MiB frame -ceiling, full-history retention with no compaction, and full replay at open. A -root at capacity is retired by stopping the daemon, moving the root aside and -starting a fresh root. No new store adapter, journal format version, migration +256 MiB log capacity refused as `store_capacity_exceeded`, a log already past +that bound refused at open as `store_log_too_large`, a 4 MiB frame ceiling, +full-history retention with no compaction, and full replay at open. A root at +capacity is retired by stopping the daemon, moving the root aside and starting +a fresh root. No new store adapter, journal format version, migration or backup tooling enters M5. The credential handoff to a provider child moves from the process-wide @@ -197,21 +198,20 @@ and 4 in full — daemon lifetime and store fault injection on real local processes, socket framing and generation negotiation, lease admission and fencing after real kills, and the residency and delivery bounds — and it proves the parent-environment, concurrency-independence and re-pointed -negative cases of Outcome 6. Beyond the fast check, a change selects only what -its boundary asks for: - -| The change touches | What it selects in addition | -| --- | --- | -| The wire protocol: generation 2's schema and vectors | The independent client workflows (`--only node_client`, part of the release check), and `docs/developer/compatibility-surfaces.md` updated in the same change | -| The CLI or the operator-facing daemon commands | The operator page that describes the behavior updated in the same change; a changed operator command also selects its workflow in the release check | -| Provider or credential handling: Outcome 6 | `bash scripts/check-release.sh`, the real-provider cases | -| The provider launcher's operating-system boundary: the child's spawn, its control pipe and its cleanup | `bash scripts/fixtures/pinned-load.sh` over the touched cases on a Linux host: thirty runs under four pinned cores and load, no failure and no hang | -| Durable records, the Store, recovery | Nothing more to run; the review confirms the fault-injection and old-reader cases still cover the change | -| A port behaviour or an adapter of one | Nothing more to run; the review confirms the port's conformance suite still runs against every adapter | -| Documentation only | `bash scripts/check.sh --docs` | - -The toolchain floor and `.tool-versions` are unchanged by M5, so no change -selects the floor row for that reason. +negative cases of Outcome 6. + +Beyond the fast check, a change selects only what its boundary asks for. +The rows of the +[selection table](../developer/verification.md#concept-verification-selection) +M5 reaches are five: the wire protocol, for generation 2's schema and +vectors; the CLI and operator-facing commands, for `loopex daemon`, +`loopex attach` and `loopex sessions`; provider and credential handling, for +Outcome 6; the operating-system process boundary, because Outcome 6 changes +the provider child's spawn, control pipe and cleanup; and durable records and +the Store, which M5 touches only through the daemon's use of the unchanged +adapter. The toolchain floor and `.tool-versions` are unchanged, so nothing +selects that row. What each of the five costs, down to the command and its +parameters, is in the technical companion rather than repeated here. **Close.** At one commit on `main` where every outcome maps to tests, retained evidence or a demonstration: hosted CI's green run on that candidate is the @@ -230,6 +230,8 @@ plus a verified source archive of that commit. It publishes no Hex package, binary, installer or service unit, and freezes no public protocol or embedded API. +Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). + ### Rollout and Compatibility @@ -244,8 +246,10 @@ stream is promised. An operator running `0.2.0` runs the daemon on the local adapter and lives within its limits: 256 MiB of log per state root, a 4 MiB frame ceiling, full history with no compaction and full replay at open. Reaching capacity is a -truthful `store_capacity_exceeded` refusal, never silent loss, and the -documented recovery is to retire the root — stop the daemon, move the root +truthful `store_capacity_exceeded` refusal, never silent loss; a root whose +log is already past that bound is refused at open as `store_log_too_large` +rather than opened and truncated. The documented recovery is to retire the +root — stop the daemon, move the root aside, start a fresh one — after which a session in the retired root is reached only by reopening that root. From ccc8166c7c42852e80638634f5a286bc83ef13ba Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:35:44 -0700 Subject: [PATCH 009/585] adr(M5): define a realizable credential resolver contract Audit finding 1. ADR 0034 named an opaque reference with no type, owner, custody, rotation, bound or failure semantics, and said the operator supplies the secret through the parent environment while M5 Outcome 6 said that environment never carries it. Verified in code first. The adapter's sole credential read is provider_bridge.ex:401, inside the sender, with its 1..65,536 size check. ProviderLauncher.spawn_environment/0 at provider_launcher.ex:23-27 calls System.get_env/0 on every launch, because the first spawned image is /usr/bin/env (provider_launcher.ex:115-117) whose own environment `env -i` does not clear. The drift-protection case at adapter_test.exs:73-99 scans one expression, System.get_env(...), and pins provider_launcher.ex to [""], so it admits the enumeration and catches no indirect route. The pair now fixes the option :credential_reference as {resolver_module, reference_term} of bounded plain data, a one-callback host-owned resolver called once inside the sender between the child's ready frame and the credential frame, per-invocation rotation with no cache, the invocation's existing deadline as the only bound, and a table of seven refusals. Custody is the host's and stated separately for the reference hosts, which read the operator's variable once at composition and delete it there; Outcome 6's environment claim is restated from that boundary. The launcher's enumeration moves to composition. The drift proof is widened to get_env/0, /1, /2, fetch_env/1, fetch_env!/1, :os.getenv, :os.env and indirect application, with both adapter files expected empty. The maintainer's req_llm 1.24 upgrade joins the same workstream as its own reviewed dependency change, not as an ADR 0034 consequence, because it touches mix.exs and mix.lock rather than the credential files. --- ...andoff-over-bootstrap-channel-technical.md | 161 ++++++++++++++---- ...edential-handoff-over-bootstrap-channel.md | 91 +++++++--- docs/plans/M5-technical.md | 18 +- docs/plans/M5.md | 39 +++-- 4 files changed, 237 insertions(+), 72 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index e322a7dde..a82ae0953 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -52,12 +52,71 @@ booting — never reaches step 5. That is the property the two existing bootstrap-refusal cases assert, and it is why the credential is not carried by the step-3 frame. -### Resolution and scrub points +### The reference, its resolver, and its failures + +The per-invocation option is `:credential_reference`, one member of the +configuration map the host already supplies to `complete/3`. Its value is +`{resolver_module, reference_term}`: + +- `resolver_module` is an atom naming a module that implements + `Loopex.LLM.ReqLLM.CredentialResolver`, one callback, + `resolve(reference_term) :: {:ok, binary()} | {:error, term()}`; +- `reference_term` is bounded plain boundary data — at most 256 bytes when + encoded by the repository's canonical encoding, and never a PID, port, + function, monitor or reference. It names which credential is wanted; it is + not the credential and carries no authority of its own. + +Any other shape, including a bare binary that could be the bytes themselves, +is refused as an invalid option before any child is spawned. The behaviour +exists rather than a closure because the reference travels in configuration +that is copied between processes and may be printed by a crash report, and +plain boundary data is what may travel there. + +**Owner and custody.** The resolver is the host's. The adapter declares the +behaviour, calls it, and knows nothing about where the bytes live. Each +reference implementation states its own custody and proves it for itself: +the reference CLI, the app-server host and the M5 daemon read +`Loopex.LLM.ReqLLM.credential_variable/0` exactly once, where they compose the +runtime, delete that name from the VM's environment in the same step, and hold +the bytes in one host-owned process, registered under the runtime reference +rather than a global name, whose `format_status/1` redacts its state and which +answers `resolve/1` only for its own reference term. The real-provider lane +composes the same way. Nothing in the adapter depends on that arrangement, and +a different host may keep the bytes anywhere it can defend. + +**When it is resolved.** Exactly once per invocation, inside the sender +process, between the child's `ready` frame and the credential frame — step 5 +above and nowhere else. A resolved value is never cached, never reused for a +second invocation, and never returned to the guardian. + +**Rotation.** Per invocation, by construction: the resolver may answer +different bytes for the same reference on a later call, and no layer holds a +previous answer to contradict it. A rotation that happens while an invocation +is in flight does not reach that invocation, which has already resolved; it +reaches the next one. Nothing is invalidated and no invocation is restarted. + +**Timeout.** Resolution is bounded by the invocation's existing deadline and by +nothing else; this decision adds no second clock. The sender calls the +resolver with the remaining time to that deadline, and a resolver that has not +answered when it elapses is a failed resolution. + +**Failures.** Each is a refusal with a bounded non-secret reason, and each +leaves no retained copy of anything the resolver may have produced: + +| Condition | Outcome | +| --- | --- | +| No `:credential_reference` in the configuration | Refused before the namespace is created and before any child is spawned, with the adapter's existing missing-credential reason | +| Malformed reference, or a `resolver_module` that does not export the callback | The same refusal, before any child is spawned | +| Resolver answers `{:error, reason}` | The sender reports `:error`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and `reason` is reduced to the bounded non-secret status ADR 0029 fixes | +| Resolver does not answer before the invocation deadline | The same failure path, distinguished by its own stable reason; the sender is killed and its stack goes with it | +| Resolved value outside 1 to 65,536 bytes | Refused in the sender before the frame is written, exactly as the size check refuses today | +| Two resolutions in flight at once | Independent. Each invocation has its own sender and resolves for itself; the adapter serializes nothing and shares nothing between them, and two answers for the same reference may differ | + +No failure is retried inside the adapter. Whether to attempt again is the +coordinator's durable decision under ADR 0018, unchanged. + +### Scrub points -- **At the call.** The credential reaches the adapter as an opaque reference - in the per-invocation configuration the host already supplies to - `complete/3`. The reference is not the bytes: it is resolved exactly once, - and only where the frame is written. - **In the sender.** The minimal credential sender keeps the shape it has today: it is spawned for this one send, it installs its own group leader sink so no IO request can carry anything out of it, it resolves the @@ -66,14 +125,20 @@ the step-3 frame. reference, never the resolved value; the value exists only in that process's own stack for the duration of one send, so no guardian state, no message, no exit reason and no crash report can hold it. -- **In the parent's environment.** The adapter performs no `System.get_env/1` - for the credential. `Loopex.LLM.ReqLLM.credential_variable/0` remains as the - one name the *host* reads when it composes a runtime — the reference CLI at - start, and the real-provider lane when it names the variable in its own - failure message — and nothing in the adapter's call path reads it. - `ProviderLauncher.spawn_environment/0` keeps removing that name, and every - other known credential and loader name, from the first spawned image; the - fixed `env -i` argument lists stay as they are. +- **In the parent's environment.** The adapter performs no environment read + for the credential by any route. `Loopex.LLM.ReqLLM.credential_variable/0` + remains as the one name the *host* reads when it composes a runtime — the + reference CLI at start, and the real-provider lane when it names the + variable in its own failure message — and the host deletes that name once it + has read it. `ProviderLauncher.spawn_environment/0`'s enumeration moves off + the call path: the removal list is computed once where the host composes the + runtime, under ADR 0019's existing rule that the trusted host introduces no + further environment names while the snapshot is in use, and is carried in + the launch configuration the adapter already builds. The unconditional + `@excluded` names and the fixed `env -i` argument lists stay as they are. + Deleting the enumeration outright was rejected: the first spawned image is + `/usr/bin/env` itself, whose environment `env -i` does not clear, so without + the removal list that image would carry the parent's whole environment. - **In the child.** Unchanged: the child receives the credential on the socket and nowhere else. Its environment at entry is the fixed `PATH`, `LANG`, `LC_ALL` and the two crash-dump suppressions, and ADR 0029's bounded @@ -126,10 +191,12 @@ proves, and the refusal above the ceiling, are unchanged. Three proofs are new: -- **Parent environment.** Before, during and after a call, the parent VM's - environment holds no credential under the adapter's name or any value equal - to the credential in use. "During" is observed from inside the call, at the - point the child reports readiness. +- **Parent environment.** From the completion of composition onward — before, + during and after a call — the parent VM's environment holds no credential + under the adapter's name and no value equal to the credential in use. + "During" is observed from inside the call, at the point the child reports + readiness. The case composes the runtime the way a reference host does, with + the variable set, and asserts that composition returns having deleted it. - **Concurrent independence.** Two invocations with distinct credentials run at once and each child records only its own; neither child, nor either child's diagnostics, ever sees the other's. @@ -137,20 +204,44 @@ Three proofs are new: drift-protection case in `apps/loopex_llm_reqllm/test/adapter_test.exs` — `the adapter reads exactly one credential environment variable` — pins the exact `System.get_env` arguments per library file, including - `"provider_bridge.ex" -> ["\"LOOPEX_PROVIDER_API_KEY\""]`. That case must - survive, strengthened rather than deleted: the expected list for - `provider_bridge.ex` becomes `[]`, so the case then proves that no file in - the adapter's library tree reads any environment variable for a credential - at all, which is a stronger claim than the one it makes today. + `"provider_bridge.ex" -> ["\"LOOPEX_PROVIDER_API_KEY\""]` and + `"provider_launcher.ex" -> [""]`, the arity-zero enumeration. That case must + survive, strengthened rather than deleted, in two ways. Both of those + expected lists become `[]`, leaving only `provider_worker.ex`'s two + non-secret crash-dump names, so the case then proves that no file in the + adapter's library tree reads any environment variable at all except those + two. And its scan is widened from one regular expression over + `System.get_env(...)` to every route by which an environment read can be + written: `System.get_env/0` and `/1`, `System.fetch_env/1` and + `fetch_env!/1`, `System.get_env/2`, `:os.getenv/0`, `/1` and `/2`, + `:os.env/0`, and indirect application of any of them through `apply/3` or a + captured function. Each route it does not pin is refuted outright. The + narrower scan is what lets an environment read return by a name the current + expression does not match, which is the drift the case exists to catch. +- **Resolution failures.** One case per row of the failure table above: absent + reference, malformed reference, a resolver module without the callback, a + refusing resolver, a resolver that does not answer before the invocation + deadline, a value outside the size bound, and two resolutions in flight at + once. Each asserts the refusal, its stable reason, that no child was spawned + where the contract says none is, and that no message, exit reason or crash + report from the invocation carries the resolver's value. +- **Host custody.** For each reference host — the CLI, the app-server host and + the daemon — composition reads the variable exactly once, deletes it, and + the holding process's `format_status/1` redacts its state under a forced + crash report. -The first two belong in `credential_plane_test.exs` beside the cases they -generalise; the third stays where it is. +The first two, the failure cases and the custody cases belong in +`credential_plane_test.exs` beside the cases they generalise; the drift case +stays where it is. Two details of that case matter to whoever writes the change. The literal `"LOOPEX_PROVIDER_API_KEY"` it pins today lives in `provider_bridge.ex:401`, inside the credential sender, while `credential_variable/0` and its module attribute live in `req_llm.ex:49` and -`:149-150`; only the first disappears. So `adapter_test.exs:50`'s +`:149-150`; only the first disappears. The arity-zero enumeration the case +also pins lives in `provider_launcher.ex:23-27`, and it does not disappear — +it moves to composition, so the file that holds it afterwards is a host +composition site rather than the adapter's call path. So `adapter_test.exs:50`'s `assert variable == "LOOPEX_PROVIDER_API_KEY"` is, afterwards, a pin on the host-facing accessor — the one name an operator configures — and that is what it should say it is. The neighbouring case `a missing credential is reported @@ -165,10 +256,13 @@ The review is an acceptance point of M5 Outcome 6, read by someone other than the implementer, over the exact diff. It answers: where the reference is held between the call and the send; that the resolved value has no path into guardian state, a message, an exit reason, a crash report, an IO request, a -file or the environment; that a failed or partial send leaves no retained -copy; that the deadline, cleanup and abandonment paths do not resurrect one; -and that a host supplying no reference is refused rather than falling back to -an ambient read. Its record is retained with the milestone's evidence. +file or the environment; that every row of the failure table refuses without +retaining a copy; that the deadline, cleanup and abandonment paths do not +resurrect one; that a host supplying no reference is refused rather than +falling back to an ambient read; and, on the host side of the boundary, that +each reference implementation reads the operator's variable once, deletes it, +redacts the holding process's state, and hands the adapter a reference that +carries no bytes. Its record is retained with the milestone's evidence. ### Concurrency, as a measurement @@ -196,10 +290,11 @@ child built from the same manifest digest behaves identically; the build manifest is not revised by this decision. The one visible change is host composition: a host that starts a runtime with -this adapter supplies a credential reference with the call. The reference CLI -and the real-provider lane keep reading `LOOPEX_PROVIDER_API_KEY` where they -compose, so an operator's setup is unchanged and the release check's -credential frame is unchanged. An embedder that relied on the adapter reading +this adapter supplies a credential reference with the call and owns the bytes +behind it. The reference CLI, the app-server host, the M5 daemon and the +real-provider lane keep reading `LOOPEX_PROVIDER_API_KEY` where they compose, +and delete it there, so an operator's setup is unchanged and the release +check's credential frame is unchanged. An embedder that relied on the adapter reading the environment for it must pass the reference instead; that is the refusal path, not a silent fallback, and it is stated in the operator and developer documentation the milestone updates. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 955dfdc2d..5cfb0b712 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -38,21 +38,46 @@ measured the result at M4 closure — that application is the critical path of the fast check, 96% of its time sits in those twelve modules, and no further test change shortens the check while the slot is shared. -**Decide that the credential is a per-invocation input, delivered on the -child's private channel and never resident in any process-wide slot.** The -host supplies the credential to the adapter with the call, as an opaque -reference it owns; the adapter resolves that reference to bytes only inside -the minimal sender process that writes the credential frame, and only after -the child has proved its nonce, codec version and build manifest digest. The -adapter reads no environment variable for the credential. Nothing else -changes about where the credential may go: it is never in the child's -environment, never in argv, never in the journal, a public event, a snapshot, -a progress item or a diagnostic, never in a process state, a message, an exit -reason or a crash report, and never written to a file. The operator still -names the credential once, to the host, through the same environment variable; -the host reads it where it composes the runtime and holds a reference from -then on, so the variable is a configuration input rather than a live transport -for every call. +**Decide that the credential is a per-invocation input, resolved only inside +the process that writes it to the child's private channel.** The host supplies +the adapter, with each call, a *credential reference*: bounded plain data +naming a host-owned resolver, never the bytes themselves. The adapter resolves +that reference exactly once per invocation, inside the minimal sender process +that writes the credential frame, and only after the child has proved its +nonce, codec version and build manifest digest. The adapter reads no +environment variable for the credential, and no resolved value exists anywhere +but that one process's own stack for the duration of one send. A call that +carries no reference is refused before any child is spawned, which is the +refusal a missing environment variable produces today. + +**The resolution boundary is where the adapter's claims stop.** Inside it — the +reference, the sender, the frame, the child — the adapter proves what it says: +the value is never in the child's environment, in argv, in the journal, in a +public event, a snapshot, a progress item or a diagnostic, in adapter process +state, a message, an exit reason, a crash report or an IO request, and never +written to a file. Outside it, custody belongs to the host and the adapter +proves nothing about it. This pair therefore states the reference +implementations' custody as their own obligation rather than claiming a +property of every host that might supply a resolver. + +The operator still names the credential once, through the same environment +variable, and the reference implementations — the CLI, the app-server host and +the M5 daemon — read it exactly once where they compose the runtime and delete +it from the VM's environment in the same step, holding the bytes behind the +resolver from then on. The variable is a configuration input consumed at +composition, not a live transport for every call, and from the moment +composition completes the parent VM's environment carries no credential. M5 +Outcome 6's claim is stated at that boundary: a claim that the variable is +never set at all would contradict the way an operator supplies a secret to a +process they start. + +One enumeration leaves the call path with it. The launcher's first spawned +image is `/usr/bin/env`, whose own environment the port can only clear name by +name, so the launcher enumerates the parent's environment on every launch +today. That snapshot moves to composition, under the same ADR 0019 constraint +that already forbids the host to introduce environment names while it is in +use, and is carried in the launch configuration the adapter already builds. No +per-invocation path then reads the environment for any purpose at all. **Alternatives rejected.** Keeping the environment variable and buying the speed by sharding the provider suite across test VMs was rejected: it is @@ -67,16 +92,33 @@ frames, without removing a single place the credential can be observed. Widening the existing bootstrap frame to carry the credential alongside the manifest digest was rejected because the child must prove its identity before it is handed a secret, and that frame is sent before the child has proved anything. +Carrying the credential bytes in the per-invocation configuration, rather than +a reference, was rejected because the bytes would then sit in adapter state, +in the messages that configuration travels in, and in any crash report that +prints it — the retention this decision exists to remove. A single +adapter-level credential set once at composition was rejected because it is +the process-wide slot again one level down: two concurrent invocations with +different credentials could not be independent, which is half of what this +decision buys. A resolver supplied as a function was rejected because a +closure is not plain boundary data and its captured environment is exactly the +retention the security review has to exclude. **Evidence its acceptance requires.** This is a trust claim, so its class is negative tests plus a security review, with a real-provider proof for the path the release check already runs. Every credential-plane negative that M0 to M2 established is re-pointed at the new handoff and must hold with its assertion unchanged in meaning; the parent VM's environment is proved empty of the -credential before, during and after a call; two invocations running at once -are proved unable to observe each other's credential; and a named reviewer -reads the handoff — resolution point, frame ordering, failure paths and every -place a value could be retained — and records the reading with the milestone. +credential from the completion of composition onward — before, during and +after a call; two invocations running at once are proved unable to observe +each other's credential; every resolution failure the contract names — absent +reference, refusing resolver, a resolver that does not answer within the +invocation's deadline, a value outside the size bound, and two resolutions in +flight at once — is proved to refuse with a bounded non-secret reason and to +leave no retained copy; the adapter's library tree is proved to read no +environment variable for a credential by any route; and a named reviewer reads +the handoff — resolution point, frame ordering, failure paths, the host +reference implementations' custody, and every place a value could be retained +— and records the reading with the milestone. The real-provider lane in `bash scripts/check-release.sh` proves the path still reaches a real provider. The concurrency result is a measurement recorded beside the M4-closure baseline, not a pass condition. @@ -91,11 +133,12 @@ has: the secret exists in the parent only inside one short-lived process that does nothing but send it, and in the child that needs it. Two invocations in one VM become independent, so the twelve provider test modules can run concurrently and the fast check stops being pinned by that application. Host -composition gains one explicit input: a host that starts a runtime with this -adapter says which credential reference the adapter is to use, instead of -relying on the VM's environment being right at call time. A host that supplies -no reference gets the adapter's ordinary refusal to dispatch, which is what a -missing environment variable produces today. +composition gains one explicit input and one explicit obligation: a host that +starts a runtime with this adapter says which credential reference the adapter +is to use, instead of relying on the VM's environment being right at call +time, and it owns where the bytes live behind that reference. A host that +supplies no reference gets the adapter's ordinary refusal to dispatch, which +is what a missing environment variable produces today. Nothing public changes. This is adapter-internal: no Model callback, no public event, snapshot, artifact, wire method or protocol generation, no durable diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index ac21d7c4e..d28cad8cc 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -20,7 +20,7 @@ decision named only in prose declares nothing. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 1 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and operator root-retirement procedure documented; the daemon-grade adapter, its experiments and its migration reserved for the successor milestone | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or the core attachment change lands, so before workstreams 2 and 4 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 3 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5 | The credential as a per-invocation input resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; no environment read in the adapter's call path; the re-pointed credential-plane proofs and the security review as acceptance points | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by a `{resolver_module, reference_term}` reference the host owns, resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; the resolver's owner, custody, rotation, deadline bounding and every failure outcome; no environment read in the adapter's call path and the launcher's enumeration moved to composition; the re-pointed credential-plane proofs and the security review as acceptance points | ADR 0031's daemon-grade adapter, its contract experiments and its migration belong to the successor milestone and bind nothing in M5; only its @@ -43,7 +43,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session stop, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity or any durable record | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | -| `loopex_llm_reqllm` | The credential handoff, its sender, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, or anything outside the adapter | +| `loopex_llm_reqllm` | The credential handoff, its sender, the resolver behaviour it declares, the launch configuration that carries the composition-time environment snapshot, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | **Rejoin order.** Prerequisite decisions first. Then the new application with @@ -108,7 +108,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. Every daemon boundary emits its ADR 0030 spans and a daemon-scoped trace session captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | The parent VM's environment holds no credential under the adapter's name, and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an empty expected list for `provider_bridge.ex`, so it proves the adapter's library tree reads no environment variable for a credential at all. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table refuses with its stable reason and retains no copy: absent reference, malformed reference, a resolver module without the callback, a refusing resolver, a resolver silent past the invocation deadline, a value outside the size bound, and two resolutions in flight at once. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -292,8 +292,16 @@ daemon is a host and a host is an application. One socket listener, one narrow core concurrent-attachment change, one in-memory lease record and one admission check, one resident window and eviction policy, one per-connection output buffer, one session index with bounded pages, three CLI commands and -the Node client's socket mode. Outcome 6 adds no module and no abstraction: it -changes where one value is resolved and deletes an environment read. +the Node client's socket mode. Outcome 6 adds exactly one abstraction, the +one-callback `Loopex.LLM.ReqLLM.CredentialResolver` behaviour, because the +reference has to travel in configuration that is copied between processes and +may be printed by a crash report, so it must be plain boundary data and a +closure cannot be: it unifies the three reference hosts that hold a credential +today — the CLI, the app-server host and the daemon — and any embedder that +holds one elsewhere. Beside it, each reference host gains one holding process +for the one value it already reads. Nothing else: the change otherwise moves +where one value is resolved and deletes two environment reads from the call +path. Nothing else. No lease, transport, byte limit or residency policy in core; no second loop, event dispatcher, cancellation path or protocol codec; no diff --git a/docs/plans/M5.md b/docs/plans/M5.md index db069c321..61786d98b 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -52,7 +52,7 @@ loop. | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with exact reconnect, retained encoded-event bytes within the daemon-owned bounds, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with every daemon boundary emitting the accepted telemetry spans; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, compiles and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and the parent VM's environment never carries it; every existing credential-plane negative proof holds against the new handoff; and the adapter's library tree is proved to read no environment variable for a credential at all. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's environment enumeration has left the per-invocation call path. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -114,7 +114,13 @@ or backup tooling enters M5. The credential handoff to a provider child moves from the process-wide environment variable the adapter reads inside each call to the per-invocation private channel the launcher already opens for the nonce and the build -manifest. The maintainer set this as an M5 outcome on 2026-09-19 for two +manifest. The host supplies a credential reference with each call and owns +where the bytes live behind it; the reference hosts — the CLI, the app-server +host and the daemon — read the operator's variable once where they compose and +delete it there, so the claim about the parent VM's environment is stated from +the completion of composition onward rather than for all time. ADR 0034 fixes +the reference's shape, the resolver's owner, when it is resolved, how rotation +behaves, what bounds it, and what every failure does. The maintainer set this as an M5 outcome on 2026-09-19 for two reasons. A credential that must sit in the parent VM's environment for the duration of every call is a weaker property than one that exists only on a private channel to the child that needs it; and that shared slot is what makes @@ -160,8 +166,11 @@ isolated hands, ACP mapping, public-protocol freeze, hosted store, Hex package, binary, installer or service-manager integration. Generation 2 adds daemon methods and lease fields only; no other protocol breadth. Outcome 6 changes where a credential is resolved and nothing about what a child may do -with it: no new credential scope, no host credential store, no change to the -`Loopex.Model` callbacks or to ADR 0019's process topology. Those capabilities +with it: no new credential scope, no credential store, vault or rotation +service beyond each reference host holding the one value it already reads at +composition, no change to the `Loopex.Model` callbacks or to ADR 0019's +process topology. The `req_llm` move to `1.24` is an ordinary dependency +change and adds no dependency, no adapter capability and no provider surface. Those capabilities retain their vision barriers and require their own evidence. Technical depth: [Deferral acceptance points](M5-technical.md#technical-plan-prerequisites). @@ -177,7 +186,7 @@ implementation that depends on it, not before unrelated work. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and operator root-retirement procedure documented; the daemon-grade adapter, its selection experiments and its migration are the successor milestone's | 1, 5 | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the adapter reads no environment variable for it | 6 | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by a host-owned reference and resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the reference's shape, the resolver's owner, custody, rotation, bounding and every failure are exact; the adapter reads no environment variable for it and its enumeration leaves the call path | 6 | Three accepted decisions remain load-bearing and are not reopened: M4's ADR 0023 fixes the protocol M5's generation 2 extends and M4's ADR 0030 fixes @@ -294,11 +303,21 @@ runs last because it describes what the others built. daemon-side residency above it: the resident window, per-connection output buffers, detachment at the last emitted cursor, idle eviction and the aggregate byte ceiling. -5. **The credential handoff.** ADR 0034's change to the provider adapter, the - re-pointed credential-plane proofs, the two new proofs, its own security - review by someone other than its implementer, and the measured effect on - the provider suite once its modules can run concurrently. It touches no - daemon code and shares no file with the other workstreams. +5. **The credential handoff and the provider dependency.** ADR 0034's change + to the provider adapter and to the host composition sites that read the + operator's variable, the re-pointed credential-plane proofs, the new proofs + of the resolver contract and its failures, the launcher's enumeration + moving to composition, its own security review by someone other than its + implementer, and the measured effect on the provider suite once its modules + can run concurrently. This workstream also carries one bounded dependency + item: `req_llm` moves from `~> 1.17.1` to `~> 1.24` in + `apps/loopex_llm_reqllm/mix.exs` and `mix.lock`. It is an ordinary + dependency decision, so it lands as its own reviewed change, naming the + version floor, the reviewed changelog diff across the intervening releases, + the adapter and streaming-conformance suites green, and the real-provider + case at closure. It is sequenced before the credential change where both + touch the adapter, so the credential proofs are written once against the + upgraded library rather than twice. 6. **Documentation and the `0.2.0` release candidate.** The operator daemon guide and the developer daemon pair, the updates M5 forces on the existing operator and developer pages, the changelog and the indexes, the `VERSION` From da1df88f2d1994549a2ae2ed7f6779ae475c1671 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:39:24 -0700 Subject: [PATCH 010/585] adr(M5): bind capacity, inventory, residency and stale-writer recovery Audit findings 2, 3, 4 and 5, each verified in code before the documents changed. Finding 2 holds. Loopex.Store.Local.Log.append/3 admits size at log.ex:186 and refuses with store_capacity_exceeded at log.ex:454-459, before the log is opened for writing. Loopex.Store.Local treats that like every other append error: the with at local.ex:251-253 falls to {:stop, reason, unknown(transaction), state} at local.ex:269-270, so the Store process terminates and the caller is told commit_unknown. The plan's "refuses further mutation while observers stay attached" could not hold on an unchanged adapter. Capacity is now recorded as store loss: the daemon closes the socket and every connection and exits naming it. The Store change that would make capacity definite and survivable is recorded as rejected, with its conformance and fault-matrix cost. Finding 3 holds. Loopex.SessionDirectory says at session_directory.ex:26-30 that neither of its files is Store durable truth, and Loopex.track_session at loopex.ex:433-439 is called after create_session/3 commits, so there is a real crash cut; loopex_cli.ex:604-615 already reports that write failing. Its entry type carries session_id and runtime_id only, so lineage, lifecycle state and committed sequence could never have been kept current. session.list is narrowed to what the root records with four daemon-ownable fields, the crash cut is added, and the recovery procedure records the entry at the activation that reaches the session by ID. Finding 4 holds. Core exposes no durable session stop (loopex.ex), so session.stop could only have been a new core durable command; it is withdrawn from generation 2 and from ADR 0033's mutation list. Active and dormant residency, lazy recovery, a 64 active-session ceiling, a 4,096-entry index bound, and one-composition-per-root homogeneity reported at activation are defined, with their numbers in the plan's ceiling table. Finding 5 holds. :recover_stale_writer defaults to false at local.ex:78 and loopex_composition.ex:58,225. The daemon now binds it explicitly, and the dead, live and unverifiable holders are proved before the socket path is read, unlinked or bound. --- ...store-selection-and-migration-technical.md | 47 ++++++-- ...mon-grade-store-selection-and-migration.md | 50 +++++--- ...tachment-residency-and-replay-technical.md | 111 +++++++++++++++--- ...-daemon-attachment-residency-and-replay.md | 41 +++++-- ...controller-lease-and-takeover-technical.md | 2 +- docs/plans/M5-technical.md | 15 ++- docs/plans/M5.md | 86 +++++++++++--- 7 files changed, 279 insertions(+), 73 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 283083e3a..42539cd69 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -19,15 +19,40 @@ daemon's limits, and every one is an existing constant or refusal of - one append-only, length-prefixed, digest-checked log per state root, held by one operating-system process through the writer marker with the `store_writer_active` and `store_writer_unverifiable` refusals; -- a hard log capacity of 256 MiB (`@max_log_bytes`): an append that would - exceed it refuses with `store_capacity_exceeded`, and a log already larger - than the bound refuses at open with `store_log_too_large`; +- a hard log capacity of 256 MiB (`@max_log_bytes`): the size admission at + `Loopex.Store.Local.Log.append/3` refuses with `store_capacity_exceeded` + before the log is opened for writing, and a log already larger than the + bound refuses at open with `store_log_too_large`; +- one consequence of that refusal, which the daemon inherits and must state: + `Loopex.Store.Local` treats every `append` error alike. The refusal falls + through the `commit_new` clause to `{:stop, reason, commit_unknown, state}`, + so the Store process terminates and the caller is told `commit_unknown`. + Physically nothing was written; contractually the transaction is ambiguous + and the store is gone. The daemon therefore cannot keep observers attached + past a capacity refusal, and does not claim to: it closes the listener and + every connection and exits, naming the capacity. Changing that would be a + change to the adapter's own contract, which this ADR does not make; - a 4 MiB frame ceiling (`@max_frame_bytes`) on any single record; - full-history retention: no compaction, no retention cutoff, and full replay at every open, so replay time and memory grow with the root's history until the root is retired; -- session discovery through the existing session directory beside the log, - which lists every session the root knows. +- stale-writer recovery off by default. `:recover_stale_writer` defaults to + `false` in `Loopex.Store.Local` and in `LoopexComposition`, so a marker left + by a daemon that was killed refuses every later open with + `store_writer_active` until something asks for recovery. The daemon asks for + it explicitly, which is what makes kill-and-restart work, and inherits the + adapter's discipline unchanged: the marker is reclaimed only where its own + recorded holder is probed and found dead, an unverifiable holder leaves the + marker in place with `store_writer_unverifiable`, and a live holder refuses + with `store_writer_active`; +- session discovery through the existing session directory beside the log. + That directory is plain files, not Store truth: `Loopex.SessionDirectory` + says so itself, and a host writes an entry after `create_session/3` commits, + so a process that dies in between leaves a session the Store holds and the + directory does not. Nothing is lost — the Store remains the authority and + the session is reached by its ID — but no enumeration built on the directory + may claim to list every session the root contains, and the daemon's index + does not. Root retirement is an operator procedure, not a store operation: stop the daemon so the marker is released; move the root directory aside under a name @@ -38,11 +63,13 @@ foreground server. The daemon's operator documentation states the capacity, the refusal reason, the frame ceiling, full retention and this procedure. Evidence for the M5 selection is the M5 plan's Outcome 1 obligation, not a -second copy here: a root driven to the capacity ceiling refuses further -mutation with the store's own reason while observers stay attached and an -orderly stop still succeeds, and after that stop the foreground server reopens -the same root. No new conformance evidence is required, because the adapter -and its suites are unchanged. +second copy here: a root driven to the capacity ceiling refuses the append +with the store's own reason and takes the daemon's listener and connections +down with it, a root already past the bound refuses at open, a stale marker is +recovered where its holder is proved dead and refused where it is not, and +after an orderly stop the foreground server reopens the same root. No new +conformance evidence is required, because the adapter and its suites are +unchanged. ### Boundary diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 806dee56f..f39e0494f 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -34,13 +34,18 @@ daemon holds the local writer marker for its process's lifetime and inherits the adapter's exact, documented limits: one append-only log per state root with a hard 256 MiB capacity, a 4 MiB frame ceiling, full-history retention with no compaction, full replay at open, and one writer per root. Reaching -capacity is a truthful refusal, never a silent loss: the adapter answers -`store_capacity_exceeded`, the daemon refuses further mutation with that -reason while observers stay attached and an orderly stop still succeeds, and a -log already past the bound is refused at open as `store_log_too_large` rather -than opened and truncated. The operator retires the root by stopping the -daemon, moving the root aside and starting a fresh root. Sessions in a retired -root are resumable only by reopening that root. +capacity is a truthful stop, never a silent loss, and it is not survivable on +this adapter. The append is refused before a byte is written, with +`store_capacity_exceeded`; the adapter then terminates its Store process and +the caller receives `commit_unknown` for that transaction, because that is +what this adapter does with every append error. So the daemon meets capacity +as a loss of the store, not as a recoverable refusal: it closes the listener +and every connection and exits, naming the capacity in the close, and the +operator retires the root. A log already past the bound is refused at open as +`store_log_too_large` rather than opened and truncated. Nothing committed is +lost and nothing false is recorded, which is what the truthfulness claim +means here. Sessions in a retired root are resumable only by reopening that +root. This is a bounded, experimental selection made on evidence the local adapter already carries; it is not a daemon-grade store, and the 0.2.0 daemon's operator documentation states these limits and the @@ -83,16 +88,29 @@ engine, its fault matrix, its migration and its rollback — without adding a proved capability to the durable-service question M5 exists to answer. Raising or removing the local log's 256 MiB capacity to postpone retirement was rejected because a silently growing log trades a truthful refusal for an -unbounded replay at open. Mnesia and DETS were rejected as successor +unbounded replay at open. Changing the local adapter so that a capacity +refusal is definite and survivable — answered as a plain refusal without +terminating the Store, so a daemon could keep its observers attached and stop +in an orderly way — was rejected for M5 on 2026-09-19. It is a change to the +Store's own behaviour at the one point where that behaviour is most +load-bearing: today every append error is commit-ambiguous, and separating one +error class from the rest means proving, through the shared conformance suite +and the fault matrix on every adapter, that the separated class is definite in +every injection and that no other class quietly joins it. That is the +successor adapter's evidence, and buying it here would double M5's store +evidence to make one operator message nicer. Until then the daemon's capacity +behaviour is the adapter's, stated plainly rather than promised away. Mnesia and DETS were rejected as successor candidates for the reasons the companion records. **Evidence its acceptance requires.** The M5 half is a durability claim, so its class is process and store fault injection on the real adapter plus a -rollback proof: a root driven to capacity refuses further mutation with the -store's own reason while observers stay attached, an orderly stop still -succeeds, and the foreground server and reference CLI then reopen the same -root. No new conformance evidence is required, because the adapter and its -suites are unchanged. The successor half claims a new engine and a migration, +rollback proof: a root driven to capacity refuses the append with the store's +own reason, terminates the store, and the daemon closes the listener and every +connection and exits naming the capacity, with nothing committed lost; a root +already past the bound refuses at open; and after an orderly stop on a root +below the bound the foreground server and reference CLI reopen it. No new +conformance evidence is required, because the adapter and its suites are +unchanged — which is the point of selecting it. The successor half claims a new engine and a migration, so its class is the full store conformance suite, the fault matrix, bounded replay measurement, backup and restore, forward migration with interrupted- import recovery, and safe refusal by the exact previous binary; none of it is @@ -116,8 +134,10 @@ The daemon and its clients see the same durable session truth the embedded API and the foreground server see; the store adapter is a host choice, not a semantic one. In M5 the foreground server, the reference CLI and the daemon all run on the local adapter and can reopen one another's roots. A root that -reaches the local log's capacity stops accepting mutation and is retired by -the operator; nothing already committed is lost. The private journal format +reaches the local log's capacity takes its daemon down with it and is retired +by the operator; nothing already committed is lost, and the operator +documentation says plainly that capacity is an outage rather than a +degradation, so that the ceiling is planned for rather than discovered. The private journal format is a separate compatibility surface: adding an adapter later freezes no wire, artifact or embedded contract, and the exact private format stays experimental in 0.x. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index bf812299b..c078a2122 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -22,7 +22,15 @@ Startup order is fixed. The daemon first opens the state root through the local adapter and acquires its writer marker; a daemon that does not hold the marker refuses with the adapter's `store_writer_active` or `store_writer_unverifiable` reason and never reads, unlinks or binds the -socket path. Only the marker holder may remove a stale `daemon.sock` left by +socket path. The daemon opens the root with `recover_stale_writer: true`, +explicitly, because that option defaults to `false` in both +`Loopex.Store.Local` and `LoopexComposition` and a daemon that did not ask for +it could never restart after being killed. Asking for it is not asking to +ignore a holder: the adapter reclaims the marker only where it probes the +recorded holder and finds it dead, leaves it in place with +`store_writer_unverifiable` where the holder cannot be decided, and refuses +with `store_writer_active` where the holder is alive. All three are proved +before the socket path is read, unlinked or bound. Only the marker holder may remove a stale `daemon.sock` left by a dead daemon and bind a new one, so two simultaneous starts on one root resolve at the marker, exactly one listener exists, and the loser exits without touching the socket. If the daemon loses store ownership while @@ -66,21 +74,87 @@ enforced inside core. | Method | Required fields | Result | | --- | --- | --- | -| `session.list` | `limit` (1 to 256), optional `after_session_id` | A page of at most `limit` session entries ordered by session ID bytes ascending and starting strictly after `after_session_id`; each entry carries session identity, lineage, lifecycle state, last committed sequence and controller presence, never content; `next_after_session_id` is present exactly when more entries exist | -| `session.stop` | `session_id`, `command_id`, `writer_epoch` | Admission of a durable stop under the current controller; observers refuse | -| `daemon.status` | none | Placement identity, daemon incarnation, socket path, attachment and session counts against their limits, uptime | +| `session.list` | `limit` (1 to 256), optional `after_session_id` | A page of at most `limit` index entries ordered by session ID bytes ascending and starting strictly after `after_session_id`; each entry carries the session identity, the placement identity recorded for it, `residency` of `active` or `dormant`, and `controlled` as a boolean, never content and never durable session state; `next_after_session_id` is present exactly when more entries exist | +| `daemon.status` | none | Placement identity, daemon incarnation, socket path, attachment, active-session and index counts against their limits, uptime | | `session.acquire_control`, `session.release_control` | `session_id`, `request_id` and the lease fields ADR 0033 fixes | Lease result naming the writer epoch and the remaining lease term | +### The session index, and what it may claim + `session.list` reads a daemon-owned index, never the session directory or the -store on the request path. The index is built once at daemon start from the -session directory and updated when the daemon creates, resumes or stops a -session; it is rebuilt only by a daemon restart. A page is consistent with -the index at the moment it is read; no consistency is promised across pages, -so a session created or stopped between pages may appear in neither or both, -and a client that needs a stable view deduplicates by session ID. A `limit` -outside 1 to 256 or an `after_session_id` that is not a well-formed session -ID refuses with the existing invalid-argument reason; an `after_session_id` -naming an unknown session is admitted and pages from its byte position. +store on the request path. What the index *is* follows from what it is built +from. `Loopex.SessionDirectory` holds plain files beside the log and states +that neither is Store durable truth; a host records an entry after +`create_session/3` commits, and that write can fail on its own — the reference +CLI reports exactly that failure to the operator. So there is a real crash cut +between a committed session and its directory entry, and a daemon rebuilt from +the directory can be missing a session the Store holds. + +The index therefore claims only what it can keep true, and each field is one +the daemon itself owns or reads once: + +- `session_id` and the recorded placement identity, read from the directory + entry at daemon start, or written when the daemon first activates a session + the directory does not hold; +- `residency`, a daemon fact, updated on every activation and every transition + to dormant; +- `controlled`, a daemon fact, updated on every lease grant, release and + expiry by the same per-session owner ADR 0033 gives those transitions. + +Lineage, lifecycle state and last committed sequence are deliberately absent. +A daemon index cannot keep them current without reading the Store on the +request path or subscribing to every session it is not holding, and a field +that is silently stale is worse than an absent one; a client that needs them +attaches, and the snapshot carries them at a committed sequence. + +The recovery procedure for the crash cut is explicit and needs no new durable +record. A session absent from the index is still reachable by its ID: a client +that knows the ID acquires control and resumes it, the Store answers because +the Store is the authority, and the daemon records the directory entry as part +of that activation, so the session appears in every later listing. The +operator documentation states this, because an operator who lost a terminal +mid-creation is exactly who meets it. `session.list` is documented as *the +sessions this root records*, not *the sessions this root contains*. + +A page is consistent with the index at the moment it is read; no consistency +is promised across pages, so a session created or dropped between pages may +appear in neither or both, and a client that needs a stable view deduplicates +by session ID. A `limit` outside 1 to 256 or an `after_session_id` that is not +a well-formed session ID refuses with the existing invalid-argument reason; an +`after_session_id` naming an unknown session is admitted and pages from its +byte position. + +### Session residency: active, dormant, and their bounds + +A session is **active** when the daemon holds a live coordinator for it and +**dormant** when the index records it and the daemon does not. Nothing durable +distinguishes the two; dormancy is a daemon fact and costs a dormant session +nothing. + +- **Lazy recovery.** A restarted daemon activates no session. It acquires the + writer marker, reads the index, binds the socket, and activates a session + the first time a client attaches to, acquires control of or resumes it. +- **Active-session ceiling.** At most 64 sessions are active at once per + daemon. A session that has had no attachment and no admitted command for the + idle interval goes dormant, releasing its slot. An activation that would + exceed the ceiling while every active session is still in use refuses with a + stable reason naming the ceiling; it never evicts a session that a client is + driving or watching. +- **Index bound.** The index holds at most 4,096 entries. A root whose session + directory holds more refuses at daemon start with a stable reason naming the + bound and pointing at root retirement, in the same posture as + `store_log_too_large`: refuse rather than serve a truncated view of what the + root records. +- **Homogeneity.** One state root is one host composition for the daemon's + process lifetime. The daemon is composed once, with one workspace, policy, + provider configuration and set of project resources, and serves every + session in the root under it. A recorded session the current composition + cannot serve — a placement identity it does not hold, or retained + configuration it cannot satisfy — is reported at *activation*, naming the + session and the mismatch, with the existing refusal reasons; it is never a + reason a start fails, because recovery is lazy and start never reads it. The + operator documentation says that mixing compositions in one root means some + sessions will refuse to activate, and that the remedy is one root per + composition. The client supplies its ordered supported generations in `initialize`. The daemon supports exactly `loopex.experimental/2`: it selects that generation @@ -149,7 +223,16 @@ initialize refused with `unsupported_generation` and nothing created; simultaneous daemon starts on one root leaving exactly one listener with the loser never touching the socket; Store-child failure closing the listener and every connection before exit; `session.list` pages of at most 256 entries in -session-ID order with an exact continuation cursor; progress coalescing under +session-ID order with an exact continuation cursor, carrying only the four +fields above; a session committed to the Store whose directory entry was never +written — injected at exactly that cut — absent from the listing, still +reachable by ID, and present in every listing after the activation that +records it; a restarted daemon activating nothing until a client reaches for a +session; the active-session ceiling refusing an activation while every slot is +in use, and admitting one after a session goes dormant; a root whose directory +holds more than the index bound refusing at start with its stable reason; a +recorded session the current composition cannot serve refused at activation by +name while every other session in the root activates; progress coalescing under pressure with counted drops and no journal delay; peer-credential refusal; a socket path beyond the bound refused at start; frame, fragment and malformed-input refusals identical to the foreground server's. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index c2636b96b..21fdbe2df 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -33,9 +33,13 @@ only mean something against a transport. The daemon carries the ADR 0023 JSONL protocol over a Unix-domain socket, reusing its framing, initialize handshake, request, admission, snapshot, event and progress records and limits unchanged, and serves exactly one generation, -`loopex.experimental/2`, which adds `session.list`, `session.stop`, -`daemon.status`, the two control methods and the writer-epoch field ADR 0033 -names. A client that offers only generation 1 is refused at initialize under +`loopex.experimental/2`, which adds `session.list`, `daemon.status`, the two +control methods and the writer-epoch field ADR 0033 names. It adds no durable +method. An earlier draft of this decision also added `session.stop` and called +it durable; that is withdrawn, because core owns durable session truth, core +has no durable stop command, and M5's only core change is concurrent +attachment. Ending work is releasing control and disconnecting, after which +the session goes dormant and `session.resume` brings it back. A client that offers only generation 1 is refused at initialize under ADR 0023's existing no-common-generation rule and nothing durable is created; generation-1 clients keep the M4 foreground server, whose wire, one-attachment rule and behavior do not change. A narrow core change lets @@ -63,14 +67,27 @@ output buffer; a slow attachment is detached at its last completely emitted cursor while every other attachment continues. Idle attachments are evicted at the residency limit and reconnect at their retained cursor with no missing durable event. Transient progress is coalesced or dropped first and -never delays a journal transaction. `session.list` returns bounded pages -with an exact continuation cursor from a daemon-owned index. The proposed +never delays a journal transaction. + +A session is *active* when the daemon holds a live coordinator for it and +*dormant* when the root records it and the daemon does not. Recovery is lazy: +a restarted daemon activates nothing, reads its index, and activates a session +when a client reaches for it. That is what a daemon can honestly promise on a +store whose session directory is not Store truth and whose every open replays +a full log. `session.list` returns bounded pages, with an exact continuation +cursor, over a daemon-owned index of what the root *records* — identity, +recorded placement identity, active or dormant, controlled or not — and never +over what the Store contains, because no index built from the session +directory can claim that. Lineage, lifecycle state and committed sequence are +not list fields: a client that needs them attaches and reads the snapshot. +The proposed limits are exact and are bound at acceptance: 64 attachments per session, 512 per daemon, a 1,024-event core queue per attachment, a 4,096-event resident window per session, 4 MiB of encoded output buffered per connection, 16 MiB of encoded resident-window events per session, 512 MiB of aggregate retained encoded events per daemon, ten minutes of idle time -before eviction, 256 sessions per list page, and the ADR 0023 frame ceiling +before eviction, 64 active sessions per daemon, 4,096 index entries per root, +256 sessions per list page, and the ADR 0023 frame ceiling unchanged. Count and byte ceilings apply together; an event that would exceed either triggers the stated detachment, eviction or refusal behavior before the ceiling is crossed. @@ -87,8 +104,16 @@ to preserve the subscribe/snapshot race. Promising exactly-once replay was rejected on 2026-09-14 because at-least-once with client deduplication is the founding contract and no other surface honors more. Removing `session.list` was rejected the same day because an observer without filesystem access to the -root would have no way to discover sessions. The companion records each in -full. +root would have no way to discover sessions. Rebuilding an authoritative +inventory by enumerating the Store, and writing the inventory entry inside the +session-creating transaction so it is crash-atomic with the commit, were both +rejected on 2026-09-19: each is a change to the Store port or to the local +adapter's transaction shape, and both are exactly what M5's selection of the +unchanged adapter declines to buy. Activating every recorded session at +daemon start was rejected the same day: the local adapter replays a full log +at every open, so startup cost would grow with the product of session count +and history, and a root with one unservable session would fail a start that +need never have read it. The companion records each in full. **Evidence its acceptance requires.** Two classes together. The transport and its generation are a protocol claim, so they need vectors and a compatibility diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index be2bba846..b44f4109b 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -65,7 +65,7 @@ the local store's writer marker, unchanged. `session.acquire_control` from the holder, which extends the deadline without changing the epoch. - Every existing-session mutation in generation 2, including - `session.resume`, `session.stop`, `session.prompt`, `session.steer`, + `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, `session.respond_interaction`, `session.admit_resources` and `session.activate_skill`, carries `writer_epoch`. The daemon admits it only if the sending connection is the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d28cad8cc..0451fa8d7 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -40,7 +40,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | -| `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session stop, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity or any durable record | +| `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session residency between active and dormant, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | | `loopex_llm_reqllm` | The credential handoff, its sender, the resolver behaviour it declares, the launch configuration that carries the composition-time environment snapshot, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | @@ -103,7 +103,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. Sessions progress with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart recovers every session under the same placement identity with no duplicate effect. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses further mutation with `store_capacity_exceeded` while observers stay attached and an orderly stop still succeeds, and a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. Session open and stop through the socket only | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. The active-session ceiling refuses an activation while every slot is in use and admits one after a session goes dormant; a root whose directory exceeds the index bound refuses at start; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its own generation, and a generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -224,8 +224,9 @@ by stopping one and starting the other. Prove that an orderly daemon stop releases the writer marker and that the foreground server and the CLI then resume a daemon-created session with identical replay. -A root that reaches the local log's 256 MiB capacity is retired, not migrated: -stop the daemon, move the root aside, start a fresh root. A root already past +A root that reaches the local log's 256 MiB capacity is retired, not migrated. +The daemon has already exited by then, because the capacity refusal terminates +the store; the operator moves the root aside and starts a fresh root. A root already past that bound refuses at open with `store_log_too_large`, which is the message the operator page must explain, because it is what an operator meets when a root grew past the ceiling under an earlier process. A session in a @@ -316,7 +317,7 @@ decision named above; M5 introduces none of its own. | Ceiling | Value | Source | | --- | --- | --- | -| Log capacity per state root | 256 MiB; an append past it refused as `store_capacity_exceeded`, a log already past it refused at open as `store_log_too_large` | ADR 0031 | +| Log capacity per state root | 256 MiB; an append past it refused as `store_capacity_exceeded`, which terminates the store and closes the daemon, a log already past it refused at open as `store_log_too_large` | ADR 0031 | | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | | Attachments per session | 64 | ADR 0032 | @@ -325,7 +326,9 @@ decision named above; M5 introduces none of its own. | Daemon socket output buffer per connection | 4 MiB encoded | ADR 0032 | | Resident window per session | 4,096 events and 16 MiB encoded | ADR 0032 | | Aggregate retained encoded events per daemon | 512 MiB | ADR 0032 | -| Idle time before eviction | 10 minutes | ADR 0032 | +| Idle time before eviction, and before an unused session goes dormant | 10 minutes | ADR 0032 | +| Active sessions per daemon | 64; a further activation refused while every slot is in use | ADR 0032 | +| Session index entries per root | 4,096; a root whose directory holds more refused at daemon start | ADR 0032 | | `session.list` page | at most 256 entries, `limit` in 1 to 256 | ADR 0032 | | Socket path bound | the platform's, 104 bytes on Darwin and 108 on Linux, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 61786d98b..9505f1bda 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -47,7 +47,7 @@ loop. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root: sessions run while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon recovers every session under the same placement identity, a second daemon on the same root loses at the store writer marker before touching the socket, losing the store closes the socket and every connection, a root at the local log's capacity refuses further mutation truthfully while observers stay attached, sessions are listed in bounded pages, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root: an active session runs while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated and a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with exact reconnect, retained encoded-event bytes within the daemon-owned bounds, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -71,8 +71,28 @@ may take control but never widens what host policy allows. The socket reuses ADR 0023's framing, initialize handshake, request, admission, snapshot, event and progress records and limits unchanged, and serves generation `loopex.experimental/2` only, which adds `session.list`, -`session.stop`, `daemon.status`, the two control methods and the writer-epoch -field, and lifts the one-attachment-per-process rule to residency limits. A +`daemon.status`, the two control methods and the writer-epoch field, and lifts +the one-attachment-per-process rule to residency limits. It adds no durable +method: core owns durable session truth and its only M5 change is concurrent +attachment, so a daemon method that ended a session durably would have to add +a durable command to core, which M5 does not do. Ending work is releasing +control and disconnecting; the daemon then lets the session go dormant, and +`session.resume` brings it back. + +`session.list` is a daemon convenience, not an enumeration of durable truth. +It answers from a daemon-owned index built at start from the state root's +session directory, and that directory is not Store truth: a process that +commits a session and dies before the directory entry is written leaves a +session the Store holds and the directory does not. So `session.list` promises +exactly what it can keep true — the sessions this root records, each with its +identity, its recorded placement identity, whether the daemon currently holds +it active, and whether a controller lease is currently held — and no more. +Lineage, lifecycle state and committed sequence are not in a list entry, +because a daemon index cannot keep them current without reading the Store on +the request path; a client that needs them attaches, and the snapshot carries +them authoritatively. A session missing from the list is never a lost session: +it is reached by its ID, and the daemon records the entry when it activates +one the directory does not hold. A client offering only generation 1 is refused at initialize; generation-1 clients keep the M4 foreground server, whose wire and behavior do not change. Attach is the runtime's race-free cursor transaction, and delivery is @@ -102,14 +122,35 @@ two-phase outcome the core already commits. The daemon runs every session on the existing local store adapter, selected for this release by ADR 0031: one state root, the local log the M4 foreground server and CLI already write, and the local writer marker held by the daemon -from before the socket is bound until the daemon exits. The adapter's limits -are the daemon's limits and the operator documentation states them: a hard -256 MiB log capacity refused as `store_capacity_exceeded`, a log already past +from before the socket is bound until the daemon exits. The daemon asks for +stale-writer recovery explicitly, so a marker left by a dead daemon is +reclaimed where the adapter can prove its holder dead and refused where it +cannot. The adapter's limits are the daemon's limits and the operator +documentation states them: a hard 256 MiB log capacity, a log already past that bound refused at open as `store_log_too_large`, a 4 MiB frame ceiling, -full-history retention with no compaction, and full replay at open. A root at -capacity is retired by stopping the daemon, moving the root aside and starting -a fresh root. No new store adapter, journal format version, migration -or backup tooling enters M5. +full-history retention with no compaction, and full replay at open. + +Reaching capacity is not a survivable refusal on this adapter and the plan +does not pretend otherwise. The adapter answers `store_capacity_exceeded` for +the append and terminates the Store process, so the caller receives +`commit_unknown`; the daemon treats that exactly as it treats any other loss +of the store, closing the listener and every connection and exiting, with the +capacity named in the close so an operator is not left guessing. Nothing +committed is lost and nothing false is recorded. The root is then retired by +moving it aside and starting a fresh one; a root whose log is already past the +bound refuses at open rather than being opened and truncated. Making capacity +a definite pre-write refusal that a live daemon survives would be a change to +the Store adapter's own behaviour, with the conformance and fault-injection +evidence that carries; ADR 0031 records why that is the successor's work and +not M5's. No new store adapter, journal format version, migration or backup +tooling enters M5. + +A daemon activates a session when a client reaches for it, not at startup. +Sessions the root records are dormant until then, and the daemon holds at most +a bounded number of active ones at a time; the rest stay dormant and cost +nothing. One root is one host composition, so a recorded session the daemon's +current composition cannot serve is reported at activation, by session, rather +than failing a startup that never reads it. The credential handoff to a provider child moves from the process-wide environment variable the adapter reads inside each call to the per-invocation @@ -255,10 +296,14 @@ stream is promised. An operator running `0.2.0` runs the daemon on the local adapter and lives within its limits: 256 MiB of log per state root, a 4 MiB frame ceiling, full history with no compaction and full replay at open. Reaching capacity is a -truthful `store_capacity_exceeded` refusal, never silent loss; a root whose -log is already past that bound is refused at open as `store_log_too_large` -rather than opened and truncated. The documented recovery is to retire the -root — stop the daemon, move the root +truthful `store_capacity_exceeded` refusal of the append, never silent loss, +and on this adapter it is also the end of that daemon: the store terminates, +the caller sees `commit_unknown`, and the daemon closes the socket and every +connection and exits naming the capacity. The operator page states that +plainly, because capacity here is an outage to plan for rather than a +degradation to ride out. A root whose log is already past that bound is +refused at open as `store_log_too_large` rather than opened and truncated. +The documented recovery is to retire the root — stop the daemon, move the root aside, start a fresh one — after which a session in the retired root is reached only by reopening that root. @@ -284,10 +329,13 @@ before it can be proved; the fifth is independent of all of them; the sixth runs last because it describes what the others built. 1. **The daemon.** One new application, `loopex_daemon`: marker-first startup - on the local adapter, session lifetime with zero attachments, orderly stop - and abrupt death, restart recovery under the same placement identity, the - session index and its bounded pages, shutdown on store loss, capacity - refusal, and reopening under the foreground server after an orderly stop. + on the local adapter with explicit stale-writer recovery, session lifetime + with zero attachments, orderly stop and abrupt death, lazy activation after + restart under the same placement identity, active and dormant residency + with its ceiling, the session index with its bound and its bounded pages, + activation refusal for a session this composition cannot serve, shutdown on + store loss, capacity as one such loss, and reopening under the foreground + server after an orderly stop. 2. **The socket transport.** The listener, its owner-only peer check and path bound, ADR 0023's framing and records reused, generation 2's schema and vectors beside generation 1's, negotiation and the generation-1-only @@ -344,7 +392,7 @@ that adds the tests it names. | # | State | Evidence | | --- | --- | --- | -| 1 | Open | No daemon exists. Session lifetime with zero attachments, marker-first startup, store-loss shutdown, capacity refusal, bounded listing and reopening under the foreground server are its separate witnesses | +| 1 | Open | No daemon exists. Session lifetime with zero attachments, marker-first startup with explicit stale-writer recovery, store-loss shutdown, capacity as store loss, lazy activation and its ceilings, the index crash cut, bounded listing and reopening under the foreground server are its separate witnesses | | 2 | Open | No socket transport exists; generation 2 has no schema or vectors yet | | 3 | Open | No controller lease, writer epoch or takeover exists above core | | 4 | Open | Core replaces an existing same-session attachment today; no independent concurrent attachments, resident window, socket output buffer or eviction exists | From 9367c8976dcae224621cb26a436a7947030efa55 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:41:04 -0700 Subject: [PATCH 011/585] adr(M5): restore one replay owner and bind lease expiry MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit findings 6, 7 and 17. Finding 6 holds as a contradiction inside ADR 0032's own companion: the transport section keeps snapshot barriers, queued durable delivery and the cursor transaction in core, and the attachment-lifecycle section then made the daemon's resident window a replay source deciding what a cursor is owed. Core is now the only replay owner. The window is defined as a droppable encoding cache over events core has already delivered: it anchors no snapshot, establishes no cursor, is never consulted to decide what a client is owed, and may be dropped whole. Every delivery case runs three times — window on, window disabled, window dropped mid-stream — byte for byte identical, which is what makes the claim a proof rather than a promise. Aggregate reclamation is given a fixed deterministic order so the zero-attachment case is testable: zero-attachment windows by ascending last delivery with a session-ID tie-break, then the furthest-behind session's window, and only then detachment. Finding 7 holds. ADR 0033's lease-record section serialises a takeover against an unresolved core admission while its terms promised takeover at expiry with no grace; the two could not both be true without a rule. The rule is now stated in four steps: a check completed before the deadline settles under its lease, the holder gains nothing at the deadline, a takeover is eligible at the deadline but granted only when the in-flight set is empty, and the grant then mints a fresh epoch. Blocked admission across expiry, holder disconnect and lease-owner failure are each required as witnesses. Finding 17 is folded in because it is the same Outcome 4 sentence: "idle eviction with exact reconnect" becomes contiguous at-least-once reconnect with no gap, matching the rest of the outcome and the founding contract. --- ...tachment-residency-and-replay-technical.md | 46 ++++++++++++++++--- ...-daemon-attachment-residency-and-replay.md | 18 +++++--- ...controller-lease-and-takeover-technical.md | 46 +++++++++++++++++-- ...aboration-controller-lease-and-takeover.md | 11 ++++- docs/plans/M5-technical.md | 6 +-- docs/plans/M5.md | 16 ++++--- 6 files changed, 115 insertions(+), 28 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index c078a2122..f3a0dc4b5 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -65,6 +65,9 @@ per-connection socket output buffer of encoded frames not yet written to the socket, bounded at 4 MiB, and the per-session resident window of encoded recent events, bounded at 4,096 events and 16 MiB, and it enforces the 512 MiB aggregate across every output buffer and resident window it holds. +Neither daemon stage owns replay: core owns the cursor and decides what is +owed, and both daemon stages hold only bytes for events core has already +named. When the next event would exceed the core count or a daemon byte bound, the daemon detaches the attachment at its last completely emitted cursor with a stable reason rather than letting either stage grow. No byte limit is @@ -179,12 +182,36 @@ exactly N, and durable events after N are buffered for that attachment and delivered contiguously after the snapshot. The daemon adds: - a resident window of at most 4,096 durable events and 16 MiB of encoded - events per session held in memory; a cursor inside the window replays from - memory and a cursor older than the window replays from the store. On the - local adapter every durable event is retained until the root is retired, - so store replay always succeeds. `cursor_expired` with a fresh snapshot - and cursor is the defined response a compacting adapter returns for a - cursor older than its retained history; no M5 witness can produce it and + events per session held in memory, defined as a **droppable encoding + cache** and nothing else. It holds the encoded bytes of events core has + already delivered to at least one attachment of that session, so a second + attachment arriving at the same position is served without encoding them + again. It is not a replay source: it never anchors a snapshot, never + establishes or advances a cursor, and is never consulted to decide what a + client is owed. Every attach, reattach and reconnect — including one whose + position lies inside the window — goes through core's cursor transaction, + and the window is used only to answer the bytes core has already named. It + may be dropped whole at any instant; the only consequence is that the next + delivery re-encodes. Correctness therefore cannot depend on it, and the + tests prove that by running the residency cases twice, once with the window + disabled, with identical delivery. + + Reclamation is deterministic so that it can be tested rather than observed. + When the daemon's aggregate encoded-byte ceiling would be exceeded, windows + are released in this fixed order: first every window whose session has zero + attachments, in ascending order of the monotonic time of their last + delivery, ties broken by session ID bytes ascending; then, if the ceiling is + still exceeded, the window of the session whose slowest attachment is + furthest behind, by the same tie-break. Only after every window has been + released does the daemon detach the slowest attachment at its last emitted + cursor. Independently of pressure, a window whose session has had zero + attachments for the idle interval is dropped. No reclamation stalls a + journal transaction and none changes what any client is owed. + + On the local adapter every durable event is retained until the root is + retired, so store replay always succeeds. `cursor_expired` with a fresh + snapshot and cursor is the defined response a compacting adapter returns for + a cursor older than its retained history; no M5 witness can produce it and none claims to; - the core event-count queue and the daemon socket output buffer above; when the next event would exceed either, the attachment is detached at its last @@ -212,7 +239,12 @@ sequence and event ID. Tests prove: two core attachments to one session keep independent live handles, snapshots and cursors with no implicit replacement; an explicit replacement invalidates only its named incarnation; snapshot-then-contiguous at-least-once -delivery with no gap across the window boundary; a slow observer detached at +delivery with no gap across the window boundary; the same delivery cases run +again with the resident window disabled, byte for byte identical, and with the +window dropped mid-stream, proving the cache establishes nothing; deterministic +reclamation in the fixed order above, including the case where zero-attachment +windows alone consume the aggregate ceiling and are released before any +attachment is detached; a slow observer detached at its last emitted cursor while the controller and other attachments continue; the per-session and per-daemon limits refusing independently; idle eviction and reconnect with no missing durable event and any duplicate deduplicated by diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 21fdbe2df..51eb132a5 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -57,12 +57,18 @@ foreign peer is refused before initialize. Every attachment starts from a snapshot anchored at the committed sequence and then receives the buffered and live stream contiguously, at least once. -The daemon keeps a bounded resident window of recent durable events per -session and replays older ones from the store on demand. On M5's local -adapter every durable event stays replayable until the operator retires the -root, so replay always succeeds; `cursor_expired` remains the defined -response a compacting adapter returns for a cursor older than its retained -history, and no M5 path produces it. Each connection owns a bounded socket +Replay has exactly one owner, and it is core. Every attach, reattach and +reconnect goes through the runtime's cursor transaction, and every durable +event a client is owed comes from core's dispatcher over the store. The +daemon's resident window is not a replay source: it is a droppable cache of +encoded bytes for events core has already delivered, so a second connection +at the same position is served without re-encoding. It never anchors a +snapshot, never establishes or advances a cursor, and may be dropped at any +moment with no effect but re-encoding. On M5's local adapter every durable +event stays replayable until the operator retires the root, so replay always +succeeds; `cursor_expired` remains the defined response a compacting adapter +returns for a cursor older than its retained history, and no M5 path produces +it. Each connection owns a bounded socket output buffer; a slow attachment is detached at its last completely emitted cursor while every other attachment continues. Idle attachments are evicted at the residency limit and reconnect at their retained cursor with no diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index b44f4109b..ae2efb0db 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -89,9 +89,40 @@ the local store's writer marker, unchanged. - An orderly connection close by the holder releases the lease; an abrupt loss leaves it to expire. +### Expiry against an in-flight admission + +Two rules above meet at the deadline and their order has to be stated, not +left to the implementation. The per-session owner serializes a lease +transition against a mutation whose holder check has already started, so a +takeover cannot pass an admission core has not yet resolved; and takeover is +admitted at expiry with no grace. The linearization rule is: + +1. A mutation whose holder, epoch, state and deadline check *completed* while + the deadline was still in the future is **in flight** and settles under + that lease, even if the deadline passes while core's admission is + unresolved. It completes or fails on its own terms; it is neither retried + nor fenced by the expiry. +2. At the deadline the lease state becomes `expired` and the holder gains + nothing further: every mutation whose check begins at or after the deadline + refuses, including one from the holder, and renewal no longer extends it. +3. A takeover becomes **eligible** at the deadline and is **granted** only + once every in-flight mutation for that session has resolved. Until then the + acquire waits, bounded by the acquiring request's own deadline; a wait that + exceeds it refuses with a stable reason naming the in-flight admission, and + the client may acquire again. +4. The grant then mints a fresh epoch, so nothing admitted under the previous + lease can be confused with anything after it. + +This adds no grace to the lease. The expired holder gains no new authority; it +only finishes what it had already started, which is the same guarantee the +serialization rule gives at every other moment. A holder cannot extend its +tenure by starting work, because rule 2 refuses every new check at the +deadline and the in-flight set can only shrink. + Proposed terms bound at acceptance: lease length 30 seconds, renewal interval -10 seconds for the reference clients, takeover admitted when the live daemon's -monotonic deadline is reached, no grace period beyond the lease itself. +10 seconds for the reference clients, takeover eligible when the live daemon's +monotonic deadline is reached and granted when the in-flight set is empty, no +grace period beyond the lease itself. ### Cancellation across processes @@ -124,8 +155,15 @@ Tests prove: exactly one controller with observers within the ADR 0032 bounds; a stale epoch, copied current epoch, non-holder connection, released state and expired state each refused before core admission with the current controller unaffected; a lease transition racing command admission preserves -this order; takeover only after release or expiry with a fresh epoch minted -before the successor's first command; a controller killed mid-run fenced +this order; the expiry linearization above, with a mutation blocked inside +core across the deadline settling under its own lease while the eligible +takeover waits and is granted only after it resolves, the holder's next +mutation refused at the deadline, the acquiring request refusing with its +stable reason when its own deadline elapses first, the holder's connection +disconnecting while its mutation is in flight, and the per-session lease owner +failing while a mutation is in flight — in every case exactly one of settle or +refuse, never both, and no epoch reused; takeover only after release or expiry +with a fresh epoch minted before the successor's first command; a controller killed mid-run fenced after takeover, its late commands refused; the per-session lease owner process crashing and restarting while the daemon and client sockets survive, after which the previous holder's delayed command is refused, no epoch is diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index 665b2d1fa..5574d5230 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -66,8 +66,15 @@ interaction answer, metadata field or attachment order confers it, and the daemon's own configuration may narrow who may take over; it cannot widen what the host's policy allows a command to do. The proposed lease terms are exact and are bound at acceptance: a thirty-second lease renewed every ten seconds, -takeover admitted at the live daemon's steady-clock expiry, and immediate -release on orderly disconnect. Writer exclusion between two daemons on one +takeover eligible at the live daemon's steady-clock expiry, and immediate +release on orderly disconnect. Expiry and an unresolved admission meet on one +rule, so neither promise is quietly broken by the other: a mutation whose +holder check completed before the deadline settles under its lease even if the +deadline passes while core is still deciding; at the deadline the holder gains +nothing further and every new mutation of its refuses; and a takeover becomes +eligible at the deadline but is granted only once those in-flight mutations +have resolved. That adds no grace, because the expired holder can only finish +what it had already begun. Writer exclusion between two daemons on one state root stays the local store's writer marker, unchanged. **Alternatives rejected.** Putting the lease in core was rejected because the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0451fa8d7..7aace9b63 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -105,8 +105,8 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. The active-session ceiling refuses an activation while every slot is in use and admits one after a session goes dormant; a root whose directory exceeds the index bound refuses at start; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its own generation, and a generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; the holder disconnecting and the per-session lease owner failing, each while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. Every daemon boundary emits its ADR 0030 spans and a daemon-scoped trace session captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table refuses with its stable reason and retains no copy: absent reference, malformed reference, a resolver module without the callback, a refusing resolver, a resolver silent past the invocation deadline, a value outside the size bound, and two resolutions in flight at once. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -334,7 +334,7 @@ decision named above; M5 introduces none of its own. | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | -| Takeover grace beyond expiry | none | ADR 0033 | +| Takeover grace beyond expiry | none; takeover is eligible at expiry and granted once the session's in-flight admission set is empty | ADR 0033 | | Writer epoch | opaque, at most 64 bytes, at least 128 bits of fresh randomness, minted per grant | ADR 0033 | | Credential size | 1 to 65,536 bytes | ADR 0019, unchanged by ADR 0034 | | Credential frame cap | 69,632 bytes | ADR 0019, unchanged by ADR 0034 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 9505f1bda..d201c6534 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -49,8 +49,8 @@ loop. | --- | --- | --- | --- | | 1 | A daemon owns session lifetime for a state root: an active session runs while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated and a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | -| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | -| 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with exact reconnect, retained encoded-event bytes within the daemon-owned bounds, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | +| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | +| 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with every daemon boundary emitting the accepted telemetry spans; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, compiles and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's environment enumeration has left the per-invocation call path. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | @@ -98,8 +98,11 @@ clients keep the M4 foreground server, whose wire and behavior do not change. Attach is the runtime's race-free cursor transaction, and delivery is contiguous and at least once: gaps are forbidden, duplicates are permitted, and a client deduplicates by session ID, event sequence and event ID as the -vision requires. The daemon adds a bounded resident window, daemon-owned -bounded socket output buffers, detachment at the last emitted cursor and idle +vision requires. Core is the only replay owner: every attach, reattach and reconnect +goes through its cursor transaction, and the daemon's resident window is a +droppable cache of already-delivered encoded bytes that anchors no snapshot +and establishes no cursor. Above that the daemon adds daemon-owned bounded +socket output buffers, detachment at the last emitted cursor and idle eviction; on the local adapter every durable event stays replayable until the operator retires the root, so `cursor_expired` remains a defined protocol response no M5 path produces. @@ -109,8 +112,9 @@ before existing-session mutation. Exactly one controller holds a daemon-owned lease per session; every other attachment is read-only. For an existing session, the daemon admits a mutation only when its requesting connection is the holder of a held, unexpired lease and carries its current writer epoch. -Takeover is explicit, only after release or expiry, and mints a fresh epoch -before the successor's first command. The lease lives in the daemon's memory +Takeover is explicit, becomes eligible only after release or expiry, waits for +any mutation already in flight under the outgoing lease to resolve, and mints +a fresh epoch before the successor's first command. The lease lives in the daemon's memory for the daemon process's lifetime, never in the session journal or any durable record; every writer epoch is minted fresh and never reused, so a restart of the daemon or of a session's lease owner leaves that session uncontrolled with From e295de5eb1e1e89a807bdb8a2fd67d67bc6d4333 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:41:45 -0700 Subject: [PATCH 012/585] plan(M5): give generation 2 its own digest and settle observability Audit findings 8 and 9. Finding 8 holds. Loopex.Protocol.Session.schema_digest/0 at session.ex:191-199 is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and public_schema_conformance_test.exs:285-291 says exactly that beside the literal 3a1723e3...08f4. Generation 2 changes the generation string and adds methods, so the plan's "negotiates generation 2 with the same schema digest" asked for a value that cannot exist. Generation 2 now requires its own exact literal digest, and generation 1's digest, schema-file digest and vectors-file digest are separately proved unchanged, so additivity is proved rather than asserted. Finding 9 holds. ADR 0030's companion states the inventory is exact, that a callback or cut absent from its table is not instrumented, and that adding one is an amendment; the table is five ports and six coordinator cuts. The daemon is a host above those ports, so "every daemon boundary emits the ADR 0030 spans" required an amendment the plan did not propose. M5 now emits no new event: it proves the daemon's workflows drive the existing core spans end to end with the same bounded identity metadata, and observes daemon-internal functions through a daemon-scoped trace session. A future daemon event is named as an ADR 0030 amendment and is not M5's. --- ...tachment-residency-and-replay-technical.md | 12 ++++++++-- docs/plans/M5-technical.md | 4 ++-- docs/plans/M5.md | 23 +++++++++++++++---- 3 files changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index f3a0dc4b5..fd946e5d6 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -164,8 +164,16 @@ daemon supports exactly `loopex.experimental/2`: it selects that generation when the client lists it, at any position, and otherwise refuses with `unsupported_generation`, leaving the connection uninitialized with no second attempt, exactly as ADR 0023 fixes for a foreground process. The successful -reply carries `selected_generation`, the exact generation-2 schema digest, -the generation-2 method inventory and limits. The generation-2 schema and its +reply carries `selected_generation`, generation 2's own exact schema digest, +the generation-2 method inventory and limits. That digest is necessarily a new +value: the digest is taken over the generation, the ordered methods, the +ordered record families, the ordered error codes and the limits, and +generation 2 changes the generation and the method list, so it cannot and must +not equal generation 1's. It is written out as a literal beside generation +1's, and generation 1's literal digest, schema-file digest and vectors-file +digest are asserted unchanged in the same place, so an accidental edit to +generation 1's contract fails there rather than silently renaming what +existing clients agreed to. The generation-2 schema and its vectors are new files beside generation 1's, as `apps/loopex_protocol/priv/schema/loopex-experimental-2.json` and `apps/loopex_protocol/priv/vectors/loopex-experimental-2.json`, reviewed with diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 7aace9b63..dc7f67e2d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -104,10 +104,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. The active-session ceiling refuses an activation while every slot is in use and admits one after a session goes dormant; a root whose directory exceeds the index bound refuses at start; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 with the same schema digest and limits the foreground server negotiates for its own generation, and a generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; the holder disconnecting and the per-session lease owner failing, each while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. Every daemon boundary emits its ADR 0030 spans and a daemon-scoped trace session captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table refuses with its stable reason and retains no copy: absent reference, malformed reference, a resolver module without the callback, a refusing resolver, a resolver silent past the invocation deadline, a value outside the size bound, and two resolutions in flight at once. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every diff --git a/docs/plans/M5.md b/docs/plans/M5.md index d201c6534..f16813c0a 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -48,10 +48,10 @@ loop. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | | 1 | A daemon owns session lifetime for a state root: an active session runs while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | -| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated and a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | +| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | -| 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with every daemon boundary emitting the accepted telemetry spans; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, compiles and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | +| 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end and daemon-internal functions observed through a daemon-scoped trace session rather than new events; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, compiles and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's environment enumeration has left the per-invocation call path. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -176,9 +176,22 @@ negative proof M0 to M2 established is carried to the new mechanism rather than relaxed. It is its own workstream with its own security review, and its measured result is part of closure. -M4's observability continues without change: every daemon boundary emits the -ADR 0030 spans, and a trace session scoped to the daemon's runtime captures -identities only. The socket path is bounded by the platform and refused when +M4's observability continues without change, and "without change" is meant +exactly. ADR 0030's emission inventory is closed — five ports and six +coordinator cuts, with a new callback or cut instrumented only by amending +that ADR — and the daemon is a host above those ports, not one of them. So M5 +adds no telemetry event and proposes no amendment. What it proves instead is +that the daemon's workflows drive the existing core spans end to end: a +session created, driven, taken over and aborted through the socket emits the +same command-admission, commit, effect-intent, publication, interaction, model, +store, policy and executor spans an embedded caller emits, with the same +bounded identity metadata. Daemon-internal functions — the listener, the +connection, the lease owner, the residency stages — are observed the way the +runtime already observes code that emits nothing: a trace session scoped to +the daemon's runtime, bounded and redacted, started without changing source. +A daemon-scoped trace session captures identities only. If the daemon later +needs events of its own, that is an ADR 0030 amendment with its exact events, +metadata, bounds and tests, and it is not M5's. The socket path is bounded by the platform and refused when too long; the socket is owner-only and a foreign peer is refused before initialize; the daemon never runs as a service-manager unit by itself, and the documented launch is a foreground command an operator or their service manager From c3b5140605faa42ba55b32b2e68abba6f6573311 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:43:58 -0700 Subject: [PATCH 013/585] plan(M5): make the archive build and peer authorization realizable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit findings 10 and 11. Finding 10 holds. apps/loopex_cli/mix.exs matches {source, 0} = System.cmd ("git", ["rev-parse", "HEAD"]) at line 34, again at line 80, and git status --porcelain=v1 at line 83; Mix.Tasks.Loopex.Provider.Build.clean_source! does the same at loopex.provider.build.ex:120-125. A git archive extraction has no .git, so every match fails and the documented CLI build cannot run from the extraction Outcome 5 requires. M5 now owes a tracked SOURCE_IDENTITY carrying $Format:%H$ under a tracked .gitattributes export-subst entry, one resolver both paths call, and four refusals: missing, unsubstituted or malformed, changed-during-build proved by a SHA-256 over the extracted tracked paths before and after, and mismatched proved where external truth exists — the release check asserts the identity the extraction reports equals the commit git archive was staged from. Finding 11 holds, and the runtime probe was run. On this OTP 29 Darwin toolchain :socket.supports(:options, :socket) reports peercred: false and passcred: false, and :socket.getopt(sock, :socket, :peercred) answers {:error, {:invalid, {:socket_option, {:socket, :peercred}}}}. The raw option does work: :socket.getopt_native(sock, {0, 1}, 128) returned a struct xucred decoding to the connecting process's uid. The boundary is now primarily the filesystem — an owner-only directory and socket verified after bind — with peer-credential inspection as a named, fail-closed second layer, LOCAL_PEERCRED on Darwin and SO_PEERCRED on Linux, which is why the listener is on OTP's :socket API rather than the classic inet backend. The path bound was probed too: on Darwin a bind at 103 bytes succeeds and at 104 is refused, because sun_path's 104 bytes include the terminator. The plan's 104/108 becomes a usable 103/107, derived and tested per platform. --- ...tachment-residency-and-replay-technical.md | 63 +++++++++++++++++-- ...-daemon-attachment-residency-and-replay.md | 12 +++- docs/plans/M5-technical.md | 55 ++++++++++++++-- docs/plans/M5.md | 20 ++++-- 4 files changed, 132 insertions(+), 18 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index fd946e5d6..bbea7b4fb 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -11,12 +11,63 @@ Concept: [Context and decision](0032-daemon-attachment-residency-and-replay.md#c ### Transport The daemon listens on one Unix-domain socket. Its path is -`/daemon.sock` by default and may be set explicitly; a path -longer than the platform's socket-address bound (104 bytes on Darwin, 108 on -Linux) is refused at start with `socket_path_too_long` naming the bound, never -truncated. The socket file is created with owner-only permissions and the -daemon reads the connecting peer's credentials; a peer whose user identity -differs from the daemon's is closed before any frame is read. +`/daemon.sock` by default and may be set explicitly. + +**The path bound is derived, not assumed.** `sun_path` is 104 bytes on Darwin +and 108 on Linux *including* the NUL terminator, so the usable path is one +byte shorter than the structure: at most 103 bytes on Darwin and 107 on Linux. +That is measured, not inferred — on the supported OTP 29 Darwin toolchain a +bind at 103 bytes succeeds and at 104 bytes is refused with +`{:invalid, {:sockaddr, …}}`. Each supported platform derives its own bound +the same way rather than carrying a constant, and a path beyond it is refused +at start with `socket_path_too_long` naming the derived bound, never +truncated. The tests bind at the bound and at one byte past it on every +platform the release check runs. + +**Peer authorization has two layers, and the load-bearing one is the +filesystem.** The socket lives in a directory the daemon owns with mode +`0700`, and the socket itself is created mode `0600`; both are verified after +bind by reading back their owner and mode and comparing them with the daemon's +own effective user, and the daemon refuses to serve if either is wrong, if the +parent is not owned by that user, or if any component of the path is a +symbolic link it did not create. That is what actually keeps another user out: +connecting to a Unix-domain socket requires write permission on the socket and +traversal of its directory, so a foreign peer never reaches `accept`. It is +the same arrangement ADR 0019 already uses for the provider child's private +channel, proved there, and reused rather than reinvented. + +**Peer-credential inspection is the second layer, and its mechanism is named +per platform** because the portable one does not exist. On the supported +OTP 29 Darwin toolchain `:socket.supports(:options, :socket)` reports +`peercred: false` and `passcred: false`, and `:socket.getopt(sock, :socket, +:peercred)` answers `{:error, {:invalid, {:socket_option, …}}}`; the named +option is simply not available there. What is available is the raw option: +`:socket.getopt_native(sock, {0, 1}, 128)` — Darwin's `SOL_LOCAL`, +`LOCAL_PEERCRED` — returns a `struct xucred` from which the peer's effective +uid is decoded, and it was confirmed to return the connecting process's uid on +that toolchain. On Linux the mechanism is `SO_PEERCRED` at `SOL_SOCKET`, +yielding `struct ucred`. Both are socket options, and the classic `inet` +backend exposes neither, so the listener uses OTP's own `:socket` API (or +`gen_tcp` over the socket backend, whose handle it can reach) rather than the +classic backend. A peer whose decoded uid differs from the daemon's is closed +before any frame is read. + +**Fail closed.** Where a platform has a named mechanism, a credential read +that errors, returns a short or unrecognised structure, or reports a uid the +daemon cannot decode closes the connection before initialize; it is never +treated as permission. Where a platform has no mechanism at all, the daemon +says so in its diagnostics and the boundary is the verified filesystem layer +alone — which the daemon proves it has, because it refuses to serve when +ownership and mode cannot be verified. + +The evidence follows the same split. The fast check proves the filesystem +layer and the fail-closed paths without needing a second user: a permissive +directory or socket mode, a parent the daemon does not own, and a path +component the daemon did not create are each refused at start; an unreadable +or undecodable peer credential closes the connection. The real cross-uid +refusal is a release-check case on the Linux lane, where a second unprivileged +user exists: a connection from another uid is refused before initialize and a +connection from the daemon's own uid succeeds, both recorded with the run. Startup order is fixed. The daemon first opens the state root through the local adapter and acquires its writer marker; a daemon that does not hold the diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 51eb132a5..8d2237820 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -52,8 +52,16 @@ beyond the platform bound is refused at start rather than truncated. A daemon acquires the root's store writer marker before it touches the socket path, so two simultaneous starts resolve at the marker and never at the socket, and a daemon that loses its store closes the listener and every connection -before it exits. Only the daemon's own operating-system user may connect; a -foreign peer is refused before initialize. +before it exits. Only the daemon's own operating-system user may connect, and +the boundary that enforces it is the filesystem: an owner-only directory and +socket whose ownership and mode the daemon verifies after bind and refuses to +serve without, which is what stops a foreign peer reaching `accept` at all. +Peer-credential inspection is a second, fail-closed layer whose mechanism is +named per platform, because there is no portable one: the supported OTP 29 +Darwin toolchain reports no `peercred` or `passcred` socket option, so Darwin +reads `LOCAL_PEERCRED` and Linux reads `SO_PEERCRED`, and a credential that +cannot be obtained or decoded closes the connection rather than admitting it. +A foreign peer is refused before initialize. Every attachment starts from a snapshot anchored at the committed sequence and then receives the buffered and live stream contiguously, at least once. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index dc7f67e2d..d3bb7701c 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -104,10 +104,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. The active-session ceiling refuses an activation while every slot is in use and admits one after a session goes dormant; a root whose directory exceeds the index bound refuses at start; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. A foreign-uid peer refused before initialize. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: a permissive directory or socket mode, a parent the daemon does not own, and a path component it did not create each refused at start, and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; the holder disconnecting and the per-session lease owner failing, each while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The attended real-provider cases run from that extraction. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table refuses with its stable reason and retains no copy: absent reference, malformed reference, a resolver module without the callback, a refusing resolver, a resolver silent past the invocation deadline, a value outside the size bound, and two resolutions in flight at once. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every @@ -257,7 +257,13 @@ rules in `apps/loopex/lib/mix/tasks/loopex.deps_budget.ex` and its cases in that adds the application, and `mix loopex.deps_budget` proves the direction. M5 adds no external dependency. No transport library, socket abstraction layer or service-manager integration enters any application; the socket is the -runtime's own `gen_tcp` local address family. +runtime's own, on OTP's `:socket` API for the local address family. The +classic `inet` backend is not sufficient here and the choice is not a +preference: the peer-credential read ADR 0032 requires is a socket option, and +the classic backend exposes neither the named option nor the raw one, while +`:socket` exposes `getopt_native/3`. Either `:socket` directly or `gen_tcp` +over the socket backend with its handle reachable satisfies this; no library +is added either way. Supply `loopex daemon`, `loopex attach` and `loopex sessions` in the reference CLI, and extend the client in `clients/node` to connect over the socket, to @@ -268,6 +274,47 @@ step, package manifest or dependency, as the maintainer decided for M4 on continues to verify it before any client runs; the release check's application list gains `loopex_daemon` in the same change that adds its release cases. +**The archive must be able to build itself.** Today it cannot, and this is +work M5 owes rather than a property it can assert. Both build paths demand a +`.git` directory: `apps/loopex_cli/mix.exs` matches `{source, 0} = System.cmd +("git", ["rev-parse", "HEAD"], ...)` at line 34 and again at line 80, with +`git status --porcelain=v1 --untracked-files=all` at line 83, and +`Mix.Tasks.Loopex.Provider.Build`'s `clean_source!` does the same at +`loopex.provider.build.ex:120-125`. A `git archive` extraction has no `.git`, +so every one of those matches fails and the documented CLI build cannot run +from the extraction the closure candidate must build from. + +M5 therefore adds an archive-carried source identity that both paths accept, +and one shared resolver they both call: + +- a tracked `SOURCE_IDENTITY` file holding `$Format:%H$` and the commit date, + with a tracked `.gitattributes` marking it `export-subst`, so `git archive` + substitutes the exact commit into the extracted copy while the checkout's + copy keeps the unsubstituted literal; +- a resolver that prefers git when `.git` is present — the existing behaviour, + unchanged, including the clean-tree requirement — and otherwise reads + `SOURCE_IDENTITY`; +- three refusals in the archive case, each with its own stable reason and none + of them a fallback to building anyway: the file is **missing**; the file is + **unsubstituted or malformed**, which is what a hand-copied checkout file or + a hand-written one looks like, since anything but one lowercase 40-character + hexadecimal commit id and a commit date is refused; or the extracted tree + **changed during the build**, which is the property `git status` buys in a + checkout and which the resolver proves here by a SHA-256 over the extracted + tracked source paths, sorted, taken before the build and again after and + required equal; +- the provider build manifest embeds the resolved commit id together with that + source digest, so an identity naming a commit whose tree is not what was + built is detectable rather than merely trusted. + +The **mismatch** case is proved where the external truth exists: the release +check stages the archive with `git archive` from a known commit, retains the +archive's SHA-256 and that commit, and asserts that the identity the +extraction's build reports is exactly that commit. Then, inside the +extraction, the documented CLI build runs and the real-provider workflow runs +against it, which is the proof that the archive is buildable rather than +merely extractable. + `VERSION` and the application versions move to `0.2.0` in an ordinary reviewed commit before closure, as the [milestone guide](../developer/milestones-technical.md#technical-milestones-release) @@ -330,7 +377,7 @@ decision named above; M5 introduces none of its own. | Active sessions per daemon | 64; a further activation refused while every slot is in use | ADR 0032 | | Session index entries per root | 4,096; a root whose directory holds more refused at daemon start | ADR 0032 | | `session.list` page | at most 256 entries, `limit` in 1 to 256 | ADR 0032 | -| Socket path bound | the platform's, 104 bytes on Darwin and 108 on Linux, refused at start as `socket_path_too_long` | ADR 0032 | +| Socket path bound | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index f16813c0a..4fb84bcb3 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -51,7 +51,7 @@ loop. | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | -| 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end and daemon-internal functions observed through a daemon-scoped trace session rather than new events; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, compiles and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | +| 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end and daemon-internal functions observed through a daemon-scoped trace session rather than new events; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's environment enumeration has left the per-invocation call path. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -191,9 +191,15 @@ runtime already observes code that emits nothing: a trace session scoped to the daemon's runtime, bounded and redacted, started without changing source. A daemon-scoped trace session captures identities only. If the daemon later needs events of its own, that is an ADR 0030 amendment with its exact events, -metadata, bounds and tests, and it is not M5's. The socket path is bounded by the platform and refused when -too long; the socket is owner-only and a foreign peer is refused before -initialize; the daemon never runs as a service-manager unit by itself, and the +metadata, bounds and tests, and it is not M5's. The socket path is bounded by the platform's usable `sun_path`, one byte less +than the structure because of the terminator — at most 103 bytes on Darwin and +107 on Linux, derived per platform rather than assumed — and refused when too +long. Owner-only access is enforced first by the filesystem, an owner-only +directory and socket whose ownership and mode the daemon verifies after bind +and refuses to serve without, and second by a fail-closed peer-credential read +whose mechanism is named per platform because no portable one exists: the +supported OTP 29 Darwin toolchain offers no `peercred` socket option at all. +A foreign peer is refused before initialize; the daemon never runs as a service-manager unit by itself, and the documented launch is a foreground command an operator or their service manager runs. @@ -386,8 +392,10 @@ runs last because it describes what the others built. 6. **Documentation and the `0.2.0` release candidate.** The operator daemon guide and the developer daemon pair, the updates M5 forces on the existing operator and developer pages, the changelog and the indexes, the `VERSION` - change to `0.2.0`, and the release-ready source archive proved by extracting - it, compiling it and running the two-process workflow from the extraction. + change to `0.2.0`, the archive-carried source identity both build paths + accept in place of `.git`, and the release-ready source archive proved by + extracting it, building the CLI and its provider companion inside the + extraction, and running the two-process workflow there. Parallel work uses one worktree per writer over the non-overlapping paths the technical companion assigns, with one integrator owning the rejoin. From b59433c060286333bb8cd76791b87df6d0d3014a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:45:27 -0700 Subject: [PATCH 014/585] adr(0031): make it one acceptably bounded decision MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit finding 12. The pair contradicted itself about its own authority: the concept said its "successor half binds nothing in M5" while the companion's closing paragraph said acceptance binds this complete pair at the exact candidate the maintainer names. An ADR that carries a half it calls non-binding is not one decision, and docs/adr/README.md's immutability rule makes that worse rather than better, because acceptance anchors the bytes. ADR 0031 is now about the 0.2.0 local-adapter selection and its limits and nothing else. The prescribed successor engine candidates, the experiment protocol, the migration ledger and its rollback and oldest-reader claims are withdrawn. What replaces them is a short statement of the open questions the successor's own ADR must answer — engine, the unchanged port boundary it inherits from ADR 0006, selecting evidence, and whether a migration exists at all — prescribing none of them. The file names keep the word "migration" because an ADR's name is its permanent identity; the index title now reads "Daemon store selection for 0.2.0", and the pair says why the two differ. --- ...store-selection-and-migration-technical.md | 175 ++++-------------- ...mon-grade-store-selection-and-migration.md | 92 ++++----- docs/adr/README.md | 9 +- docs/plans/M5-technical.md | 8 +- docs/plans/M5.md | 2 +- 5 files changed, 85 insertions(+), 201 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 42539cd69..026b16e9d 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -71,145 +71,48 @@ after an orderly stop the foreground server reopens the same root. No new conformance evidence is required, because the adapter and its suites are unchanged. -### Boundary - -`loopex_store_daemon`, the successor's adapter, implements the same private -port set `Loopex.Store` already fixes for the local adapter: `transact/2`, -`transaction_status/4`, `runtime_command/2`, `ownership_head/3`, -`load_records/4` and `load_events/4`, plus the snapshot store and load calls -the port declares. It changes no callback arity or result shape; ADR 0006 -owner epochs and incarnation identities remain the commit-authority fence and -the writer marker remains physical writer exclusion. The public protocol, the -embedded API and every public event are unchanged by the adapter choice. -Neither core nor `loopex_store_local` depends on the adapter, and the -daemon's controller lease stays in daemon memory under ADR 0033; no adapter -stores a lease. - -### Candidate one: BEAM-native segmented log - -- One root directory per state root with a `manifest` file naming the format - version `loopex_store_daemon_v1`, the placement identity the root was - created under, and the migration ledger. -- One append-only frame log per session, reusing the local adapter's - length-prefixed, digest-checked frame and its sync-after-commit rule, so a - torn tail is detected and truncated at the last complete frame exactly as - today. -- Private and public snapshots written every N private records or M seconds, - whichever first, each naming the journal version and public sequence it - covers; open replays only records after the newest verified snapshot, so - replay is bounded by the snapshot interval rather than session age. -- A session index file listing session identity, source and fork lineage, - genesis and tombstone state and the last known public sequence, rebuilt from - the logs when absent or inconsistent rather than trusted. -- The root-scoped daemon writer marker held for the whole root, using the - local adapter's liveness-probe discipline and the same - `store_writer_active` and `store_writer_unverifiable` refusals. - -### Candidate two: SQLite through a NIF binding - -One database per state root with tables for sessions, private records, -public outbox rows, snapshots and idempotency; transactions through the -engine's journal; the same port mapping. Both candidates use a root manifest -with format version, placement identity and migration ledger; SQLite keeps its -session index as database lookup state rather than a separate index file. It -is evaluated on the same suite with three additional obligations: the NIF's -failure containment (a crash or -a blocked scheduler is a VM-level risk the native candidate does not carry), -its packaging (a compiled dependency joins the version train and the release -archive), and equivalent crash and corruption outcomes under its own journal -and database file format. - -### Selection experiment and evidence - -After M5 closes, both candidates run in separate disposable branches and -worktrees. The experiments may build only the adapter slices and fixtures -necessary to measure this decision; they do not merge to `main` or become -accepted product bytes. Both run: - -- the shared store conformance suite that the local and in-memory adapters - already pass, unchanged; -- common semantic fault cut points: kill before durable commit, after durable - commit but before acknowledgement, and during snapshot or checkpoint write; - corrupt or incomplete durable bytes, missing or corrupt derived lookup state, - and a marker left by a dead writer. Each candidate uses physical injections - appropriate to its representation and proves the same Store-level recovery - or refusal outcomes. The native candidate additionally runs literal torn - last frame, corrupt middle frame, and missing or corrupt session-index - fixtures; SQLite runs its corresponding database and journal corruption and - index-rebuild fixtures. The decision packet records the exact injection and - observed outcome for each candidate and cut point; -- commit-ambiguity resolution: a `transact` whose acknowledgement was lost is - resolved by `transaction_status` to exactly one outcome; -- bounded replay: open time and memory grow with the snapshot interval, not - with session length, measured on a session with at least one hundred - thousand records; -- backup and restore: a quiescent copy reopens with every session identity and - public sequence intact and the integrity check clean. - -Record each experiment's exact candidate SHA, commands, platform and measured -results in the decision packet. The winner, both experiment SHAs, its -evidence and any packaging cost are then written into a new ADR that declares -`Supersedes: 0031` for this successor half, not into these bytes: once this -pair is accepted as an M5 prerequisite it is anchored, and its one Acceptance -row already binds the M5 local-adapter selection. That successor ADR is -independently reviewed and accepted on its own. Selection does not itself -accept the successor milestone. Product implementation of the adapter starts -only after that successor ADR and that milestone's plan are accepted. - -### Migration - -Supported pair: local adapter format `loopex_store_writer_v2` log, as the M4 -foreground server, the reference CLI and the M5 daemon write it, to -`loopex_store_daemon_v1` root. The import reads the original log through the -local adapter's own reader, writes each session and derived lookup state through -the selected adapter into a new root, records `started`, -`session imported`, `verified` and `completed` -in the manifest's migration ledger with the source log digest, and refuses to -serve until `completed` is present. Reopen after interruption reads the -ledger: a root without `completed` is either resumed from the last recorded -session or discarded and restarted, both without touching the source log. The -original log is never modified, moved or deleted by the import. - -Every previous local-reader binary, the M5 daemon release included, treats -the daemon-grade root directory as an invalid store file and returns its -existing `store_file_invalid` reason. It cannot name `loopex_store_daemon_v1` -or advertise a maximum format it never implemented. The successor daemon -reader validates the root manifest version and refuses unknown versions -explicitly; it is the oldest reader of this new root. A daemon binary opening -a local log serves it only through explicit import; it never upgrades in -place. - -### Evidence and alternatives - -Successor tests cover forward migration of a genuine local session log with -identical replay afterwards, interruption at each ledger step with detection -on reopen, safe refusal by the exact previous binary with its actual reason, -and backup and restore. Mnesia and DETS were rejected: DETS carries a -two-gigabyte table limit and no tail-repair story, and Mnesia's schema is -VM-global state that contradicts the runtime-instance rule. A hosted -PostgreSQL adapter remains a later choice under the same ports and is not -evaluated here. Deferring this ADR entirely from M5 was rejected on -2026-09-14: the daemon still needs a recorded selection, and the local -adapter's ceilings are a fact the operator must be told rather than an -absence of decision. +### What this pair leaves open + +A daemon-grade adapter is not decided here, and nothing below prescribes one. +What is recorded is only the shape of the question, so the successor ADR knows +what it has to answer rather than inheriting a preference: + +- **Which engine**, chosen on measured evidence rather than on argument. The + candidates are open; the obvious ones have been named informally and none is + eliminated or selected here. +- **The unchanged boundary it must implement.** Whatever the engine, it sits + behind the private port set `Loopex.Store` already fixes for the local + adapter — `transact/2`, `transaction_status/4`, `runtime_command/2`, + `ownership_head/3`, `load_records/4`, `load_events/4` and the snapshot store + and load calls — with no change to callback arity or result shape. ADR 0006 + owner epochs and incarnation identities remain the commit-authority fence, + the writer marker remains physical writer exclusion, and no adapter stores a + lease. This much follows from decisions already accepted, so it is a + constraint on the successor rather than a choice this pair is making. +- **What evidence selects it**: the shared store conformance suite unchanged, + a semantic fault matrix, commit-ambiguity resolution, bounded replay + measured rather than claimed, and backup and restore. +- **What migration means**, if any: whether a local root is imported at all, + how an interrupted import is detected on reopen, what the rollback pair is, + and which binary is the oldest reader of the new root. + +Each of those is settled by the successor's own ADR, proposed with the +successor milestone's plan and accepted on its own review. Until then they +are questions, and this pair does not answer them. ### Compatibility and Rollback Mechanics Concept: [Consequences and rollback](0031-daemon-grade-store-selection-and-migration.md#concept-adr-0031-consequences). -In M5 no journal format changes; the daemon, the foreground server and the -CLI reopen one another's roots, and rollback is stopping the daemon. The -private journal is a separate compatibility surface and stays experimental -in 0.x; the successor adapter adds no public event, snapshot field, wire -method or embedded function. Successor rollback is the retained original log -plus the previous binary, which is a copy back, not a reverse migration. -Backup is a quiescent copy of the root plus the adapter's integrity check; -restore reopens the copy under the same placement identity and refuses a -placement mismatch exactly as resume does today. - -Acceptance of the M5 selection binds this pair at the exact candidate the -maintainer names in the governance record, and that is the only disposition -this pair carries. The successor selection is a separate disposition on a -separate ADR that supersedes this one's successor half, recorded the same way -once its experiment evidence exists; this pair is not edited again. +No journal format changes; the daemon, the foreground server and the CLI +reopen one another's roots, and rollback is stopping the daemon. The private +journal is a separate compatibility surface and stays experimental in 0.x. +There is no forward migration, so there is no migration to roll back and no +oldest-reader claim to defend. + +Acceptance binds this complete pair at the exact candidate the maintainer +names in the governance record, and it carries exactly one disposition: the +`0.2.0` selection of the local adapter and its documented limits. A successor +adapter is a separate disposition on a separate ADR declaring +`Supersedes: 0031`, recorded once its evidence exists. diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index f39e0494f..9a69a216d 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -8,9 +8,12 @@ Technical depth: [Daemon-grade store mechanics](0031-daemon-grade-store-selectio - **Decision owner:** Maintainer - **Supersedes:** nothing; refines the store posture in vision §12.2 - **Prerequisite for:** M5 outcomes 1 and 5, accepted before the daemon opens - a state root — that is, before M5's workstream 1 lands — for the - local-adapter selection and its documented limits. Its successor half binds - nothing in M5; see the note on supersession below. + a state root + +This pair decides one thing: which store the `0.2.0` daemon runs on, and what +that choice costs. The file names keep the word *migration* because an ADR's +name is its permanent identity and is not rewritten; the decision no longer +prescribes one. See *What this pair does not decide*. ### Context and Decision @@ -25,11 +28,11 @@ bootstrap adapters were never asked to make: bounded replay, an index, a migration pair with interrupted-migration recovery, backup and restore, and a stated oldest binary that may reopen a migrated root. The vision freezes the store contract, not an engine, and says adapters are selected by -evidence. - -This ADR decides two things at two times. +evidence. None of those operational claims is made for `0.2.0`; what has to +be decided now is which store the daemon runs on and what the operator is +owed about its limits. -**For M5, select the existing local adapter as the daemon's store.** The +**Select the existing local adapter as the daemon's store for `0.2.0`.** The daemon holds the local writer marker for its process's lifetime and inherits the adapter's exact, documented limits: one append-only log per state root with a hard 256 MiB capacity, a 4 MiB frame ceiling, full-history retention @@ -46,6 +49,7 @@ operator retires the root. A log already past the bound is refused at open as lost and nothing false is recorded, which is what the truthfulness claim means here. Sessions in a retired root are resumable only by reopening that root. + This is a bounded, experimental selection made on evidence the local adapter already carries; it is not a daemon-grade store, and the 0.2.0 daemon's operator documentation states these limits and the @@ -54,30 +58,21 @@ the ADR entirely: the reference daemon needs a recorded store selection even when the selected adapter is the existing one, and documenting the ceilings makes the durable-service claim truthful without adding an engine. -**For the successor milestone, decide the selection procedure now and let its -evidence fix the engine before that milestone's acceptance.** The -daemon-grade store is a new adapter, `loopex_store_daemon`, behind the -unchanged private session Store ports. After M5 closes, isolated, disposable -contract experiments in their own worktrees compare a BEAM-native segmented -log and a SQLite-backed NIF adapter against the same conformance and -fault-injection suites. Neither experiment becomes product implementation or -merges to `main`. The current recommendation is the BEAM-native adapter -because it avoids a compiled dependency and VM-level NIF risk while reusing -proven local framing and repair; these are hypotheses to test, not a -categorical veto of SQLite. Any candidate that fails a required fault case is -ineligible. - -**Where the selection is recorded.** Not here. Once this pair is accepted as -an M5 prerequisite its bytes are anchored: a decision is replaced additively, -by a successor that declares `Supersedes: 0031`, and the predecessor stays -exactly as accepted. This pair's single Acceptance row binds one disposition, -and that disposition is the M5 local-adapter selection. So the successor -milestone's engine, the two exact experiment revisions, their measured -evidence and the migration are recorded in a **new ADR superseding this one's -successor half**, proposed when the experiments have run and accepted on its -own review. What this pair decides now, and all it decides now, is the M5 -selection and the procedure the successor's experiments must follow; nothing -in the successor half binds M5. +**What this pair does not decide.** An earlier draft also prescribed the +successor milestone's engine candidates, its experiment procedure and its +migration, then said that half bound nothing — while its companion said +acceptance binds the pair. Those cannot both be true, and an ADR that carries +a non-binding half is not one decision. The successor half is withdrawn on +2026-09-19. A daemon-grade adapter behind the unchanged private Store ports +remains an open question, and the questions it must answer — which engine, on +what measured evidence, with what migration, what interrupted-import recovery, +what backup and restore, and which binary is the oldest reader of the new root +— are named in the companion as open, prescribed nowhere. They are settled by +their own ADR, proposed with the successor milestone's plan, accepted on its +own review, declaring `Supersedes: 0031` for the selection this pair makes. +Nothing about that work binds M5, and nothing in M5 forecloses it: the local +adapter, its format and its ports are unchanged, so any successor starts from +exactly the root M5 leaves. **Alternatives rejected.** Deferring this decision out of M5 entirely was rejected on 2026-09-14: the reference daemon still needs a recorded store @@ -86,6 +81,10 @@ told rather than an absence of decision. Building the daemon-grade adapter inside M5 was rejected because it doubles the milestone's evidence — a new engine, its fault matrix, its migration and its rollback — without adding a proved capability to the durable-service question M5 exists to answer. +Deciding the successor's engine and migration procedure here, ahead of the +experiments that would inform them, was rejected on 2026-09-19: a decision +recorded before its evidence is a preference, and one that has to call itself +non-binding to be tolerable is not a decision at all. Raising or removing the local log's 256 MiB capacity to postpone retirement was rejected because a silently growing log trades a truthful refusal for an unbounded replay at open. Changing the local adapter so that a capacity @@ -99,8 +98,7 @@ and the fault matrix on every adapter, that the separated class is definite in every injection and that no other class quietly joins it. That is the successor adapter's evidence, and buying it here would double M5's store evidence to make one operator message nicer. Until then the daemon's capacity -behaviour is the adapter's, stated plainly rather than promised away. Mnesia and DETS were rejected as successor -candidates for the reasons the companion records. +behaviour is the adapter's, stated plainly rather than promised away. **Evidence its acceptance requires.** The M5 half is a durability claim, so its class is process and store fault injection on the real adapter plus a @@ -110,20 +108,9 @@ connection and exits naming the capacity, with nothing committed lost; a root already past the bound refuses at open; and after an orderly stop on a root below the bound the foreground server and reference CLI reopen it. No new conformance evidence is required, because the adapter and its suites are -unchanged — which is the point of selecting it. The successor half claims a new engine and a migration, -so its class is the full store conformance suite, the fault matrix, bounded -replay measurement, backup and restore, forward migration with interrupted- -import recovery, and safe refusal by the exact previous binary; none of it is -owed before the successor milestone's acceptance. - -Migration is one-way and explicit: the successor's daemon imports a local log -written by the M4 foreground server, the reference CLI or the M5 daemon into -its own root, retains the original untouched beside it as the rollback pair, -records every step so an interrupted import is detected and completed or -rolled back on the next open, and stamps the new root with a format version. -Every previous release binary must safely refuse that root with its existing -error; it cannot report a version it does not know. No in-place rewrite and -no silent upgrade on first open. +unchanged — which is the point of selecting it. That is the whole of the +evidence this pair owes, because that selection is the whole of what it +decides. Technical depth: [Contract and evidence](0031-daemon-grade-store-selection-and-migration-technical.md#technical-adr-0031-decision). @@ -143,15 +130,8 @@ artifact or embedded contract, and the exact private format stays experimental in 0.x. M5 rollback is stopping the daemon: the foreground server and CLI reopen the -same root under the same placement identity. Successor rollback is the -retained original local log plus the previous binary. A previous binary -cannot open the daemon-grade root; when pointed at that directory, its -existing local reader returns `store_file_invalid`, without claiming to -understand the new format. The selected successor daemon binary is the oldest -reader of the daemon-grade root. The imported original is never modified, so -restoring it is a copy, not a reverse migration. Backup is a quiescent copy -of the root verified by the adapter's own integrity check; restore reopens -that copy under the same placement identity. +same root under the same placement identity. There is no forward migration to +roll back, because M5 introduces none. Technical depth: [Compatibility mechanics](0031-daemon-grade-store-selection-and-migration-technical.md#technical-adr-0031-compatibility). diff --git a/docs/adr/README.md b/docs/adr/README.md index 8c144fd20..588698149 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -40,7 +40,7 @@ a decision adds a new record rather than rewriting the old one. | 0028 | Bounded artifact retrieval | Accepted | [Decision](0028-bounded-artifact-retrieval.md#concept) | [Technical depth](0028-bounded-artifact-retrieval-technical.md#technical-depth) | | 0029 | Bounded provider failure diagnostics | Accepted | [Decision](0029-bounded-provider-failure-diagnostics.md#concept) | [Technical depth](0029-bounded-provider-failure-diagnostics-technical.md#technical-depth) | | 0030 | Observability: tracing and telemetry | Accepted | [Decision](0030-observability-tracing-and-telemetry.md#concept) | [Technical depth](0030-observability-tracing-and-telemetry-technical.md#technical-depth) | -| 0031 | Daemon-grade store selection and migration | Proposed | [Decision](0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | +| 0031 | Daemon store selection for `0.2.0` | Proposed | [Decision](0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | | 0032 | Daemon attachment residency and replay | Proposed | [Decision](0032-daemon-attachment-residency-and-replay.md#concept) | [Technical depth](0032-daemon-attachment-residency-and-replay-technical.md#technical-depth) | | 0033 | Collaboration: controller lease and takeover | Proposed | [Decision](0033-collaboration-controller-lease-and-takeover.md#concept) | [Technical depth](0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth) | | 0034 | Provider credential handoff over the bootstrap channel | Proposed | [Decision](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | [Technical depth](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-depth) | @@ -162,9 +162,10 @@ The protocol/interaction proposals were renumbered from the old draft's 0019/002 because those numbers are now accepted M2 decisions. 0031 to 0034 are the four Proposed M5 prerequisites: the daemon's store -selection, which for M5 is the existing local adapter with its documented -limits and retirement procedure and for the successor milestone the -daemon-grade adapter chosen by contract experiments plus its migration; daemon +selection for `0.2.0`, which is the existing local adapter with its documented +limits, its capacity-as-store-loss consequence and its retirement procedure, +leaving a daemon-grade adapter and any migration open for a separate decision; +daemon attachment residency and at-least-once replay over the generation-2-only Unix-domain-socket transport with bounded session pages; the collaboration rule of one in-memory controller lease with fresh per-grant epochs, observers diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d3bb7701c..e142c6bf0 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -17,14 +17,14 @@ decision named only in prose declares nothing. | Decision | Acceptance point | What its acceptance settles | | --- | --- | --- | -| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 1 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and operator root-retirement procedure documented; the daemon-grade adapter, its experiments and its migration reserved for the successor milestone | +| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 1 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or the core attachment change lands, so before workstreams 2 and 4 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 3 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by a `{resolver_module, reference_term}` reference the host owns, resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; the resolver's owner, custody, rotation, deadline bounding and every failure outcome; no environment read in the adapter's call path and the launcher's enumeration moved to composition; the re-pointed credential-plane proofs and the security review as acceptance points | -ADR 0031's daemon-grade adapter, its contract experiments and its migration -belong to the successor milestone and bind nothing in M5; only its -local-adapter selection and documented limits are M5 prerequisites. +ADR 0031 decides one thing, the `0.2.0` local-adapter selection and its +documented limits. It prescribes no successor engine, experiment or migration; +those are named as open questions there and settled by their own decision. M4 owns interactions, transfers, the foreground server and observability. An inherited defect is reproduced at the exact base and repaired at its owner; a diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 4fb84bcb3..383d9bcf2 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -247,7 +247,7 @@ implementation that depends on it, not before unrelated work. | Decision | What it settles | Outcomes that wait on it | | --- | --- | --- | -| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal and operator root-retirement procedure documented; the daemon-grade adapter, its selection experiments and its migration are the successor milestone's | 1, 5 | +| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence and the operator root-retirement procedure documented; a daemon-grade adapter and any migration are left open for a separate decision and prescribed nowhere | 1, 5 | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by a host-owned reference and resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the reference's shape, the resolver's owner, custody, rotation, bounding and every failure are exact; the adapter reads no environment variable for it and its enumeration leaves the call path | 6 | From 4073538d68a46a845bc96c6d9da025f33117f7a0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:47:14 -0700 Subject: [PATCH 015/585] plan(M5): correct verification selection, workstream order and doc gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit findings 13, 14, 15 and 16. Finding 13 holds. The selection table's row at docs/developer/verification.md reads "The executor's OS boundary (launch, signals, cleanup)" and its companion row at verification-technical.md:79 points only at apps/loopex_executor_local/test/coding_tools_test.exs, so nothing in the guide selects pinned-load.sh for a provider change. Both rows now name an operating-system process boundary generally and list the provider child's five cases — provider_launcher_test.exs, provider_startup_boundaries_test.exs, provider_deadline_test.exs, provider_retainer_boundaries_test.exs and credential_plane_test.exs. Both documents join M5's required documentation changes, and the plan says the widening is M5's work rather than an assumption it may make. Finding 14 holds. The concept listed the daemon first and core concurrent attachments fourth while the companion's rejoin order puts the core change before anything the daemon can prove. The concept list is reordered to the rejoin order, workstream 1 is stated as landing in two parts, and every downstream reference is renumbered: ADR 0031 before workstream 2, ADR 0032 before workstreams 1 and 3, ADR 0033 before workstream 4, in the plan's prerequisite table and in the two ADRs' own prerequisite lines. Finding 15 holds. host.ex:221 reads the credential variable and host.ex:138 composes the store the daemon composes too; scripts/check-release.sh gates on the same variable and gains loopex_daemon; the provider pages and the closure evidence page are written by both. The claim is replaced by a table of the four shared surfaces and who resolves them, and by the narrower claim that is actually true. Finding 16: the gate is kept and made auditable. Closure retains a checklist derived from the candidate by git ls-files over both documentation trees, sorted, every row marked updated or reviewed unchanged, with no unmarked row and no path missing. --- ...-daemon-attachment-residency-and-replay.md | 6 +- ...aboration-controller-lease-and-takeover.md | 4 +- docs/developer/verification-technical.md | 7 +- docs/developer/verification.md | 2 +- docs/plans/M5-technical.md | 70 +++++++++++++------ docs/plans/M5.md | 58 ++++++++++----- 6 files changed, 103 insertions(+), 44 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 8d2237820..53dc82af8 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -9,7 +9,7 @@ Technical depth: [Attachment residency mechanics](0032-daemon-attachment-residen - **Supersedes:** nothing; ADR 0023's one-attachment-per-foreground-process rule and generation-1 wire remain in force on the foreground server - **Prerequisite for:** M5 outcomes 1, 2 and 4, accepted before the socket is bound or the core attachment change lands — that is, before M5's workstreams - 2 and 4 + 1 and 3 ### Context and Decision @@ -39,7 +39,9 @@ method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core has no durable stop command, and M5's only core change is concurrent attachment. Ending work is releasing control and disconnecting, after which -the session goes dormant and `session.resume` brings it back. A client that offers only generation 1 is refused at initialize under +the session goes dormant and `session.resume` brings it back. + +A client that offers only generation 1 is refused at initialize under ADR 0023's existing no-common-generation rule and nothing durable is created; generation-1 clients keep the M4 foreground server, whose wire, one-attachment rule and behavior do not change. A narrow core change lets diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index 5574d5230..bfe3aeb82 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -8,7 +8,7 @@ Technical depth: [Collaboration mechanics](0033-collaboration-controller-lease-a - **Decision owner:** Maintainer - **Supersedes:** nothing; the core keeps the vision §11.6 rule that it mandates no controller lease - **Prerequisite for:** M5 Outcome 3, accepted before any admission check is - written — that is, before M5's workstream 3 + written — that is, before M5's workstream 4 ### Context and Decision @@ -71,7 +71,7 @@ release on orderly disconnect. Expiry and an unresolved admission meet on one rule, so neither promise is quietly broken by the other: a mutation whose holder check completed before the deadline settles under its lease even if the deadline passes while core is still deciding; at the deadline the holder gains -nothing further and every new mutation of its refuses; and a takeover becomes +nothing further and every new mutation of its own refuses; and a takeover becomes eligible at the deadline but is granted only once those in-flight mutations have resolved. That adds no grace, because the expired holder can only finish what it had already begun. Writer exclusion between two daemons on one diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index 53edbf2fb..1f2d4fa2f 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -76,13 +76,14 @@ Concept: [Selection](verification.md#concept-verification-selection). | Observability | `apps/loopex/test/trace_session_test.exs`, `telemetry_boundary_test.exs`, `apps/loopex_telemetry/test/` | | Dependency direction | `mix loopex.deps_budget` and `apps/loopex/test/deps_budget_test.exs` | | Documentation chain | `mix loopex.status`, `mix loopex.docs_check` | -| The executor's OS boundary | `apps/loopex_executor_local/test/coding_tools_test.exs` launch-guard, cleanup and frame cases; reproduced under contention by the procedure below | +| An operating-system process boundary | The local executor's: `apps/loopex_executor_local/test/coding_tools_test.exs` launch-guard, cleanup and frame cases. The provider adapter's child: `apps/loopex_llm_reqllm/test/provider_launcher_test.exs`, `provider_startup_boundaries_test.exs`, `provider_deadline_test.exs`, `provider_retainer_boundaries_test.exs` and `credential_plane_test.exs`, which own the spawn, the control-pipe bootstrap handshake, the deadline and the cleanup grace. Either is reproduced under contention by the procedure below | **Reproducing an executor race under contention.** The launch guard, its wrapper subshell and the tool share one pipe, and the hosted runner's four loaded cores exposed a frame split that a twenty-core machine never showed. -The procedure that reproduced it on serenity, and that a change to the -executor's OS boundary is read against: pin the test VM and eight busy-loop +The procedure that reproduced it on serenity, and that a change to any +operating-system process boundary is read against — the executor's, and the +provider child's, which has the same spawn, control-pipe and cleanup shape: pin the test VM and eight busy-loop hogs to four cores with `taskset -c 0-3`, add one process writing 8 MiB with `dd oflag=dsync` in a loop, and run the case in a loop of thirty, counting any run past its 60 s run deadline as a hang. The frame split reproduced 2 in 34 diff --git a/docs/developer/verification.md b/docs/developer/verification.md index d06be0bb5..3cd48b485 100644 --- a/docs/developer/verification.md +++ b/docs/developer/verification.md @@ -63,7 +63,7 @@ Technical depth: [The selection table](verification-technical.md#technical-verif | The wire protocol, its schema or vectors | The Node consumer workflows (`--only node_client`, part of the release check), and the compatibility surfaces page updated in the same change | | The CLI or operator-facing commands | The operator page that describes the behavior updated in the same change; a changed operator command also selects its workflow in the release check | | Provider or credential handling | `bash scripts/check-release.sh`, the real-provider cases | -| The executor's OS boundary (launch, signals, cleanup) | `bash scripts/fixtures/pinned-load.sh` over the touched cases on a Linux host: thirty runs under four pinned cores and load, no failure and no hang | +| An operating-system process boundary (launch, control pipe, signals, cleanup) — the local executor's, or the provider adapter's child | `bash scripts/fixtures/pinned-load.sh` over the touched cases on a Linux host: thirty runs under four pinned cores and load, no failure and no hang | | The toolchain floor or `.tool-versions` | The fast check under the floor pair once | | Documentation only | `bash scripts/check.sh --docs`, which `check.sh --select` chooses on its own for a prose-only diff | | Unknown | The release check, and the review names the boundaries it found | diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index e142c6bf0..d698c1b78 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -17,9 +17,9 @@ decision named only in prose declares nothing. | Decision | Acceptance point | What its acceptance settles | | --- | --- | --- | -| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 1 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | -| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or the core attachment change lands, so before workstreams 2 and 4 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | -| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 3 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | +| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | +| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or the core attachment change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | +| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by a `{resolver_module, reference_term}` reference the host owns, resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; the resolver's owner, custody, rotation, deadline bounding and every failure outcome; no environment read in the adapter's call path and the launcher's enumeration moved to composition; the re-pointed credential-plane proofs and the security review as acceptance points | ADR 0031 decides one thing, the `0.2.0` local-adapter selection and its @@ -47,25 +47,44 @@ Concept: [Scope](M5.md#concept-plan-scope). | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | **Rejoin order.** Prerequisite decisions first. Then the new application with -its dependency-budget change, and the narrow core attachment change, which the -daemon's attach path needs before it can be proved. Then marker-first daemon -lifetime and the socket over the local adapter, workstreams 1 and 2, which may -run together once the application exists. Then the collaboration lease, -workstream 3, on that base. Then the daemon-side residency, replay and -backpressure that sit above the core change, the rest of workstream 4. Then -the two-process workflow with the reference CLI and the independent Node -client. Then the documentation and the source-archive proof, workstream 6, at -the end because it describes what the others built. Then independent review of -the closure candidate. +its dependency-budget change, and the narrow core attachment change — the +first half of workstream 1, which the daemon's attach path needs before it can +be proved, and which is why workstream 1 is numbered first in the concept +pair. Then marker-first daemon lifetime and the socket over the local adapter, +workstreams 2 and 3, which may run together once the application exists. Then +the collaboration lease, workstream 4, on that base. Then the daemon-side +residency, replay and backpressure that sit above the core change, the second +half of workstream 1. Then the two-process workflow with the reference CLI and +the independent Node client. Then the documentation and the source-archive +proof, workstream 6, at the end because it describes what the others built. +Then independent review of the closure candidate. Prove lifetime, refusal of a second daemon at the marker, shutdown on store loss, capacity refusal, reopening under the foreground server after an orderly stop, independent simultaneous core attachments, snapshot-then-contiguous delivery, stale-epoch refusal, takeover and cross-process abort before the -client workflow rejoins. Workstream 5, the credential handoff, is independent -of every other workstream: it touches `apps/loopex_llm_reqllm` and the host -composition sites that read the credential variable, shares no file with the -daemon work, and may land at any point after ADR 0034 is accepted. +client workflow rejoins. + +Workstream 5, the credential handoff and the provider dependency, is +independent of the daemon's *semantics* and may land at any point after +ADR 0034 is accepted. It is not, however, file-disjoint from the daemon work, +and an earlier draft's claim that it shares no file with the other +workstreams would have set the rejoin up to fail. It owns `apps/loopex_llm_reqllm` +outright, but four surfaces are shared with the daemon workstreams and belong +to the integrator, who resolves them rather than either writer: + +| Shared surface | Why both reach it | +| --- | --- | +| Host composition — `apps/loopex_composition`, `apps/loopex_app_server/lib/loopex_app_server/host.ex`, `apps/loopex_cli` | The credential item changes how every host supplies a credential reference and deletes the operator's variable; the daemon *is* a new host composed the same way, and `host.ex:221` is where the variable is read today | +| The integration scripts — `scripts/check-release.sh` and its fixtures | Workstream 5 selects the real-provider lane; the daemon workstreams add `loopex_daemon` to `release_apps` and the Linux cross-uid case | +| Provider and credential documentation under `docs/operator/` and `docs/developer/` | Workstream 5 adds the operator credential sentence and the host-composition note; workstream 6 rewrites the same pages for the daemon | +| Closure evidence — `docs/evidence/M5-closure-runs.md` and `docs/evidence/README.md` | Every workstream's runs, the security review and the demonstration are retained on one page | + +So workstream 5 takes its own worktree like every other writer, and the +integrator sequences those four surfaces. What is true without qualification +is narrower and worth stating on its own: workstream 5 touches no daemon +application code, and no daemon workstream touches the adapter's library +tree. Parallel writers take one worktree each over these non-overlapping paths, and one integrator owns rejoin, conflicts and post-rejoin verification, as the @@ -123,8 +142,15 @@ merge needs green in hosted CI, M5 selects exactly these, from the - Outcome 6 is provider and credential handling, so it selects `bash scripts/check-release.sh` and its real-provider cases; - Outcome 6 also changes an operating-system process boundary with the same - spawn, control-pipe and cleanup shape the executor's has, so the touched - cases run under `bash scripts/fixtures/pinned-load.sh` on a Linux host: + spawn, control-pipe and cleanup shape the executor's has. That row of the + selection table named only the executor until M5 widened it, so widening it + is M5's work and not an assumption M5 may make: both verification documents + change in the same milestone, and the provider cases the row now names are + `apps/loopex_llm_reqllm/test/provider_launcher_test.exs`, + `provider_startup_boundaries_test.exs`, `provider_deadline_test.exs`, + `provider_retainer_boundaries_test.exs` and `credential_plane_test.exs`. + Those are the cases that run under `bash scripts/fixtures/pinned-load.sh` + on a Linux host: the test VM and eight busy-loop hogs pinned to four cores with `taskset -c 0-3`, one process writing 8 MiB with `dd oflag=dsync` in a loop, thirty runs, any run past its 60 s deadline counted as a hang, and no @@ -166,7 +192,11 @@ and the developer pair `docs/developer/daemon.md` and `docs/developer/runtime-and-embedding.md`, `docs/developer/agent-loop-and-tools.md`, `docs/developer/compatibility-surfaces.md`, -`docs/developer/agent-context-map.md`, the indexes +`docs/developer/agent-context-map.md`, the verification pair +`docs/developer/verification.md` and +`docs/developer/verification-technical.md`, whose +operating-system-process-boundary row and its case list M5 widens from the +executor to the provider child, the indexes `docs/operator/README.md`, `docs/developer/README.md`, `docs/README.md` and `README.md`, and `CHANGELOG.md`. Outcome 6 adds the operator's credential sentence and the developer note on host composition to the pages that describe diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 383d9bcf2..cbb5576ee 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -209,6 +209,18 @@ indexing, and for stale foreground-only claims — including the files M5 leaves unchanged. The documentation the milestone changed is part of the closure candidate, as it is for every milestone. +That gate is only worth keeping if a reviewer can check it, so it leaves a +record rather than an assurance. The closure evidence carries a checklist +derived from the candidate itself — every tracked `docs/operator/**/*.md` and +`docs/developer/**/*.md` path as `git ls-files` lists them at that commit, +sorted, one row each — and every row is marked either *updated* or *reviewed +unchanged*, with any finding named and resolved before the packet is +assembled. A path present in the tree and absent from the list, or a row with +neither mark, is an unfinished gate. Deriving the list from the candidate +rather than writing it by hand is the point: a file added late cannot be +missed by a checklist that is generated from the same bytes the reviewer +reads. + Technical depth: [Prerequisites and acceptance points](M5-technical.md#technical-plan-prerequisites). Technical depth: [Ownership and rejoin order](M5-technical.md#technical-plan-ownership). @@ -280,7 +292,10 @@ M5 reaches are five: the wire protocol, for generation 2's schema and vectors; the CLI and operator-facing commands, for `loopex daemon`, `loopex attach` and `loopex sessions`; provider and credential handling, for Outcome 6; the operating-system process boundary, because Outcome 6 changes -the provider child's spawn, control pipe and cleanup; and durable records and +the provider child's spawn, control pipe and cleanup — a row that named only +the executor until M5 widened it, so widening both verification documents is +part of M5's own documentation work rather than something it may assume; and +durable records and the Store, which M5 touches only through the daemon's use of the unchanged adapter. The toolchain floor and `.tool-versions` are unchanged, so nothing selects that row. What each of the five costs, down to the command and its @@ -347,11 +362,23 @@ Technical depth: [Packaging mechanics](M5-technical.md#technical-plan-packaging) ## Workstreams -Six workstreams. The first four are ordered by what each needs to exist -before it can be proved; the fifth is independent of all of them; the sixth -runs last because it describes what the others built. - -1. **The daemon.** One new application, `loopex_daemon`: marker-first startup +Six workstreams, listed in the order the technical companion's rejoin order +puts them in, which is the order of what each needs to exist before it can be +proved. Core concurrent attachment comes first, because the daemon's attach +path cannot be proved without it; the fifth is independent of all of them; the +sixth runs last because it describes what the others built. Workstream 1 lands +in two parts — the core change first, its daemon-side residency after the +lease — and the companion's rejoin order says where each part goes. + +1. **Core concurrent attachments, and the residency above them.** The narrow + core change that lets distinct attachments to one session coexist without + implicit replacement — which the daemon's attach path needs before anything + about it can be proved, so it lands first — and then, once the lease + exists, the daemon-side residency over it: the resident window as a + droppable cache, per-connection output buffers, detachment at the last + emitted cursor, idle eviction, dormancy and the aggregate byte ceiling with + its deterministic reclamation. +2. **The daemon.** One new application, `loopex_daemon`: marker-first startup on the local adapter with explicit stale-writer recovery, session lifetime with zero attachments, orderly stop and abrupt death, lazy activation after restart under the same placement identity, active and dormant residency @@ -359,21 +386,16 @@ runs last because it describes what the others built. activation refusal for a session this composition cannot serve, shutdown on store loss, capacity as one such loss, and reopening under the foreground server after an orderly stop. -2. **The socket transport.** The listener, its owner-only peer check and path +3. **The socket transport.** The listener, its owner-only peer check and path bound, ADR 0023's framing and records reused, generation 2's schema and vectors beside generation 1's, negotiation and the generation-1-only refusal, and the differential conformance that the facade, the foreground server and the socket produce the same durable identities. -3. **The collaboration lease.** The in-memory lease record, the per-session +4. **The collaboration lease.** The in-memory lease record, the per-session owner that serializes lease transitions with admission handoff, the combined holder, epoch, state and term check, explicit takeover with a - fresh epoch, fencing after a real kill, and cross-process abort through the - core's existing durable command. -4. **Core concurrent attachments.** The narrow core change that lets distinct - attachments to one session coexist without implicit replacement, and the - daemon-side residency above it: the resident window, per-connection output - buffers, detachment at the last emitted cursor, idle eviction and the - aggregate byte ceiling. + fresh epoch and the expiry linearization, fencing after a real kill, and + cross-process abort through the core's existing durable command. 5. **The credential handoff and the provider dependency.** ADR 0034's change to the provider adapter and to the host composition sites that read the operator's variable, the re-pointed credential-plane proofs, the new proofs @@ -388,7 +410,11 @@ runs last because it describes what the others built. the adapter and streaming-conformance suites green, and the real-provider case at closure. It is sequenced before the credential change where both touch the adapter, so the credential proofs are written once against the - upgraded library rather than twice. + upgraded library rather than twice. It touches no daemon application code, + and no daemon workstream touches the adapter's library tree — but it is not + file-disjoint from them: host composition, the integration scripts, the + provider pages and the closure evidence page are reached by both, and the + companion names them as the integrator's to sequence. 6. **Documentation and the `0.2.0` release candidate.** The operator daemon guide and the developer daemon pair, the updates M5 forces on the existing operator and developer pages, the changelog and the indexes, the `VERSION` From 95c1bf210fd61e96f8956fab1531fae0ba6c91a8 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:47:36 -0700 Subject: [PATCH 016/585] plan(M5): record the derived documentation checklist in the companion Audit finding 16, technical half. The previous commit added the derived checklist to the concept file but its companion edits were dropped by a failed scripted replacement; Outcome 5's evidence row and the documentation paragraph now carry the same obligation: a checklist derived at the candidate by git ls-files over both documentation trees, sorted, every row marked updated or reviewed unchanged, retained with the closure runs. --- docs/plans/M5-technical.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d698c1b78..e464c80f0 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -126,7 +126,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: a permissive directory or socket mode, a parent the daemon does not own, and a path component it did not create each refused at start, and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; the holder disconnecting and the per-session lease owner failing, each while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, and each finding is resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files 'docs/operator/**/*.md' 'docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table refuses with its stable reason and retains no copy: absent reference, malformed reference, a resolver module without the callback, a refusing resolver, a resolver silent past the invocation deadline, a value outside the size bound, and two resolutions in flight at once. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every @@ -202,7 +202,8 @@ executor to the provider child, the indexes sentence and the developer note on host composition to the pages that describe provider configuration. Every other tracked file under `docs/operator/` and `docs/developer/` is read at the candidate and left unchanged only -deliberately. +deliberately, and the derived checklist in Outcome 5's evidence row is what +makes that auditable rather than asserted. **Test honesty.** Future test bodies are written with their implementation; a missing witness is never a pass. Real-provider cases live in their own files From 31fe4782debc9bd55394fdfd2935ff224ea63ae4 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:50:49 -0700 Subject: [PATCH 017/585] adr(0035): propose typed decision models as policy inputs Maintainer addition, not from the audit and not an M5 prerequisite. The decision: a typed decision model may be an input to a host's policy decision and a journaled plain-data fact, and may never be the decision. That follows the contract's existing rule that model output never grants authority, and adds that a typed, calibrated answer is still model output and gets no privilege for being numeric. Enforcement is the Loopex.Policy resolution table that already fails closed on anything unexpected; thresholds stay with the host, because a threshold is a statement about acceptable risk. Every fact about the library was read from req_llm 1.24.0's own source rather than taken on description: ReqLLM.Evaluation.evaluate/4 with its eight-option schema that errors on an unrecognised key, questions of type :boolean, :choice or :score with instructions and criteria, answers in result.object under string keys, ReqLLM.Providers.TypeSafe with base url https://api.typesafe.ai, env key TYPESAFE_API_KEY, POST /v1/systemone, a bearer header, the noul normalisation to a probability member, refusal of every operation but :evaluate, and the llm_db >= 2026.9.3 floor. Five seams are named in the order they are worth doing, the state sent is held to the existing context-admission discipline, and the second credential is recorded as a dependency on ADR 0034: two providers make the per-invocation reference per provider. Latency and price are stated as unmeasured until the first real call. M5 carries one bounded experiment from it, an offline scorer in the release check's real-provider case on no live path, recorded in the plan's provider workstream and in the plan's non-goals as a deferred decision. --- docs/README.md | 3 +- ...ision-models-as-policy-inputs-technical.md | 179 ++++++++++++++++++ ...-typed-decision-models-as-policy-inputs.md | 131 +++++++++++++ docs/adr/README.md | 9 + docs/plans/M5.md | 21 +- 5 files changed, 341 insertions(+), 2 deletions(-) create mode 100644 docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md create mode 100644 docs/adr/0035-typed-decision-models-as-policy-inputs.md diff --git a/docs/README.md b/docs/README.md index 69e82f475..1f43bbe05 100644 --- a/docs/README.md +++ b/docs/README.md @@ -76,10 +76,11 @@ pairing, link, review, code-documentation, and enforcement contracts. | 0028 — bounded artifact retrieval | [Decision](adr/0028-bounded-artifact-retrieval.md#concept) | [Technical depth](adr/0028-bounded-artifact-retrieval-technical.md#technical-depth) | | 0029 — bounded provider failure diagnostics | [Decision](adr/0029-bounded-provider-failure-diagnostics.md#concept) | [Technical depth](adr/0029-bounded-provider-failure-diagnostics-technical.md#technical-depth) | | 0030 — observability: tracing and telemetry | [Decision](adr/0030-observability-tracing-and-telemetry.md#concept) | [Technical depth](adr/0030-observability-tracing-and-telemetry-technical.md#technical-depth) | -| 0031 — daemon-grade store selection and migration | [Decision](adr/0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](adr/0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | +| 0031 — daemon store selection for `0.2.0` | [Decision](adr/0031-daemon-grade-store-selection-and-migration.md#concept) | [Technical depth](adr/0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth) | | 0032 — daemon attachment residency and replay | [Decision](adr/0032-daemon-attachment-residency-and-replay.md#concept) | [Technical depth](adr/0032-daemon-attachment-residency-and-replay-technical.md#technical-depth) | | 0033 — collaboration: controller lease and takeover | [Decision](adr/0033-collaboration-controller-lease-and-takeover.md#concept) | [Technical depth](adr/0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth) | | 0034 — provider credential handoff over the bootstrap channel | [Decision](adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | [Technical depth](adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-depth) | +| 0035 — typed decision models as policy inputs | [Decision](adr/0035-typed-decision-models-as-policy-inputs.md#concept) | [Technical depth](adr/0035-typed-decision-models-as-policy-inputs-technical.md#technical-depth) | An ADR pair is one decision. Its status and governance record live in the Concept file and bind both files when accepted. diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md new file mode 100644 index 000000000..7b0cafa98 --- /dev/null +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -0,0 +1,179 @@ + +## Technical depth + +Concept: [Typed decision models as policy inputs](0035-typed-decision-models-as-policy-inputs.md#concept). + + +### Contract and Evidence + +Concept: [Context and decision](0035-typed-decision-models-as-policy-inputs.md#concept-adr-0035-decision). + +### What the model is, exactly + +Everything below was read from `req_llm` 1.24.0's own source on 2026-09-19, +not from a description of it. + +- `ReqLLM.Evaluation.evaluate/4`, reached as `ReqLLM.evaluate/4`, takes a model + input, a state that is a string, a map or a list, a map of questions, and a + keyword option list. Its module documentation calls it "a model call, not a + test run" and says an evaluation model need not support chat generation. +- A question is `%{type: :boolean | :choice | :score, instructions: …, + criteria: …}`, keyed by the name the answer comes back under. `:choice` + carries its options in `criteria`. +- The answers arrive in `result.object` under the question's name as **string** + keys, with probabilities and confidence where the type has them. The provider + normalises its own `noul` answer into a `probability` member. The original + provider payload stays in `provider_meta.raw_response`. +- The options the schema admits, and no others, are `api_key`, `base_url`, + `receive_timeout`, `total_timeout`, `max_retries`, `req_http_options`, + `fixture` and `telemetry`; an unrecognised key is an error rather than being + ignored. +- `ReqLLM.Providers.TypeSafe` declares `default_base_url + "https://api.typesafe.ai"`, `default_env_key "TYPESAFE_API_KEY"`, posts to + `/v1/systemone` with an `authorization: Bearer …` header, and refuses every + operation except `:evaluate` with an explicit parameter error. It supports no + chat, no text generation and no arbitrary JSON schema. +- `req_llm` 1.24.0 requires `llm_db >= 2026.9.3`, so the evaluation seam is not + reachable on an older `llm_db`. + +TypeSafe's own guidance, which shapes how the questions are written rather than +what the code does: questions atomic, batched into one call, their text stable +so probabilities stay comparable between calls, and actions gated on confidence +against thresholds the caller owns. + +### The invariant, and where it is enforced + +**A typed answer is data on the way to a decision, never the decision.** +Concretely: + +- Every seam takes the answer as an *input to a host-owned function*. At the + executor seam that function is the host's `Loopex.Policy` implementation, + which `Loopex.Policy` already resolves exhaustively and fails closed on: + anything but a well-shaped `{:allow, context}` or an enumerated + `{:deny, category}` becomes `{:deny, :policy_unavailable}`, and a raising, + exiting or slow callback denies. That table is unchanged and is what makes + the invariant enforceable rather than merely stated — a policy that consults + an evaluation and mishandles it denies. +- The thresholds are the host's. Loopex fixes no probability, no confidence + floor and no default answer, because a threshold is a policy judgment about + what the operator is willing to risk, and Loopex does not own those. +- An evaluation result never reaches the executor, a grant, a lease, an epoch, + a fence or a receipt. It is not an argument to anything that validates + authority. +- A missing answer is not a default answer. Where an evaluation does not + return — no credential, refusal, timeout, malformed shape — the host decides + exactly as it would with no evaluation configured. No seam has a code path + that exists only when an answer arrives. + +### The state that is sent + +The state is bounded, redacted, provenance-typed data the runtime already +holds, staged under the same context-admission discipline that governs +anything else sent to a provider. The evaluation adds no new class of +sendable data and no new path to it: if something may not be staged for a +completion, it may not be staged for an evaluation. Credentials, PIDs, raw +workspace content that admission did not admit, and anything outside the +bounded plain-data contract stay out by the rules that already exclude them. + +### Credentials + +`TYPESAFE_API_KEY` is a **second** provider credential, and this is the one +place where this decision constrains an earlier one. +[ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) +fixes a per-invocation credential reference the host owns and the sender +resolves. With a second provider it has to be **per provider**: the reference a +call carries names which credential is wanted, and a host composing both +providers supplies two references rather than one ambient value per process. +Nothing about resolution, custody, rotation or the failure table changes; only +the arity of what a host supplies does. This decision therefore depends on +ADR 0034 and cannot be implemented before it is accepted and its change has +landed. + +### Seams, in the order they are worth doing + +| # | Seam | What the questions ask | Who consumes the answer | +| --- | --- | --- | --- | +| 1 | Executor admission triage | Destructive; reaches outside the workspace; apparent intent; risk level | The host's `Loopex.Policy` implementation, with its own thresholds, through the existing seam the reference `AllowAll` and `Ask` occupy | +| 2 | Model routing per turn | Which model this turn should go to | The host's routing choice; the chosen model and the answer that informed it are journaled as a fact beside the run's existing provenance | +| 3 | Interaction escalation | "Does this need the operator", as a probability | The host that already owns whether to ask | +| 4 | Session classification | What kind of work a session is, for listing and residency | The daemon, over sessions it already holds; a daemon-side convenience with no durable effect | +| 5 | Offline transcript scoring | Whatever the release check wants to measure about retained transcripts | The release check, over retained evidence, on no live path | + +Seams 1 to 4 belong to the milestone after M5 and are implemented in that +order, because each earlier one is the cheaper proof of the same invariant. +Seam 5 is the one piece admitted earlier; see below. + +### The one experiment allowed inside M5 + +M5's provider workstream already moves to `req_llm` 1.24 for other reasons, so +the evaluation seam becomes reachable there. One bounded experiment is allowed +inside it, and only this one: an **offline scorer in the release check's +real-provider case** that calls `ReqLLM.evaluate/4` against the real endpoint +over retained transcript material, records the typed answers and the reported +`usage`, and touches no part of the agent loop. It exists to prove the 1.24 API +against the real service and to take the first latency and price measurement, +which this decision otherwise has to assert without evidence. It admits no +seam, changes no policy, journals nothing durable, and gates nothing: if it is +removed, the release check is exactly what it was. Anything beyond it waits for +this ADR's acceptance. + +### Evidence + +The negatives carry the decision and are written before the seams: + +- for every seam, an answer at every extreme — probability 0, probability 1, + confidence 1.0, a `:choice` concentrated on one option — produces exactly the + decision the host would have made without an evaluation, proved by running + each case twice, with the evaluation stubbed at that extreme and with it + absent, and requiring identical decisions and identical durable records; +- no evaluation result appears in a grant, a lease, an epoch, a fence, a + receipt or any executor argument, proved by the same drift-style scan that + pins other forbidden reaches; +- a missing credential, a refusing provider, a timeout, an unrecognised option, + a malformed `object` and an answer for a question that was not asked each + leave every decision unchanged and are each reported as a bounded non-secret + reason; +- nothing an evaluation returns shortens a path that would otherwise ask the + operator; +- the state sent is proved to contain only what context admission admitted. + +The real-provider case proves one call to the real endpoint returns the three +typed shapes and that `usage` is recorded. Latency and price are reported from +it as measurements, never as thresholds a later test may be weakened to meet. + +### Alternatives + +Parsing a text model's prose for the same judgments was rejected: it is +uncalibrated, it moves with phrasing in ways nothing can bound, and it produces +no value to journal, so a later reader cannot compare two runs. A text model +with a structured-output schema was rejected because a schema fixes the shape +of an answer but not its calibration — there is no probability and no +confidence to threshold on — and it costs a full generation to get less. +Putting thresholds in Loopex rather than the host was rejected because a +threshold is a statement about acceptable risk, which the development contract +assigns to host policy along with `allow`, `deny` and `defer`. Letting a +high-confidence answer skip the policy call was rejected outright: it is the +exemption predicate ADR 0009 refuses, arriving with a number attached. + + +### Compatibility and Rollback Mechanics + +Concept: [Consequences and rollback](0035-typed-decision-models-as-policy-inputs.md#concept-adr-0035-consequences). + +Nothing public changes. The `Loopex.Policy` and `Loopex.Model` callbacks, the +public protocol and its generations, public events, snapshots, artifacts, the +executor protocol and every durable record are untouched. A runtime with no +evaluation configured is byte-for-byte the runtime that exists today. The one +compatibility effect is on host composition, and it is ADR 0034's: a credential +reference becomes per provider. + +Rollback is removing the evaluation. Every seam is an input, so a host that +stops asking decides as it did before by the same path; a journaled answer +remains a true record of what was observed at the time and is not a premise +anything later depends on, so nothing has to be migrated or repaired. The +offline scorer, if it exists from M5, is deleted with no effect on the release +check's other cases. + +Acceptance binds this complete pair at the exact candidate the maintainer names +in the governance record. Its claims remain unproved until the tests above +exist and pass and the real-provider case has run. diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md new file mode 100644 index 000000000..58fd47728 --- /dev/null +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -0,0 +1,131 @@ + +## Concept + +Technical depth: [Typed decision model mechanics](0035-typed-decision-models-as-policy-inputs-technical.md#technical-depth). + +- **Status:** Proposed +- **Date:** 2026-09-19 +- **Decision owner:** Maintainer +- **Supersedes:** nothing; it refines where a host may get the *inputs* to the + ADR 0009 policy decision, and changes nothing about who makes it +- **Prerequisite for:** the milestone after M5. It is **not** an M5 + prerequisite and blocks nothing in M5; one bounded experiment named below is + allowed inside M5's provider workstream + + +### Context and Decision + +Several places in the runtime need a judgment that is not a lookup and not a +conversation. Should this tool call be treated as destructive? Is this run +going to need the operator? Which of two models should this turn go to? Today +each of those is either a hand-written predicate over validated arguments, or +it is not asked at all, or it would require asking a text model and reading its +prose — which is the worst of the three, because prose is not a value a +program can act on and cannot be journaled as a fact. + +A different shape of model has become available. TypeSafe AI's *Jev* is what +they call a **System One** model: it generates no text. It takes one state — a +string or a JSON document — and a map of named, typed questions, and returns a +typed answer per question with a probability: `noul`, a yes/no expressed as a +probability between 0 and 1; `choice`, per-option probabilities with a +confidence; and `score`, ordered levels with a confidence. It is one HTTP call +to `POST https://api.typesafe.ai/v1/systemone` with a bearer key in +`TYPESAFE_API_KEY` and the model alias `jev-latest`. Their guidance is that +questions be atomic, that a batch of them go in one call, that the question +text stay stable so probabilities remain comparable across calls, and that +actions be gated on confidence with thresholds the caller owns. + +ReqLLM 1.24.0, released 2026-09-17, added a provider-neutral seam for exactly +this shape: `ReqLLM.Evaluation.evaluate/4`, reached as +`ReqLLM.evaluate("typesafe:jev-latest", state, questions, opts)`. It is +declared in the library as "a model call, not a test run", the provider +supports no chat and no streaming, and the answers come back in +`result.object` under the question's name. + +**Decide that a typed decision model may be an input to a host's decision, and +may never be the decision.** A typed answer is data: a probability, a set of +option probabilities, a level, a confidence. It is journaled as a plain-data +fact where a fact is wanted, and it is handed to the host's own policy where a +decision is wanted. It never becomes a grant, never widens what a policy would +otherwise allow, and never shortens a path that would otherwise ask. This is +not a new principle — the development contract already says that IDs, +interactions, model output, context and metadata never grant authority, and +ADR 0009 already makes every executor-backed tool call consult the host's +policy with no exemption predicate. What this decision adds is that a *typed, +calibrated* model answer is still model output, and gets no privilege for +being numeric. + +The seams, in the order they are worth doing: + +1. **Executor admission triage.** A host policy that asks "is this + destructive, does it reach outside the workspace, what did the caller + appear to intend, how risky does this look" gets those as typed answers and + applies its own thresholds. It consumes them through the policy seam that + already exists — the host's `Loopex.Policy` implementation, of which the + reference `AllowAll` and `Ask` are the two shipped examples — so the port, + its fail-closed resolution table and its deny-on-anything-unexpected + behaviour are untouched. +2. **Model routing per turn**, journaled as a fact: which model a turn was + routed to, and the typed answer that informed it, recorded where the run's + provenance already lives. +3. **Interaction escalation**: "this needs the operator" as a probability, fed + to the host that owns whether to ask. +4. **Session classification** for listing and residency, a daemon-side + convenience over sessions it already holds. +5. **Offline transcript scoring** in the release check, over retained + transcripts, touching no live path at all. + +**Alternatives rejected.** Deriving the same judgments by parsing a text +model's output was rejected: the output is uncalibrated, it varies with +phrasing in ways nothing can bound, and there is no value to journal — a +sentence is not a fact a later reader can compare. Using the text model with a +structured-output schema was rejected for the same reason plus its price: a +schema constrains the shape of an answer but yields no probability and no +confidence, so a host has nothing to threshold on, and it costs a full +generation to obtain. + +**Evidence its acceptance requires.** This is a trust claim, so its class is +negative tests plus a real-provider proof. The negatives are the load-bearing +half: no typed answer, at any confidence including 1.0, ever produces a grant +the host's policy would not otherwise have produced; a missing, malformed, +slow or refusing evaluation leaves every decision exactly as it would have +been without one; and no answer shortens a path that would otherwise ask. The +real-provider case proves the call reaches the endpoint and returns the typed +shapes, and is where latency and price are first measured. + +Technical depth: [Contract and evidence](0035-typed-decision-models-as-policy-inputs-technical.md#technical-adr-0035-decision). + + +### Consequences, Compatibility and Rollback + +A host gains a way to ask a calibrated question and act on the answer with its +own thresholds, instead of writing a predicate that is right until the first +case it did not imagine. Nothing about authority moves: the policy port, its +fail-closed resolution and the executor's validation are unchanged, and a +runtime with no evaluation configured behaves exactly as it does today. + +Three consequences are real costs rather than benefits, and are stated as +such. It is a **second provider credential**, `TYPESAFE_API_KEY` alongside the +model credential, which means +[ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept)'s +per-invocation credential reference has to be **per provider** rather than one +per call — this decision depends on that one and cannot be implemented before +it. The **state sent to the model** is bounded, redacted, provenance-typed +data the runtime already holds, under the same context-admission discipline +that governs anything else staged for a provider; nothing new becomes +sendable. And **latency and price are unmeasured** until the first real call; +they are measured from the response's own `usage` there, and no threshold, no +budget and no timing claim is made before that. + +Rollback is removing the evaluation: every seam is an input, so a host that +stops asking makes the same decisions it made before, by the same paths. No +durable record depends on an answer existing, because an answer is journaled +as a fact about what was observed, not as a premise anything later requires. + +Technical depth: [Compatibility mechanics](0035-typed-decision-models-as-policy-inputs-technical.md#technical-adr-0035-compatibility). + +## Governance Record + +| Decision | Authority | Authority evidence | Bound bytes | +| --- | --- | --- | --- | +| Acceptance | — | — | — | diff --git a/docs/adr/README.md b/docs/adr/README.md index 588698149..9a3a32bc4 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -44,6 +44,7 @@ a decision adds a new record rather than rewriting the old one. | 0032 | Daemon attachment residency and replay | Proposed | [Decision](0032-daemon-attachment-residency-and-replay.md#concept) | [Technical depth](0032-daemon-attachment-residency-and-replay-technical.md#technical-depth) | | 0033 | Collaboration: controller lease and takeover | Proposed | [Decision](0033-collaboration-controller-lease-and-takeover.md#concept) | [Technical depth](0033-collaboration-controller-lease-and-takeover-technical.md#technical-depth) | | 0034 | Provider credential handoff over the bootstrap channel | Proposed | [Decision](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | [Technical depth](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-depth) | +| 0035 | Typed decision models as policy inputs | Proposed | [Decision](0035-typed-decision-models-as-policy-inputs.md#concept) | [Technical depth](0035-typed-decision-models-as-policy-inputs-technical.md#technical-depth) | 0001 and 0002 were the prerequisites that unblocked the first milestone candidate; the [plans register](../plans/README.md) records current status. @@ -175,3 +176,11 @@ the launcher already opens. The first three were proposed with the Open M5 plan on 2026-09-14 and revised twice that day on independent review; 0034 follows the maintainer's outcome of 2026-09-19. They accept nothing, and each must be accepted before the outcome that depends on it is implemented. + +0035 is Proposed for the milestone after M5 and is not an M5 prerequisite: it +decides that a typed decision model — one that returns probabilities and +confidences rather than text — may be an input to a host's policy decision and +a journaled plain-data fact, and may never be the decision. It depends on 0034, +because a second provider makes the per-invocation credential reference per +provider. M5 may run one bounded offline experiment against the real endpoint +inside its provider workstream; nothing else waits on it. diff --git a/docs/plans/M5.md b/docs/plans/M5.md index cbb5576ee..dc60a23ab 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -249,6 +249,16 @@ process topology. The `req_llm` move to `1.24` is an ordinary dependency change and adds no dependency, no adapter capability and no provider surface. Those capabilities retain their vision barriers and require their own evidence. +One decision is recorded for the milestone after M5 and deliberately bound +nothing here. +[ADR 0035](../adr/0035-typed-decision-models-as-policy-inputs.md#concept) +proposes that a typed decision model — one returning probabilities and +confidences rather than text — may be an input to a host's policy decision and +a journaled plain-data fact, never the decision itself. It is not an M5 +prerequisite and no M5 outcome waits on it. M5's provider workstream carries +one bounded experiment from it and nothing more: an offline scorer in the +release check's real-provider case, on no live path. + Technical depth: [Deferral acceptance points](M5-technical.md#technical-plan-prerequisites). @@ -410,7 +420,16 @@ lease — and the companion's rejoin order says where each part goes. the adapter and streaming-conformance suites green, and the real-provider case at closure. It is sequenced before the credential change where both touch the adapter, so the credential proofs are written once against the - upgraded library rather than twice. It touches no daemon application code, + upgraded library rather than twice. Because 1.24 also makes + `ReqLLM.evaluate/4` reachable, this workstream carries one bounded + experiment for + [ADR 0035](../adr/0035-typed-decision-models-as-policy-inputs.md#concept): + an offline scorer in the release check's real-provider case that calls the + real endpoint over retained transcript material and records the typed + answers and the reported `usage`, which is where that decision's latency + and price are first measured. It touches no part of the agent loop, admits + no seam, journals nothing durable and gates nothing; removing it leaves the + release check exactly as it was. It touches no daemon application code, and no daemon workstream touches the adapter's library tree — but it is not file-disjoint from them: host composition, the integration scripts, the provider pages and the closure evidence page are reached by both, and the From 5b982823dec874677549a158eb9166290a3adfc0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:51:30 -0700 Subject: [PATCH 018/585] docs(M5): say in the root README what comes next MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Maintainer addition. The README's narrative ended at M4 and said no milestone was active, which the derived status capsule directly above it contradicts: the capsule records M5 as open. A reader arriving at the repository had no way to learn what the next milestone is for without opening the register. A short "What comes next" section, outside the derived block, now names M5 as the durable-service rung — daemon-owned session lifetime, several client processes over a Unix socket, controller and observers, on the existing local store — and links the plan pair. It says plainly that the pair is open and not accepted and that ADRs 0031 to 0034 are proposed, so it adds no claim the capsule does not support, and it points at the register for state rather than restating it. The stale "no milestone is active" sentence is corrected to agree with the capsule. mix loopex.status passes. --- README.md | 26 ++++++++++++++++++++++++-- 1 file changed, 24 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index dae675929..779b6bbf3 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,9 @@ while the session lives; a session "brain" can coordinate local or remote [Canonical milestone status and plan records](docs/plans/) -M0 through M4 are closed and integrated; no milestone is active. M1 delivered the durability kernel: an explicit -embedded runtime, durable local Store, canonical model boundary, trusted-local +M0 through M4 are closed and integrated, and `M5` is open and not yet +accepted, as the capsule above records. M1 delivered the durability kernel: +an explicit embedded runtime, durable local Store, canonical model boundary, trusted-local executor, thin reference client, durable events, and receipt reconciliation across a real runtime-process crash. What it deliberately did not deliver is a usable coding loop — that loop ran a fixed two turns, carried no conversation @@ -129,6 +130,27 @@ supervision on Darwin and Linux; raw commands still use `/bin/sh`. See the [runtime prerequisite](docs/operator/tools-and-policy.md#operator-local-supervision-shell) before using the reference stack. Core and custom executors are unaffected. +### What Comes Next + +`M5` is the next milestone, and it is the durable-service rung: a local daemon +that owns session lifetime for a state root, so sessions keep running while no +client is connected; several independent client processes reaching one session +over a Unix-domain socket; one of them driving while the others watch, with an +explicit takeover when the driver dies; and all of it on the existing local +store adapter within that adapter's documented limits. Read the +[M5 plan](docs/plans/M5.md#concept) and its +[technical companion](docs/plans/M5-technical.md#technical-depth) for the +purpose, outcomes and how each one is to be proved. + +Nothing in it is settled yet. The plan pair is open and not accepted, and its +four prerequisite decisions — ADRs [0031](docs/adr/0031-daemon-grade-store-selection-and-migration.md#concept), +[0032](docs/adr/0032-daemon-attachment-residency-and-replay.md#concept), +[0033](docs/adr/0033-collaboration-controller-lease-and-takeover.md#concept) +and [0034](docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) +— are proposed, not accepted. The status capsule above and the +[canonical register](docs/plans/README.md) carry the milestone state; this +paragraph only says what the work is for. + The [roadmap](docs/roadmap.md#concept) is non-normative capability guidance; [CHANGELOG.md](CHANGELOG.md) records what changed. From cf7c50efc670426cf469e1070c29a141465101c7 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 18:52:33 -0700 Subject: [PATCH 019/585] plan(M5): remove the last stale telemetry and store-scope wording Self-review of the audit fix set found two leftovers from earlier commits. The Design Decisions section still described ADR 0030 as fixing "the telemetry inventory every daemon boundary emits", which is the claim finding 9 removed everywhere else; it now says the inventory is closed, that M5 emits nothing outside it, and that a daemon event would need an amendment. ADR 0031's two reciprocal link titles still advertised daemon-grade store mechanics after finding 12 narrowed the pair to the 0.2.0 selection, so both now name what the files actually contain. The file names are unchanged, because an ADR's name is its permanent identity. The remaining mention of the successor experiments sits inside the historical "Revision of 2026-09-14" record and is left exactly as written: it records what was decided then and is not a current claim. --- ...daemon-grade-store-selection-and-migration-technical.md | 2 +- .../adr/0031-daemon-grade-store-selection-and-migration.md | 2 +- docs/plans/M5.md | 7 ++++--- 3 files changed, 6 insertions(+), 5 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 026b16e9d..300adfa6f 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -1,7 +1,7 @@ ## Technical depth -Concept: [Daemon-grade store selection and migration](0031-daemon-grade-store-selection-and-migration.md#concept). +Concept: [Daemon store selection for `0.2.0`](0031-daemon-grade-store-selection-and-migration.md#concept). ### Contract and Evidence diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 9a69a216d..55ba676c4 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -1,7 +1,7 @@ ## Concept -Technical depth: [Daemon-grade store mechanics](0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth). +Technical depth: [Local adapter limits and what stays open](0031-daemon-grade-store-selection-and-migration-technical.md#technical-depth). - **Status:** Proposed - **Date:** 2026-09-14 diff --git a/docs/plans/M5.md b/docs/plans/M5.md index dc60a23ab..ff4f1fae3 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -275,9 +275,10 @@ implementation that depends on it, not before unrelated work. | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by a host-owned reference and resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the reference's shape, the resolver's owner, custody, rotation, bounding and every failure are exact; the adapter reads no environment variable for it and its enumeration leaves the call path | 6 | Three accepted decisions remain load-bearing and are not reopened: M4's -ADR 0023 fixes the protocol M5's generation 2 extends and M4's ADR 0030 fixes -the telemetry inventory every daemon boundary emits, while the post-M2 -ADR 0019 fixes the provider process topology ADR 0034 refines. +ADR 0023 fixes the protocol M5's generation 2 extends, M4's ADR 0030 fixes the +closed telemetry inventory M5 emits nothing outside of and would have to amend +to add a daemon event, and the post-M2 ADR 0019 fixes the provider process +topology ADR 0034 refines. ### How Each Outcome Is Verified From ca9d95aff386b8663ab181b4872caef18fd80121 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:29:56 -0700 Subject: [PATCH 020/585] adr(M5): make the credential custody contract implementable Second-round item 1. The pair could not be built as written: it said the value exists only in the sender and never in a message, while custody sat in a long-lived host process the sender asks -- and answering is a message. The single permitted credential-bearing transfer is now named: the custody process's reply to resolve/2, bounded by the same 1..65,536-byte rule as the frame, unlogged, never forwarded, never retained after the write. It is the same class of act as the frame write, and ADR 0019 already protects that process with its own group-leader sink. Observation is bound rather than assumed: ADR 0030's arguments level already redacts values reachable through a credential reference, and because the sender is a Loopex.* module reachable by set_on_spawn, M5 must prove the reply falls inside that class under a real trace session. No ADR 0030 amendment. The callback becomes resolve(reference_term, deadline) with deadline an absolute monotonic instant, not a remaining duration, which the text asserted while the signature had no such argument. Reasons are a closed set -- :missing, :expired, :oversized, :unavailable from the resolver and :timeout from the sender -- so a host-authored term cannot smuggle a secret into a reason, and the sender reports :ok | {:error, reason} rather than a bare :error so the guardian distinguishes a refusal from a silence. Concurrent resolution is stated once, as independent successes. The refusal wording is deleted, with the reason recorded: a custody process that refused concurrent callers would reintroduce the serialisation this decision exists to remove. The consequences sentence now says where the credential is in the parent -- custody process and sender, nowhere else. --- ...andoff-over-bootstrap-channel-technical.md | 112 ++++++++++++++---- ...edential-handoff-over-bootstrap-channel.md | 50 +++++--- docs/plans/M5-technical.md | 2 +- 3 files changed, 120 insertions(+), 44 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index a82ae0953..7e73a0da1 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -60,7 +60,11 @@ configuration map the host already supplies to `complete/3`. Its value is - `resolver_module` is an atom naming a module that implements `Loopex.LLM.ReqLLM.CredentialResolver`, one callback, - `resolve(reference_term) :: {:ok, binary()} | {:error, term()}`; + `resolve(reference_term, deadline) :: {:ok, binary()} | {:error, reason}`, + where `deadline` is an **absolute monotonic instant** in native units, not a + remaining duration — a duration is stale the moment it is computed, and the + sender and the resolver are different processes. `reason` comes from the + closed set below and never from the resolver's own vocabulary; - `reference_term` is bounded plain boundary data — at most 256 bytes when encoded by the repository's canonical encoding, and never a PID, port, function, monitor or reference. It names which credential is wanted; it is @@ -78,11 +82,43 @@ reference implementation states its own custody and proves it for itself: the reference CLI, the app-server host and the M5 daemon read `Loopex.LLM.ReqLLM.credential_variable/0` exactly once, where they compose the runtime, delete that name from the VM's environment in the same step, and hold -the bytes in one host-owned process, registered under the runtime reference -rather than a global name, whose `format_status/1` redacts its state and which -answers `resolve/1` only for its own reference term. The real-provider lane -composes the same way. Nothing in the adapter depends on that arrangement, and -a different host may keep the bytes anywhere it can defend. +the bytes in one host-owned custody process, registered under the runtime +reference rather than a global name, whose `format_status/1` redacts its state +and which answers `resolve/2` only for its own reference term. The +real-provider lane composes the same way. Nothing in the adapter depends on +that arrangement, and a different host may keep the bytes anywhere it can +defend. + +**Exactly one credential-bearing transfer exists in the parent, and it is +named.** An earlier draft said the value never appears in a message while also +putting custody in a long-lived process the sender asks — which cannot both be +true, because answering is a message. The contract is a permission with a +boundary, not an absolute: + +- The **only** permitted credential-bearing transfer in the parent is the + custody process's reply to `resolve/2`, carrying `{:ok, bytes}` to the one + sender process that asked. It is bounded by the same 1..65,536-byte rule as + the frame, it is never logged, never forwarded, and never held after the + frame is written. +- It is deliberately the same class of act as the credential frame write: one + short-lived process receives the bytes, uses them once, and dies. ADR 0019 + already protects that process — the sender installs its own group-leader + sink so no IO request can carry anything out of it, it is unregistered, and + it reports only an atom or a `{:error, atom}` pair to the guardian. +- Observation of the sender is governed by the tracing rules rather than left + to hope. ADR 0030's `arguments` level redacts "a credential reference, model + content, tool arguments and artifact bytes to placeholders" and replaces + "any value reachable through a credential reference". The sender is a + `Loopex.*` module and, spawned beneath runtime-owned processes, is reachable + by `set_on_spawn`, so M5 must **prove** that the reply and the resolved value + fall inside that redaction class: a trace session at the `arguments` level + over a real invocation shows placeholders and no credential bytes. That is a + proof obligation on M5, not a change to ADR 0030, whose redaction class + already names this category. +- Everywhere else the earlier absolutes stand unchanged: not in guardian + state, not in an exit reason, not in a crash report, not in an IO request, + not in a file, not in the environment, not in argv, and in no durable or + public plane. **When it is resolved.** Exactly once per invocation, inside the sender process, between the child's `ready` frame and the credential frame — step 5 @@ -96,9 +132,24 @@ is in flight does not reach that invocation, which has already resolved; it reaches the next one. Nothing is invalidated and no invocation is restarted. **Timeout.** Resolution is bounded by the invocation's existing deadline and by -nothing else; this decision adds no second clock. The sender calls the -resolver with the remaining time to that deadline, and a resolver that has not -answered when it elapses is a failed resolution. +nothing else; this decision adds no second clock. The sender passes that +deadline as an absolute monotonic instant, and a resolver that has not answered +when it is reached is a failed resolution reported as `:timeout`. + +**The closed reason set.** A resolver answers `{:error, reason}` only with +`:missing`, `:expired`, `:oversized` or `:unavailable`; the sender itself +produces `:timeout`. Nothing else is admitted — a resolver returning anything +outside the set is treated as `:unavailable`, because a host-authored term is +exactly where a secret could be smuggled into a reason. The five atoms carry no +content, so they are safe in a message, an exit reason and a bounded +diagnostic. + +**What the sender reports.** `:ok` or `{:error, reason}` from that same closed +set, never a bare `:error`. The guardian has to distinguish a resolver that +refused from one that never answered: they are different operational faults and +ADR 0029's bounded status has to say which happened. The reported reason is one +of the five atoms and never the resolved value, the reference, or a +resolver-authored string. **Failures.** Each is a refusal with a bounded non-secret reason, and each leaves no retained copy of anything the resolver may have produced: @@ -107,10 +158,11 @@ leaves no retained copy of anything the resolver may have produced: | --- | --- | | No `:credential_reference` in the configuration | Refused before the namespace is created and before any child is spawned, with the adapter's existing missing-credential reason | | Malformed reference, or a `resolver_module` that does not export the callback | The same refusal, before any child is spawned | -| Resolver answers `{:error, reason}` | The sender reports `:error`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and `reason` is reduced to the bounded non-secret status ADR 0029 fixes | -| Resolver does not answer before the invocation deadline | The same failure path, distinguished by its own stable reason; the sender is killed and its stack goes with it | -| Resolved value outside 1 to 65,536 bytes | Refused in the sender before the frame is written, exactly as the size check refuses today | -| Two resolutions in flight at once | Independent. Each invocation has its own sender and resolves for itself; the adapter serializes nothing and shares nothing between them, and two answers for the same reference may differ | +| Resolver answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | +| Resolver answers `{:error, :unavailable}`, or anything outside the closed set | The same path, reported as `:unavailable` | +| Resolver has not answered when the deadline instant is reached | The sender reports `{:error, :timeout}`, distinct from every refusal, and is killed so its stack goes with it | +| Resolved value outside 1 to 65,536 bytes | Refused in the sender before the frame is written, exactly as the size check refuses today, reported as `{:error, :oversized}` | +| Two resolutions in flight at once | Independent **successes**. Each invocation has its own sender and resolves for itself; the adapter serialises nothing and shares nothing between them, and two answers for the same reference may differ. Concurrency is not a refusal condition, and a custody process that refused concurrent callers would reintroduce exactly the serialisation this decision exists to remove | No failure is retried inside the adapter. Whether to attempt again is the coordinator's durable decision under ADR 0018, unchanged. @@ -119,12 +171,14 @@ coordinator's durable decision under ADR 0018, unchanged. - **In the sender.** The minimal credential sender keeps the shape it has today: it is spawned for this one send, it installs its own group leader - sink so no IO request can carry anything out of it, it resolves the - reference, validates the size bound, writes the frame itself and reports a - bare `:ok` or `:error` atom to the guardian. Its closure holds the - reference, never the resolved value; the value exists only in that - process's own stack for the duration of one send, so no guardian state, no - message, no exit reason and no crash report can hold it. + sink so no IO request can carry anything out of it, it calls `resolve/2`, + receives the one permitted credential-bearing reply, validates the size + bound, writes the frame itself and reports `:ok` or `{:error, reason}` from + the closed set to the guardian. Its closure holds the reference, never the + resolved value; in the parent the value exists in the custody process and, + for the duration of one send, in this process's own mailbox and stack, and + nowhere else — no guardian state, no exit reason and no crash report can + hold it. - **In the parent's environment.** The adapter performs no environment read for the credential by any route. `Loopex.LLM.ReqLLM.credential_variable/0` remains as the one name the *host* reads when it composes a runtime — the @@ -219,12 +273,20 @@ Three proofs are new: narrower scan is what lets an environment read return by a name the current expression does not match, which is the drift the case exists to catch. - **Resolution failures.** One case per row of the failure table above: absent - reference, malformed reference, a resolver module without the callback, a - refusing resolver, a resolver that does not answer before the invocation - deadline, a value outside the size bound, and two resolutions in flight at - once. Each asserts the refusal, its stable reason, that no child was spawned - where the contract says none is, and that no message, exit reason or crash - report from the invocation carries the resolver's value. + reference, malformed reference, a resolver module without the callback, each + of the four refusal atoms, a resolver returning a term outside the closed set + (reported `:unavailable`), a resolver silent past the deadline instant + (reported `:timeout`, and asserted **distinct** from every refusal so the + guardian can tell them apart), and a value outside the size bound. Each + asserts the outcome, its closed-set atom, that no child was spawned where + the contract says none is, and that no message but the permitted reply, no + exit reason and no crash report carries the resolved value. The + two-resolutions-at-once case is a **success** case, not a refusal: both + invocations complete with their own credentials. +- **The permitted reply is redacted.** A trace session at the `arguments` + level over a real invocation shows placeholders where the reply and the + resolved value would be, and no credential bytes anywhere in the captured + entries. - **Host custody.** For each reference host — the CLI, the app-server host and the daemon — composition reads the variable exactly once, deletes it, and the holding process's `format_status/1` redacts its state under a forced diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 5cfb0b712..1135a8977 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -45,17 +45,25 @@ naming a host-owned resolver, never the bytes themselves. The adapter resolves that reference exactly once per invocation, inside the minimal sender process that writes the credential frame, and only after the child has proved its nonce, codec version and build manifest digest. The adapter reads no -environment variable for the credential, and no resolved value exists anywhere -but that one process's own stack for the duration of one send. A call that -carries no reference is refused before any child is spawned, which is the -refusal a missing environment variable produces today. - -**The resolution boundary is where the adapter's claims stop.** Inside it — the -reference, the sender, the frame, the child — the adapter proves what it says: -the value is never in the child's environment, in argv, in the journal, in a -public event, a snapshot, a progress item or a diagnostic, in adapter process -state, a message, an exit reason, a crash report or an IO request, and never -written to a file. Outside it, custody belongs to the host and the adapter +environment variable for the credential. A call that carries no reference is +refused before any child is spawned, which is the refusal a missing environment +variable produces today. + +**Exactly one credential-bearing transfer exists in the parent, and this pair +names it.** A host that keeps the bytes and answers a resolver call has to send +them to the process that asked; a contract saying the value is never in a +message could never be implemented alongside one. So the rule is a permission +with a boundary: the custody process's reply to the sender is the one +transfer — bounded, unlogged, never forwarded, never retained after the frame +is written — and it is the same class of act as writing the credential frame, +protected the same way ADR 0019 already protects that sender. + +**Everywhere else the boundary is where the adapter's claims stop.** Inside it +— the reference, the sender, the frame, the child — the adapter proves what it +says: the value is never in the child's environment, in argv, in the journal, +in a public event, a snapshot, a progress item or a diagnostic, in adapter +process state, in any message but that one, in an exit reason, a crash report +or an IO request, and never written to a file. Outside it, custody belongs to the host and the adapter proves nothing about it. This pair therefore states the reference implementations' custody as their own obligation rather than claiming a property of every host that might supply a resolver. @@ -111,11 +119,14 @@ unchanged in meaning; the parent VM's environment is proved empty of the credential from the completion of composition onward — before, during and after a call; two invocations running at once are proved unable to observe each other's credential; every resolution failure the contract names — absent -reference, refusing resolver, a resolver that does not answer within the -invocation's deadline, a value outside the size bound, and two resolutions in -flight at once — is proved to refuse with a bounded non-secret reason and to -leave no retained copy; the adapter's library tree is proved to read no -environment variable for a credential by any route; and a named reviewer reads +reference, refusing resolver, a resolver that does not answer before the +deadline instant, and a value outside the size bound — is proved to refuse +with one of the five closed reason atoms and to leave no retained copy, with +the timeout proved distinguishable from every refusal; two resolutions in +flight at once are proved to be independent successes rather than a refusal; +the one permitted credential-bearing reply is proved redacted under a trace +session at the `arguments` level; the adapter's library tree is proved to read +no environment variable by any route; and a named reviewer reads the handoff — resolution point, frame ordering, failure paths, the host reference implementations' custody, and every place a value could be retained — and records the reading with the milestone. @@ -129,8 +140,11 @@ Technical depth: [Contract and evidence](0034-provider-credential-handoff-over-b ### Consequences, Compatibility and Rollback The credential plane gets the property the rest of ADR 0019's design already -has: the secret exists in the parent only inside one short-lived process that -does nothing but send it, and in the child that needs it. Two invocations in +has. In the parent the secret exists in exactly two places — the host's custody +process, which holds it and answers for it, and the short-lived sender, which +receives it once, writes it and dies — and in the child that needs it. Nowhere +else: not in adapter state, not in the environment, not in a durable or public +plane, and in no message but the one reply this pair permits. Two invocations in one VM become independent, so the twelve provider test modules can run concurrently and the fast check stops being pinned by that application. Host composition gains one explicit input and one explicit obligation: a host that diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index e464c80f0..9b16511d2 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -127,7 +127,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; the holder disconnecting and the per-session lease owner failing, each while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files 'docs/operator/**/*.md' 'docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table refuses with its stable reason and retains no copy: absent reference, malformed reference, a resolver module without the callback, a refusing resolver, a resolver silent past the invocation deadline, a value outside the size bound, and two resolutions in flight at once. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the From 4b0ac20122e735357d1114dd5c2e6dc6edf2e7de Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:30:58 -0700 Subject: [PATCH 021/585] adr(M5): delete the launcher's environment enumeration outright Second-round item 2. Relocating the snapshot to composition weakened accepted ADR 0019, whose companion constrains the trusted host only "during this operation" -- one launch. A snapshot taken once and reused would let a name introduced afterwards reach a later launch's first image, a property ADR 0019 never gave away. The enumeration is now deleted rather than moved. The launcher passes the Port a fixed, closed list: the @excluded credential and loader names, removed unconditionally, plus the explicit downstream names. It is a constant in the source, so nothing reads the environment to build it, at launch or at composition, and ADR 0019 needs no amendment. One correction to the instruction, verified rather than assumed: Port.open's {:env, ...} option MERGES into the inherited environment, it does not replace it. A probe spawned /usr/bin/env with {:env, [{~c"PATH", ...}]} and the first image still received all 67 parent names including a planted sentinel, so "the first image receives exactly that set" is not reachable through the Port option. The closed unconditional removal list is what is implementable for the same purpose, and the pair records the measurement. What that keeps is ADR 0019's stated guarantee -- credential and loader names never reach the first image, unconditionally. What it gives up is stated rather than implied: unlisted names remain in one short-lived /usr/bin/env image that acts on none of them, whose child env -i clears regardless (the M0 child-environment conformance case asserts about the worker, not that image), readable only by the user who can already read the parent VM's environment -- the case ADR 0019 explicitly declines to defend. After this decision the credential is not in the parent environment at all. The drift proof is unchanged and still expects empty lists for both provider_bridge.ex and provider_launcher.ex. --- ...andoff-over-bootstrap-channel-technical.md | 50 +++++++++++++++---- ...edential-handoff-over-bootstrap-channel.md | 21 +++++--- docs/plans/M5-technical.md | 4 +- docs/plans/M5.md | 8 +-- 4 files changed, 61 insertions(+), 22 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 7e73a0da1..7397e5fd8 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -184,15 +184,47 @@ coordinator's durable decision under ADR 0018, unchanged. remains as the one name the *host* reads when it composes a runtime — the reference CLI at start, and the real-provider lane when it names the variable in its own failure message — and the host deletes that name once it - has read it. `ProviderLauncher.spawn_environment/0`'s enumeration moves off - the call path: the removal list is computed once where the host composes the - runtime, under ADR 0019's existing rule that the trusted host introduces no - further environment names while the snapshot is in use, and is carried in - the launch configuration the adapter already builds. The unconditional - `@excluded` names and the fixed `env -i` argument lists stay as they are. - Deleting the enumeration outright was rejected: the first spawned image is - `/usr/bin/env` itself, whose environment `env -i` does not clear, so without - the removal list that image would carry the parent's whole environment. + has read it. `ProviderLauncher.spawn_environment/0`'s enumeration of the live + environment — `System.get_env/0` on every launch — is **deleted**, and + nothing replaces it: no enumeration at launch, and none at composition + either. The launcher passes the Port a fixed, closed list instead — the + `@excluded` names removed unconditionally, plus the explicit downstream + names — which is a constant in the source, so no code path reads the + environment to build it. The fixed `env -i` argument lists stay as they are. + + An earlier draft moved the snapshot to composition. That is withdrawn on + 2026-09-20, because it quietly weakened an accepted decision. ADR 0019's + companion requires that the trusted host "must not mutate unrelated launch + environment **during this operation**" — a constraint on one launch, not a + promise of immutability for the runtime's lifetime. A snapshot taken at + composition and reused would let a name introduced afterwards reach a later + launch's first image, which is a property ADR 0019 never gave away. Deleting + the enumeration rather than relocating it needs no amendment to ADR 0019. + + What the fixed list preserves exactly is ADR 0019's actual guarantee, which + its companion states as "Explicit credential removals are unconditional": no + credential name and no loader or startup-injection name reaches the first + image, whether or not it was present. What it does not preserve — stated + rather than implied — is the clearing of *unlisted* names from the + `/usr/bin/env` image's own environment block in the microseconds before it + execs. Three things bound that. `/usr/bin/env` acts on none of them; `env -i` + clears every one of them for the exec'd child, so the M0 child-environment + conformance case, which asserts about the worker and not the first image, is + untouched; and the block is readable only by the same user who can already + read the parent VM's own environment, which is the case ADR 0019 explicitly + declines to defend — "This is not a new guarantee against hostile same-VM + code". After this decision the credential is not in the parent's environment + at all, so the enumeration's protective value against the credential is zero + by then. + + One mechanical note for whoever writes the change, measured rather than + assumed: `Port.open`'s `{:env, …}` option **merges** into the inherited + environment; it does not replace it. A probe on this toolchain spawned + `/usr/bin/env` with `{:env, [{~c"PATH", …}]}` and the first image still + received all 67 of the parent's names, including a planted sentinel. So + "pass an exact environment and receive exactly that set" is not reachable + through the Port option, and the closed unconditional removal list above is + what is actually implementable for the same purpose. - **In the child.** Unchanged: the child receives the credential on the socket and nowhere else. Its environment at entry is the fixed `PATH`, `LANG`, `LC_ALL` and the two crash-dump suppressions, and ADR 0029's bounded diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 1135a8977..02806e8b7 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -79,13 +79,20 @@ Outcome 6's claim is stated at that boundary: a claim that the variable is never set at all would contradict the way an operator supplies a secret to a process they start. -One enumeration leaves the call path with it. The launcher's first spawned -image is `/usr/bin/env`, whose own environment the port can only clear name by -name, so the launcher enumerates the parent's environment on every launch -today. That snapshot moves to composition, under the same ADR 0019 constraint -that already forbids the host to introduce environment names while it is in -use, and is carried in the launch configuration the adapter already builds. No -per-invocation path then reads the environment for any purpose at all. +One enumeration goes with it. The launcher reads the whole parent environment +on every launch, to clear it name by name from the first spawned image. That +read is deleted outright rather than relocated: the launcher passes a fixed, +closed removal list — the credential and loader names it already removes +unconditionally — so no code path reads the environment to build it, at launch +or anywhere else. Moving the read to composition was considered and withdrawn, +because ADR 0019 constrains the host only *during one launch* and a snapshot +reused across launches would claim an immutability that decision never gave. +What the fixed list keeps is ADR 0019's actual guarantee, that credential and +loader names never reach the first image; what it gives up, and this pair says +so, is clearing unlisted names from one short-lived `/usr/bin/env` image that +acts on none of them, whose child is cleared by `env -i` regardless, and whose +environment block is readable only by the user who can already read the parent +VM's. **Alternatives rejected.** Keeping the environment variable and buying the speed by sharding the provider suite across test VMs was rejected: it is diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 9b16511d2..09de5dbd5 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -20,7 +20,7 @@ decision named only in prose declares nothing. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or the core attachment change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by a `{resolver_module, reference_term}` reference the host owns, resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; the resolver's owner, custody, rotation, deadline bounding and every failure outcome; no environment read in the adapter's call path and the launcher's enumeration moved to composition; the re-pointed credential-plane proofs and the security review as acceptance points | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by a `{resolver_module, reference_term}` reference the host owns, resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; the resolver's owner, custody, rotation, deadline bounding and every failure outcome; no environment read anywhere in the adapter's library tree and the launcher's enumeration deleted rather than relocated, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | ADR 0031 decides one thing, the `0.2.0` local-adapter selection and its documented limits. It prescribes no successor engine, experiment or migration; @@ -43,7 +43,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session residency between active and dormant, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | -| `loopex_llm_reqllm` | The credential handoff, its sender, the resolver behaviour it declares, the launch configuration that carries the composition-time environment snapshot, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | +| `loopex_llm_reqllm` | The credential handoff, its sender, the resolver behaviour it declares, the launcher's fixed closed removal list that replaces its environment enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | **Rejoin order.** Prerequisite decisions first. Then the new application with diff --git a/docs/plans/M5.md b/docs/plans/M5.md index ff4f1fae3..407d9c54c 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -52,7 +52,7 @@ loop. | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end and daemon-internal functions observed through a daemon-scoped trace session rather than new events; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's environment enumeration has left the per-invocation call path. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's read of the whole parent environment is deleted outright, replaced by a fixed closed removal list, so no code path reads the environment to build one. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -272,7 +272,7 @@ implementation that depends on it, not before unrelated work. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence and the operator root-retirement procedure documented; a daemon-grade adapter and any migration are left open for a separate decision and prescribed nowhere | 1, 5 | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by a host-owned reference and resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the reference's shape, the resolver's owner, custody, rotation, bounding and every failure are exact; the adapter reads no environment variable for it and its enumeration leaves the call path | 6 | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by a host-owned reference and resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the reference's shape, the resolver's owner, custody, rotation, bounding and every failure are exact; the adapter reads no environment variable for it and the launcher's enumeration of the parent environment is deleted rather than relocated | 6 | Three accepted decisions remain load-bearing and are not reopened: M4's ADR 0023 fixes the protocol M5's generation 2 extends, M4's ADR 0030 fixes the @@ -410,8 +410,8 @@ lease — and the companion's rejoin order says where each part goes. 5. **The credential handoff and the provider dependency.** ADR 0034's change to the provider adapter and to the host composition sites that read the operator's variable, the re-pointed credential-plane proofs, the new proofs - of the resolver contract and its failures, the launcher's enumeration - moving to composition, its own security review by someone other than its + of the resolver contract and its failures, the deletion of the launcher's + environment enumeration, its own security review by someone other than its implementer, and the measured effect on the provider suite once its modules can run concurrently. This workstream also carries one bounded dependency item: `req_llm` moves from `~> 1.17.1` to `~> 1.24` in From 966c49db4ab43881729dc8e043171c05cf9bc403 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:33:01 -0700 Subject: [PATCH 022/585] adr(M5): keep coordinators resident and make the crash cut recoverable Second-round items 3 and 4. Item 3: dormancy as drafted could have stopped work that was still running. Its idle condition -- no attachment, no admitted command -- is not the question of whether work is in flight: a detached session may still have a model request, a tool effect, an interaction, a recovery, an unresolved commit_unknown or an admission executing inside core. And no deactivation operation exists to stop one with: core owns coordinator lifetime and M5's only core change is concurrent attachment. Dormancy now applies to attachments, resident windows and output buffers only; an activated session keeps its coordinator for the daemon's lifetime. The ceiling becomes 64 sessions activated per daemon lifetime, the 65th refusing with the restart remedy, recorded as a limitation rather than dressed as a design. New witnesses: a detached long-running command and a pending admission each cross the idle deadline and run to completion. Item 4: the index ceiling could have made a session unreachable, and the plan never said how an unrecorded session's durable existence is validated. Four parts now: durable existence is learned only from core, by calling attach or resume on the ID and forwarding core's answer, with no Store read; a client that never received the ID recovers through the create command's durable command_id, which returns the historical result rather than creating a second session; a directory write that fails at activation is reported to that client, leaves the session usable, and is retried next time; and at a full index a session reached by ID is activated but not recorded, with the listing carrying index_full so an operator is told it is incomplete. The ceiling is on recorded entries and never on reachability. Also: `residency` is set once and never back, and `controlled` on lease-owner failure is reconstructed by the daemon restart ADR 0033 requires rather than repaired in place. --- ...tachment-residency-and-replay-technical.md | 128 ++++++++++++++---- ...-daemon-attachment-residency-and-replay.md | 28 ++-- docs/plans/M5-technical.md | 10 +- docs/plans/M5.md | 49 +++++-- 4 files changed, 164 insertions(+), 51 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index bbea7b4fb..1b1bc086d 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -128,7 +128,7 @@ enforced inside core. | Method | Required fields | Result | | --- | --- | --- | -| `session.list` | `limit` (1 to 256), optional `after_session_id` | A page of at most `limit` index entries ordered by session ID bytes ascending and starting strictly after `after_session_id`; each entry carries the session identity, the placement identity recorded for it, `residency` of `active` or `dormant`, and `controlled` as a boolean, never content and never durable session state; `next_after_session_id` is present exactly when more entries exist | +| `session.list` | `limit` (1 to 256), optional `after_session_id` | A page of at most `limit` index entries ordered by session ID bytes ascending and starting strictly after `after_session_id`; each entry carries the session identity, the placement identity recorded for it, `residency` of `active` or `dormant`, and `controlled` as a boolean, never content and never durable session state; `next_after_session_id` is present exactly when more entries exist, and `index_full` is present and true exactly when the index is at its 4,096-entry ceiling, so a client is told the listing may be incomplete rather than reading an omission as an absence | | `daemon.status` | none | Placement identity, daemon incarnation, socket path, attachment, active-session and index counts against their limits, uptime | | `session.acquire_control`, `session.release_control` | `session_id`, `request_id` and the lease fields ADR 0033 fixes | Lease result naming the writer epoch and the remaining lease term | @@ -149,10 +149,18 @@ the daemon itself owns or reads once: - `session_id` and the recorded placement identity, read from the directory entry at daemon start, or written when the daemon first activates a session the directory does not hold; -- `residency`, a daemon fact, updated on every activation and every transition - to dormant; +- `residency`, a daemon fact, set to `active` at activation and never set back + within a daemon's lifetime, because activation is one-way; - `controlled`, a daemon fact, updated on every lease grant, release and - expiry by the same per-session owner ADR 0033 gives those transitions. + expiry by the same per-session owner ADR 0033 gives those transitions — + **and on that owner's failure**, which is not a transition the owner can + record for itself. Under ADR 0033 a lease owner's failure is fatal to the + daemon instance, so both fields are reconstructed by the restart rather than + repaired in place: after it, every session is `dormant` and `controlled` is + false, which is exactly true of a daemon that has activated nothing and + granted nothing. A coordinator that fails is core's to supervise; the daemon + does not invent a `residency` value for it, and a client learns of it by + attaching, where core answers authoritatively. Lineage, lifecycle state and last committed sequence are deliberately absent. A daemon index cannot keep them current without reading the Store on the @@ -160,14 +168,42 @@ request path or subscribing to every session it is not holding, and a field that is silently stale is worse than an absent one; a client that needs them attaches, and the snapshot carries them at a committed sequence. -The recovery procedure for the crash cut is explicit and needs no new durable -record. A session absent from the index is still reachable by its ID: a client -that knows the ID acquires control and resumes it, the Store answers because -the Store is the authority, and the daemon records the directory entry as part -of that activation, so the session appears in every later listing. The -operator documentation states this, because an operator who lost a terminal -mid-creation is exactly who meets it. `session.list` is documented as *the -sessions this root records*, not *the sessions this root contains*. +**The recovery procedure for the crash cut**, in four parts, needing no new +durable record and no Store read by the daemon: + +1. **Durable existence is learned only from core.** The daemon never reads + Store internals and never enumerates the log to decide whether a session + exists. It calls core's existing attach or resume on the ID and treats + core's answer as the proof: core resolves it or refuses it, and the daemon + forwards that answer. So `session.acquire_control` on an ID the index does + not hold validates durable existence the only way the daemon is allowed + to — by asking core — and a refusal from core is the refusal the client + sees. Nothing about the index is consulted to decide existence, which is + why an index that is incomplete is not a correctness problem. +2. **A client that never saw the session ID recovers by command identity.** + At the cut where the Store committed the creation and the process died + before the reply, the client may hold no ID at all. It is not lost: the + create command's `command_id` is durable and re-presenting it returns the + historical result rather than creating a second session — the idempotency + the session directory and the resume path already rely on. That is the + named route, and the operator page states it. +3. **Recording can fail, and says so.** If writing the directory entry fails + during activation, the failure is reported to the client that triggered it, + as an explicit warning that this session will not appear in `session.list` + — the reference CLI already reports exactly that failure today. The + activation itself succeeds, the session is fully usable, and the daemon + retries the record on the next activation of that session. +4. **A full index still activates.** If the index already holds 4,096 entries + and a client reaches an unrecorded session by ID, the session is activated + and is **not** recorded. Reachability never depends on the ceiling. What + changes is the listing's honesty: `session.list` then carries `index_full`, + so an operator is told the listing is incomplete rather than reading a + silent omission as an absence. + +`session.list` is documented as *the sessions this root records*, not *the +sessions this root contains*, and the operator documentation states all four +parts, because an operator who lost a terminal mid-creation is exactly who +meets them. A page is consistent with the index at the moment it is read; no consistency is promised across pages, so a session created or dropped between pages may @@ -180,24 +216,48 @@ byte position. ### Session residency: active, dormant, and their bounds A session is **active** when the daemon holds a live coordinator for it and -**dormant** when the index records it and the daemon does not. Nothing durable -distinguishes the two; dormancy is a daemon fact and costs a dormant session -nothing. - +**dormant** when the index records it and the daemon has never activated it in +this process's lifetime. Nothing durable distinguishes the two; dormancy is a +daemon fact and costs a dormant session nothing. + +**Activation is one-way for the daemon's lifetime.** A session the daemon has +activated keeps its coordinator until the daemon exits. Dormancy is *not* +deactivation, and the daemon has no operation that stops a coordinator. + +That is a correction, not a simplification. An earlier draft let an idle +session "go dormant, releasing its slot", which is wrong twice over. The idle +condition it named — no attachment and no admitted command — is not the same +question as whether work is running: a session with every client detached can +still have a model request in flight, a tool effect dispatched, an interaction +awaiting an answer, a recovery in progress, an unresolved `commit_unknown`, or +an admission executing inside core. Stopping it would destroy exactly what +Outcome 1 exists to prove, that work progresses with zero attachments. And +there is no operation to stop one with: core owns coordinator lifetime, and +M5's only core change is concurrent attachment, so a deactivation call would +be a second core change this milestone does not make. + +- **What dormancy applies to.** Attachments, resident windows and socket + output buffers, and nothing else. An idle attachment is evicted, its window + may be reclaimed, its buffer is released — and the coordinator beneath them + keeps running. Every byte ceiling in this decision is about those three and + is unaffected. - **Lazy recovery.** A restarted daemon activates no session. It acquires the writer marker, reads the index, binds the socket, and activates a session the first time a client attaches to, acquires control of or resumes it. -- **Active-session ceiling.** At most 64 sessions are active at once per - daemon. A session that has had no attachment and no admitted command for the - idle interval goes dormant, releasing its slot. An activation that would - exceed the ceiling while every active session is still in use refuses with a - stable reason naming the ceiling; it never evicts a session that a client is - driving or watching. -- **Index bound.** The index holds at most 4,096 entries. A root whose session - directory holds more refuses at daemon start with a stable reason naming the - bound and pointing at root retirement, in the same posture as - `store_log_too_large`: refuse rather than serve a truncated view of what the - root records. +- **Activation ceiling.** At most 64 sessions are activated **per daemon + lifetime**, not at once, because nothing gives a slot back. The 65th + activation refuses with a stable reason naming the ceiling and the remedy, + which is to restart the daemon. That is a real limitation rather than a + design, it is recorded as one in the plan and in the operator page, and it + is the honest cost of leaving coordinator lifetime alone in M5. Lifting it + needs a core deactivation operation that can tell "quiescent" from "idle", + which is a decision of its own. +- **Index bound.** The index holds at most 4,096 **recorded** entries. A root + whose session directory holds more refuses at daemon start with a stable + reason naming the bound and pointing at root retirement, in the same posture + as `store_log_too_large`: refuse rather than serve a truncated view of what + the root records. The ceiling is on recorded entries only, and it never + makes a session unreachable — see the crash cut below. - **Homogeneity.** One state root is one host composition for the daemon's process lifetime. The daemon is composed once, with one workspace, policy, provider configuration and set of project resources, and serves every @@ -319,9 +379,17 @@ fields above; a session committed to the Store whose directory entry was never written — injected at exactly that cut — absent from the listing, still reachable by ID, and present in every listing after the activation that records it; a restarted daemon activating nothing until a client reaches for a -session; the active-session ceiling refusing an activation while every slot is -in use, and admitting one after a session goes dormant; a root whose directory -holds more than the index bound refusing at start with its stable reason; a +session; a detached long-running command and a pending admission each crossing +the idle deadline with every client gone and running to completion, so +dormancy is proved to release attachments and never a coordinator; the +activation ceiling refusing the 65th activation of a daemon lifetime with its +stable reason and restart remedy; a root whose directory holds more than the +recorded-entry bound refusing at start with its stable reason; at that bound a +session reached by ID activated, not recorded, and the listing carrying +`index_full`; a client that never saw a session ID recovering it through the +create command's durable `command_id`; a directory write failing at activation +reported to that client, the session still usable, and the record retried at +the next activation; a recorded session the current composition cannot serve refused at activation by name while every other session in the root activates; progress coalescing under pressure with counted drops and no journal delay; peer-credential refusal; a diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 53dc82af8..f6f9669e1 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -38,8 +38,10 @@ control methods and the writer-epoch field ADR 0033 names. It adds no durable method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core has no durable stop command, and M5's only core change is concurrent -attachment. Ending work is releasing control and disconnecting, after which -the session goes dormant and `session.resume` brings it back. +attachment. Ending a client's involvement is releasing control and +disconnecting; the session itself keeps running, which is the point of a +daemon, and another client reaches it again by acquiring control and +attaching. A client that offers only generation 1 is refused at initialize under ADR 0023's existing no-common-generation rule and nothing durable is @@ -86,11 +88,20 @@ missing durable event. Transient progress is coalesced or dropped first and never delays a journal transaction. A session is *active* when the daemon holds a live coordinator for it and -*dormant* when the root records it and the daemon does not. Recovery is lazy: -a restarted daemon activates nothing, reads its index, and activates a session -when a client reaches for it. That is what a daemon can honestly promise on a -store whose session directory is not Store truth and whose every open replays -a full log. `session.list` returns bounded pages, with an exact continuation +*dormant* when the root records it and the daemon has not activated it in this +process's lifetime. Recovery is lazy: a restarted daemon activates nothing, +reads its index, and activates a session when a client reaches for it. +Activation is one-way: dormancy applies to attachments, resident windows and +output buffers, never to a coordinator, because a session with no attachment +may still have a model request, a tool effect, an interaction, a recovery, an +unresolved `commit_unknown` or an executing admission in flight, and because +stopping one would need a core deactivation operation M5 does not add. The +cost is stated rather than hidden: at most 64 sessions are activated per +daemon lifetime, the 65th refuses, and the remedy is to restart the daemon. + +Lazy recovery is what a daemon can honestly promise on a store whose session +directory is not Store truth and whose every open replays a full log. +`session.list` returns bounded pages, with an exact continuation cursor, over a daemon-owned index of what the root *records* — identity, recorded placement identity, active or dormant, controlled or not — and never over what the Store contains, because no index built from the session @@ -102,7 +113,8 @@ limits are exact and are bound at acceptance: 64 attachments per session, resident window per session, 4 MiB of encoded output buffered per connection, 16 MiB of encoded resident-window events per session, 512 MiB of aggregate retained encoded events per daemon, ten minutes of idle time -before eviction, 64 active sessions per daemon, 4,096 index entries per root, +before eviction, 64 sessions activated per daemon lifetime, 4,096 recorded +index entries per root, 256 sessions per list page, and the ADR 0023 frame ceiling unchanged. Count and byte ceilings apply together; an event that would exceed either triggers the stated detachment, eviction or refusal behavior diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 09de5dbd5..fe60db3fc 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -40,7 +40,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | -| `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index and its bounded pages, session residency between active and dormant, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | +| `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | | `loopex_llm_reqllm` | The credential handoff, its sender, the resolver behaviour it declares, the launcher's fixed closed removal list that replaces its environment enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | @@ -122,7 +122,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. The active-session ceiling refuses an activation while every slot is in use and admits one after a session goes dormant; a root whose directory exceeds the index bound refuses at start; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID and, by a client that never saw the ID, through the create command's durable `command_id` returning the historical result rather than a second session; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: a permissive directory or socket mode, a parent the daemon does not own, and a path component it did not create each refused at start, and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; the holder disconnecting and the per-session lease owner failing, each while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -404,9 +404,9 @@ decision named above; M5 introduces none of its own. | Daemon socket output buffer per connection | 4 MiB encoded | ADR 0032 | | Resident window per session | 4,096 events and 16 MiB encoded | ADR 0032 | | Aggregate retained encoded events per daemon | 512 MiB | ADR 0032 | -| Idle time before eviction, and before an unused session goes dormant | 10 minutes | ADR 0032 | -| Active sessions per daemon | 64; a further activation refused while every slot is in use | ADR 0032 | -| Session index entries per root | 4,096; a root whose directory holds more refused at daemon start | ADR 0032 | +| Idle time before an attachment is evicted and its window and buffer released | 10 minutes; it never stops a coordinator | ADR 0032 | +| Sessions activated per daemon lifetime | 64; the 65th activation refused, the remedy being to restart the daemon. It is per lifetime rather than concurrent because nothing deactivates a coordinator, which is recorded as a limitation | ADR 0032 | +| Recorded session index entries per root | 4,096; a root whose directory holds more refused at daemon start. The ceiling is on recorded entries and never on reachability: a session reached by ID beyond it is activated and not recorded, and the listing carries `index_full` | ADR 0032 | | `session.list` page | at most 256 entries, `limit` in 1 to 256 | ADR 0032 | | Socket path bound | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 407d9c54c..dd71d7cd8 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -47,7 +47,7 @@ loop. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root: an active session runs while no client is attached, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root: an activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID and by its create `command_id`, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -75,9 +75,27 @@ serves generation `loopex.experimental/2` only, which adds `session.list`, the one-attachment-per-process rule to residency limits. It adds no durable method: core owns durable session truth and its only M5 change is concurrent attachment, so a daemon method that ended a session durably would have to add -a durable command to core, which M5 does not do. Ending work is releasing -control and disconnecting; the daemon then lets the session go dormant, and -`session.resume` brings it back. +a durable command to core, which M5 does not do. Ending a client's involvement +is releasing control and disconnecting; the session itself keeps running, +which is the point of a daemon, and another client reaches it again by +acquiring control and attaching. + +Dormancy is about attachments, never about a coordinator. A session the daemon +has activated keeps its coordinator until the daemon exits: idle eviction +releases an attachment, its resident window and its output buffer, and the +work beneath them continues. It has to be that way for two reasons. A session +with every client detached may still have a model request in flight, a tool +effect dispatched, an interaction awaiting an answer, a recovery running, an +unresolved `commit_unknown` or an admission executing inside core, so "idle" +is not "quiescent" and stopping on idleness would destroy exactly what +Outcome 1 exists to prove. And there is nothing to stop it with: core owns +coordinator lifetime and M5's only core change is concurrent attachment. + +The cost is a real limitation and is recorded as one rather than hidden: at +most 64 sessions are activated per daemon lifetime, the 65th activation +refuses with a stable reason, and the operator's remedy is to restart the +daemon. Lifting it needs a core operation that can tell quiescent from idle, +which is its own decision and not M5's. `session.list` is a daemon convenience, not an enumeration of durable truth. It answers from a daemon-owned index built at start from the state root's @@ -90,10 +108,25 @@ it active, and whether a controller lease is currently held — and no more. Lineage, lifecycle state and committed sequence are not in a list entry, because a daemon index cannot keep them current without reading the Store on the request path; a client that needs them attaches, and the snapshot carries -them authoritatively. A session missing from the list is never a lost session: -it is reached by its ID, and the daemon records the entry when it activates -one the directory does not hold. A -client offering only generation 1 is refused at initialize; generation-1 +them authoritatively. + +A session missing from the list is never a lost session, and the plan says +exactly how it is recovered. The daemon learns durable existence only from +core: it calls core's attach or resume on the ID and forwards core's answer, +reading no Store internals, so an incomplete index is never a correctness +problem. A client that never received the session ID — the cut where the +Store committed and the process died before the reply — recovers through the +create command's durable `command_id`, which returns the historical result +instead of creating a second session. If recording the directory entry fails +during activation, that failure is reported to the client, the session is +fully usable anyway, and the record is retried at the next activation. And if +the index is already at its 4,096-entry ceiling, a session reached by ID is +still activated, simply not recorded, with `session.list` carrying +`index_full` so an operator is told the listing is incomplete rather than +reading an omission as an absence. The ceiling is on recorded entries; it is +never on reachability. + +A client offering only generation 1 is refused at initialize; generation-1 clients keep the M4 foreground server, whose wire and behavior do not change. Attach is the runtime's race-free cursor transaction, and delivery is contiguous and at least once: gaps are forbidden, duplicates are permitted, From b93cfb8fcebfe26e798ee63101f6a6db50e97324 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:33:44 -0700 Subject: [PATCH 023/585] adr(0033): make a lease owner's failure fatal to the daemon instance Second-round item 5. The lease owner holds the session's in-flight admission set, and the expiry rule grants a takeover only when that set is empty. The pair then had the daemon restart a failed owner beneath live sockets, which loses the set silently: a successor acquire could be granted while a forgotten admission was still able to settle. The session-owner tree is now supervised one_for_all up to the listener. An owner's failure closes the listener and every connection, the daemon exits and restarts holding no lease, no connection and no activated session, so no successor acquire exists to be granted wrongly. Core fences the forgotten admission by epoch regardless, since a fresh epoch is minted at the next grant, so this is defence in depth over a fence that already holds. The rejected option is recorded: retaining the in-flight set in a survivor moves the same window one process up, because whichever process holds it is then the process whose failure loses it -- and a set that cannot be lost is a durable set, which is the durable lease record this decision already rejects. The cost is stated plainly: one supervision fault takes the daemon down and every client reconnects. Every witness and consequence that assumed a survivable owner restart is re-pointed in the pair and in both plan files. --- ...controller-lease-and-takeover-technical.md | 54 ++++++++++++++----- ...aboration-controller-lease-and-takeover.md | 14 +++-- docs/plans/M5-technical.md | 2 +- docs/plans/M5.md | 12 +++-- 4 files changed, 60 insertions(+), 22 deletions(-) diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index ae2efb0db..b7bb6bf5e 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -20,9 +20,9 @@ deadline (monotonic), state ∈ {held, released, expired} `writer_epoch` is an opaque string from ADR 0023's identifier alphabet, at most 64 bytes, carrying at least 128 bits of fresh randomness. It is minted -at every grant and never reused: not across grants to the same connection, -not across a restart of the per-session lease owner process, and not across -a restart of the daemon. Clients treat the epoch as opaque and compare it +at every grant and never reused: not across grants to the same connection and +not across a restart of the daemon, which is the only restart that exists +because a lease owner's failure takes the daemon with it. Clients treat the epoch as opaque and compare it only for equality. The daemon incarnation is a fresh opaque identifier generated at each daemon start and reported by `daemon.status` as a diagnostic; it confers nothing and is not part of the epoch. It is a daemon @@ -33,11 +33,37 @@ One owner process per session serializes every lease read, grant, renewal, release and expiry transition with that session's mutation-admission handoff, so a takeover cannot pass a mutation whose holder check has already started but whose core admission is unresolved; that admission first resolves or -remains fenced. If that owner process crashes and is restarted by the daemon -while the daemon and its client sockets survive, the restarted owner holds no -lease: the session is uncontrolled, the previous holder's epoch can never be -minted again, and its delayed commands refuse on both the holder and the -epoch check until it acquires again and receives a new epoch. Expiry and +remains fenced. + +**A lease owner's failure is fatal to that daemon instance, deliberately.** +The owner holds the session's in-flight admission set in its own memory, and +that set is the whole basis of the expiry rule below: a takeover is granted +only when it is empty. An owner that dies takes the set with it, so a +restarted owner cannot know whether an admission is still on its way into +core. An earlier draft had the daemon restart the owner and carry on with its +sockets intact; that is withdrawn on 2026-09-20, because a successor acquire +could then be granted while a forgotten admission was still able to settle. + +So the session-owner tree is supervised `one_for_all` up to the listener: an +owner's failure closes the listener and every connection, the daemon exits, +and the daemon restarts with no lease anywhere, no connection, and no +session activated. No successor acquire exists to be granted wrongly, because +no connection survives to make one. Core fences the forgotten admission by +epoch regardless of any of this — a fresh epoch is minted at the next grant +and nothing from before can match — so the daemon-side rule is defence in +depth over a fence that already holds, not the only thing standing between a +crash and interleaving. + +Retaining the in-flight set in a survivor was the alternative and was +rejected: whichever process held it would then be the process whose failure +loses it, so the window moves up one level rather than closing, and a daemon +that cannot lose the set is a daemon that has made the set durable — a durable +lease record by another name, which this decision rejects for its own reasons. +The cost is real and is stated: one supervision fault takes the daemon down +and every client reconnects. That is the honest price of not inventing a +recovery for state whose whole purpose is to be exact. + +Expiry and admission use the daemon's monotonic clock: a deadline is set only by a successful grant or renewal, and a wall-clock jump cannot shorten or extend a live holder's authority. Nothing about a lease is persisted or recovered. @@ -163,11 +189,13 @@ stable reason when its own deadline elapses first, the holder's connection disconnecting while its mutation is in flight, and the per-session lease owner failing while a mutation is in flight — in every case exactly one of settle or refuse, never both, and no epoch reused; takeover only after release or expiry -with a fresh epoch minted before the successor's first command; a controller killed mid-run fenced -after takeover, its late commands refused; the per-session lease owner -process crashing and restarting while the daemon and client sockets survive, -after which the previous holder's delayed command is refused, no epoch is -ever reused, and a new acquire carries a new epoch; an abort from the new +with a fresh epoch minted before the successor's first command; a controller +killed mid-run fenced after takeover, its late commands refused; a +per-session lease owner killed while a mutation is in flight taking the +listener, every connection and the daemon down with it, after which the +restarted daemon holds no lease, has activated nothing, and the previous +holder's delayed command is refused on both the holder and the epoch check; +an abort from the new controller cancelling work dispatched under the old controller's command with a truthful cleanup outcome; an observer never acquiring authority through content, metadata, answers or order; after a daemon restart every diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index bfe3aeb82..f5e6d8412 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -87,16 +87,22 @@ restart every connection is gone with its socket and admission already requires the holder connection, so durability could only preserve a counter nothing needs. A counter-based epoch scoped to the daemon incarnation was rejected on 2026-09-14 because a lease-owner restart under the same -incarnation would mint values already issued. +incarnation would mint values already issued. Restarting a failed lease owner +beneath live sockets was rejected on 2026-09-20: the owner holds the session's +in-flight admission set, a takeover waits on that set being empty, and a +restarted owner cannot know what it has forgotten. Retaining the set in a +survivor moves the same window one process up; making it survivable at all +would mean making it durable, which is the durable lease record this decision +already rejects. **Evidence its acceptance requires.** This is a trust claim, so its class is negative tests on real processes plus a security reading of the admission path: every refusal — stale epoch, copied current epoch, non-holder connection, released lease, expired lease, observer abort — proved before core admission and before any session write, a controller killed mid-run fenced -after takeover, a lease-owner process restarted while the daemon and its -sockets survive, and a daemon restart leaving every session uncontrolled with -every earlier epoch refused. No durable record changes, so no migration or +after takeover, a lease owner killed while a mutation is in flight taking the +daemon down rather than being restarted beneath live sockets, and a daemon +restart leaving every session uncontrolled with every earlier epoch refused. No durable record changes, so no migration or rollback evidence is owed. Technical depth: [Contract and evidence](0033-collaboration-controller-lease-and-takeover-technical.md#technical-adr-0033-decision). diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index fe60db3fc..9d50a3bd0 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -124,7 +124,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID and, by a client that never saw the ID, through the create command's durable `command_id` returning the historical result rather than a second session; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: a permissive directory or socket mode, a parent the daemon does not own, and a path component it did not create each refused at start, and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The per-session lease owner crashing and restarting while the daemon and the client sockets survive, with the previous holder's delayed command refused and no epoch ever reused. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; the holder disconnecting and the per-session lease owner failing, each while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files 'docs/operator/**/*.md' 'docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index dd71d7cd8..170b28ef0 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -49,7 +49,7 @@ loop. | --- | --- | --- | --- | | 1 | A daemon owns session lifetime for a state root: an activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID and by its create `command_id`, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | -| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a crashed lease owner never reuses an epoch, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | +| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end and daemon-internal functions observed through a daemon-scoped trace session rather than new events; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's read of the whole parent environment is deleted outright, replaced by a fixed closed removal list, so no code path reads the environment to build one. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | @@ -149,9 +149,13 @@ Takeover is explicit, becomes eligible only after release or expiry, waits for any mutation already in flight under the outgoing lease to resolve, and mints a fresh epoch before the successor's first command. The lease lives in the daemon's memory for the daemon process's lifetime, never in the session journal or any durable -record; every writer epoch is minted fresh and never reused, so a restart of -the daemon or of a session's lease owner leaves that session uncontrolled with -every earlier epoch stale, and the core keeps mandating no lease. Cancellation +record; every writer epoch is minted fresh and never reused, so a daemon +restart leaves every session uncontrolled with every earlier epoch stale, and +the core keeps mandating no lease. A lease owner's failure is fatal to the +daemon instance rather than survivable: it holds the session's in-flight +admission set, which is what a takeover waits on, so losing it silently could +let a successor be granted while a forgotten admission could still settle. +Every connection closes and the daemon restarts. Cancellation crosses processes because the core owns dispatch: the current controller's `session.abort` cancels work an earlier controller started, with the truthful two-phase outcome the core already commits. From 38cbaf392d0dfeec2d8cf5d638883d89605517ee Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:34:46 -0700 Subject: [PATCH 024/585] plan(M5): fix the trace witness, socket permissions and the gate glob Second-round items 6, 8 and 9. Item 6: the daemon-internal trace witness exceeded ADR 0030's process scope. Its companion says a Loopex.Trace session "traces only processes the runtime owns", and the observability companion adds that processes are flagged from the runtime's supervisor with set_on_spawn so "a process the runtime does not own never is". The daemon's listener, connections and lease owners are host processes above the runtime, so the witness was unreachable without widening ADR 0030. It is removed: daemon internals are proved by the daemon's own tests and logs, and the observability claim is now exactly that daemon workflows drive the existing core spans end to end. Item 8: the socket permission rule rejected ordinary M4 roots. LoopexAppServer .Host creates the state root with File.mkdir_p/1 and no mode at host.ex:147, so under the ordinary umask of 022 an existing root is 0755 -- probed, not assumed. Requiring the root itself to be 0700 would have refused every root the foreground server and CLI have written since M4, contradicting the claim that moving a root between daemon and foreground is stopping one and starting the other. The socket now lives in /daemon/, created 0700 by the daemon, with the socket 0600; the root's mode is read and never changed, and the permission proof reads back the subdirectory and socket rather than the root. Item 9: the gate's derivation returned nothing. Verified at this SHA: git ls-files 'docs/operator/**/*.md' 'docs/developer/**/*.md' returns 0 paths, while git ls-files -- ':(glob)...' returns 26 -- 18 developer, 8 operator. The plan now uses the pathspec glob magic, says why it is load-bearing, and requires the closure checklist to state its derived count so an empty derivation cannot pass vacuously. --- ...tachment-residency-and-replay-technical.md | 31 ++++++++++---- ...-daemon-attachment-residency-and-replay.md | 14 ++++--- docs/plans/M5-technical.md | 12 ++++-- docs/plans/M5.md | 42 ++++++++++++------- 4 files changed, 68 insertions(+), 31 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 1b1bc086d..fa4935e39 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -10,8 +10,22 @@ Concept: [Context and decision](0032-daemon-attachment-residency-and-replay.md#c ### Transport -The daemon listens on one Unix-domain socket. Its path is -`/daemon.sock` by default and may be set explicitly. +The daemon listens on one Unix-domain socket, and where it puts it matters. +Its path is `/daemon/daemon.sock` by default, inside a +daemon-owned subdirectory the daemon creates mode `0700`, and it may be set +explicitly to another path under the same rule. + +It is a subdirectory rather than the state root itself because the root is not +the daemon's to re-permission. `LoopexAppServer.Host` creates it with +`File.mkdir_p/1` and no mode, so under the ordinary umask of 022 an existing +M4 root is `0755` — measured, not assumed. Requiring the *root* to be `0700` +would have made the daemon refuse every root the foreground server and the CLI +have been writing since M4, which contradicts this milestone's central +compatibility claim that moving a root between the daemon and the foreground +surfaces is stopping one and starting the other. Tightening the root instead +would be an unannounced permission change to an operator's existing directory. +The daemon therefore owns one subdirectory and leaves the root's mode exactly +as it found it. **The path bound is derived, not assumed.** `sun_path` is 104 bytes on Darwin and 108 on Linux *including* the NUL terminator, so the usable path is one @@ -25,12 +39,13 @@ truncated. The tests bind at the bound and at one byte past it on every platform the release check runs. **Peer authorization has two layers, and the load-bearing one is the -filesystem.** The socket lives in a directory the daemon owns with mode -`0700`, and the socket itself is created mode `0600`; both are verified after -bind by reading back their owner and mode and comparing them with the daemon's -own effective user, and the daemon refuses to serve if either is wrong, if the -parent is not owned by that user, or if any component of the path is a -symbolic link it did not create. That is what actually keeps another user out: +filesystem.** The socket lives in that `0700` daemon-owned subdirectory and is +itself created mode `0600`. Both are verified after bind by reading back their +owner and mode and comparing them with the daemon's own effective user, and +the daemon refuses to serve if either is wrong, if the subdirectory is not +owned by that user, or if any component of the path below the state root is a +symbolic link it did not create. The state root above it is read, never +re-permissioned and never required to be `0700`. That is what actually keeps another user out: connecting to a Unix-domain socket requires write permission on the socket and traversal of its directory, so a foreign peer never reaches `accept`. It is the same arrangement ADR 0019 already uses for the provider child's private diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index f6f9669e1..05a1b2cd4 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -51,15 +51,19 @@ distinct attachments to the same session coexist without replacing one another; the core continues to own their independent cursor barriers and event-count queues, while the daemon owns per-connection socket output buffers, the resident window and the residency ceilings. The socket path is -the state root's `daemon.sock` unless the operator names another, and a path -beyond the platform bound is refused at start rather than truncated. A daemon +`daemon.sock` inside a `0700` daemon-owned subdirectory of the state root +unless the operator names another, and a path beyond the platform bound is +refused at start rather than truncated. The subdirectory exists so the daemon +never has to re-permission or reject an operator's existing root, which the +foreground server creates `0755` under the ordinary umask. A daemon acquires the root's store writer marker before it touches the socket path, so two simultaneous starts resolve at the marker and never at the socket, and a daemon that loses its store closes the listener and every connection before it exits. Only the daemon's own operating-system user may connect, and -the boundary that enforces it is the filesystem: an owner-only directory and -socket whose ownership and mode the daemon verifies after bind and refuses to -serve without, which is what stops a foreign peer reaching `accept` at all. +the boundary that enforces it is the filesystem: an owner-only subdirectory +and socket whose ownership and mode the daemon verifies after bind and refuses +to serve without, which is what stops a foreign peer reaching `accept` at all, +while the state root itself keeps whatever mode it already had. Peer-credential inspection is a second, fail-closed layer whose mechanism is named per platform, because there is no portable one: the supported OTP 29 Darwin toolchain reports no `peercred` or `passcred` socket option, so Darwin diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 9d50a3bd0..027802458 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -123,10 +123,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID and, by a client that never saw the ID, through the create command's durable `command_id` returning the historical result rather than a second session; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: a permissive directory or socket mode, a parent the daemon does not own, and a path component it did not create each refused at start, and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are observed by a daemon-scoped trace session, bounded and redacted, started without changing source, which captures identities only. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files 'docs/operator/**/*.md' 'docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every @@ -287,7 +287,11 @@ rules in `apps/loopex/lib/mix/tasks/loopex.deps_budget.ex` and its cases in `apps/loopex/test/deps_budget_test.exs` change in the same reviewed change that adds the application, and `mix loopex.deps_budget` proves the direction. M5 adds no external dependency. No transport library, socket abstraction layer -or service-manager integration enters any application; the socket is the +or service-manager integration enters any application. The socket lives in a +`0700` daemon-owned `daemon/` subdirectory of the state root, which the daemon +creates and whose mode it verifies; the state root's own mode is read and never +changed, so a root the foreground server created `0755` is served unchanged and +the no-migration claim holds. The socket is the runtime's own, on OTP's `:socket` API for the local address family. The classic `inet` backend is not sufficient here and the choice is not a preference: the peer-credential read ADR 0032 requires is a socket option, and @@ -408,7 +412,7 @@ decision named above; M5 introduces none of its own. | Sessions activated per daemon lifetime | 64; the 65th activation refused, the remedy being to restart the daemon. It is per lifetime rather than concurrent because nothing deactivates a coordinator, which is recorded as a limitation | ADR 0032 | | Recorded session index entries per root | 4,096; a root whose directory holds more refused at daemon start. The ceiling is on recorded entries and never on reachability: a session reached by ID beyond it is activated and not recorded, and the listing carries `index_full` | ADR 0032 | | `session.list` page | at most 256 entries, `limit` in 1 to 256 | ADR 0032 | -| Socket path bound | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | +| Socket path bound, over `/daemon/daemon.sock` | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 170b28ef0..ff62cf533 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -51,7 +51,7 @@ loop. | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | -| 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end and daemon-internal functions observed through a daemon-scoped trace session rather than new events; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | +| 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's read of the whole parent environment is deleted outright, replaced by a fixed closed removal list, so no code path reads the environment to build one. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -222,18 +222,29 @@ that the daemon's workflows drive the existing core spans end to end: a session created, driven, taken over and aborted through the socket emits the same command-admission, commit, effect-intent, publication, interaction, model, store, policy and executor spans an embedded caller emits, with the same -bounded identity metadata. Daemon-internal functions — the listener, the -connection, the lease owner, the residency stages — are observed the way the -runtime already observes code that emits nothing: a trace session scoped to -the daemon's runtime, bounded and redacted, started without changing source. -A daemon-scoped trace session captures identities only. If the daemon later -needs events of its own, that is an ADR 0030 amendment with its exact events, -metadata, bounds and tests, and it is not M5's. The socket path is bounded by the platform's usable `sun_path`, one byte less +bounded identity metadata. That, and nothing more, is M5's observability +claim. + +Daemon-internal functions — the listener, the connection, the lease owner, the +residency stages — are proved by the daemon's own tests and its own logs, not +by a trace session. An earlier draft said a daemon-scoped trace session would +observe them, which ADR 0030 does not permit: a `Loopex.Trace` session traces +only processes the runtime owns, flagged from the runtime's supervisor with +`set_on_spawn`, and a process the runtime does not own is never covered. The +daemon's listener and lease owners are host processes above the runtime, so +they fall outside that scope by construction, and claiming otherwise would +have required widening ADR 0030's process scope. M5 does not. If the daemon +later needs events or trace coverage of its own, that is an ADR 0030 +amendment with its exact events, metadata, bounds and tests, and it is not +M5's. The socket path is bounded by the platform's usable `sun_path`, one byte less than the structure because of the terminator — at most 103 bytes on Darwin and 107 on Linux, derived per platform rather than assumed — and refused when too -long. Owner-only access is enforced first by the filesystem, an owner-only -directory and socket whose ownership and mode the daemon verifies after bind -and refuses to serve without, and second by a fail-closed peer-credential read +long. Owner-only access is enforced first by the filesystem: the socket lives in a +`0700` daemon-owned subdirectory of the state root, is itself `0600`, and both +are verified after bind, the daemon refusing to serve without them. The root +itself keeps whatever mode it has — the foreground server creates it `0755` +under the ordinary umask, so requiring `0700` there would reject every +existing M4 root and contradict the rollback claim — and second by a fail-closed peer-credential read whose mechanism is named per platform because no portable one exists: the supported OTP 29 Darwin toolchain offers no `peercred` socket option at all. A foreign peer is refused before initialize; the daemon never runs as a service-manager unit by itself, and the @@ -248,9 +259,12 @@ candidate, as it is for every milestone. That gate is only worth keeping if a reviewer can check it, so it leaves a record rather than an assurance. The closure evidence carries a checklist -derived from the candidate itself — every tracked `docs/operator/**/*.md` and -`docs/developer/**/*.md` path as `git ls-files` lists them at that commit, -sorted, one row each — and every row is marked either *updated* or *reviewed +derived from the candidate itself — every tracked Markdown path under +`docs/operator/` and `docs/developer/` as +`git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'` +lists them at that commit, sorted, one row each, with the count stated so an +empty derivation is visible rather than silently passing; the command returns +26 paths as of this revision — and every row is marked either *updated* or *reviewed unchanged*, with any finding named and resolved before the packet is assembled. A path present in the tree and absent from the list, or a row with neither mark, is an unfinished gate. Deriving the list from the candidate From 8601ce30bbf98cbf31fee672831ceea7468a4d2b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:36:02 -0700 Subject: [PATCH 025/585] plan(M5): remove the ADR 0035 experiment from the milestone Second-round item 7. The bounded experiment made M5's set incomplete: it put a real call to a second provider inside the release check M5 is required to pass, needing a credential that check does not carry and a per-provider credential reference ADR 0034 does not define. An external service's outage would then have been indistinguishable from M5 failing. A milestone whose required check depends on an unaccepted decision is not a complete set, whatever the call itself does. The experiment is gone from the plan pair, from ADR 0035's consequences and from the release check. ADR 0035 stays Proposed and wholly deferred, and its first real call -- with the first latency and price measurement -- belongs to the milestone that accepts it. The req_llm upgrade to ~> 1.24 stays in workstream 5 with its M5-specific reason now stated rather than implied: the maintainer's 2026-09-20 direction is that the milestone after M5 accommodates the typesafe.ai model, that work needs 1.24, and taking a seven-release dependency step inside M5 -- where the adapter and streaming-conformance suites and the existing real-provider case at closure already exercise it -- keeps the later milestone's cost to its own decision. It adds no call path: nothing in M5 calls anything 1.24 newly reaches, and no second provider, credential or release-check case enters. ADR 0034's reference stays singular. ADR 0035 now states the per-provider generalisation as a prerequisite amendment to 0034 that its own milestone proposes, and sketches its shape only so that change is cheap to scope, rather than describing it as something 0034 already does. --- ...ision-models-as-policy-inputs-technical.md | 71 +++++++++++-------- ...-typed-decision-models-as-policy-inputs.md | 11 +-- docs/adr/README.md | 8 +-- docs/plans/M5-technical.md | 2 +- docs/plans/M5.md | 41 ++++++----- 5 files changed, 77 insertions(+), 56 deletions(-) diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 7b0cafa98..b902a8fe9 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -81,13 +81,21 @@ bounded plain-data contract stay out by the rules that already exclude them. place where this decision constrains an earlier one. [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) fixes a per-invocation credential reference the host owns and the sender -resolves. With a second provider it has to be **per provider**: the reference a -call carries names which credential is wanted, and a host composing both -providers supplies two references rather than one ambient value per process. -Nothing about resolution, custody, rotation or the failure table changes; only -the arity of what a host supplies does. This decision therefore depends on -ADR 0034 and cannot be implemented before it is accepted and its change has -landed. +resolves, and it fixes **one** reference per call, which is right for the one +provider that exists today. A second provider needs one reference per +provider: a call names which credential is wanted, and a host composing both +supplies two references. ADR 0034 does not define that, and this pair does not +pretend it does — the generalisation is **a prerequisite change to ADR 0034**, +made by its own amendment or by an ADR superseding it, proposed with the +milestone that accepts this decision. + +Its shape is small and is named here only so the later change is cheap to +scope: the option becomes a map keyed by provider rather than one +`{resolver_module, reference_term}` pair, resolution picks the entry for the +provider being invoked, and nothing about custody, rotation, the deadline +instant or the closed reason set changes. Until that change is accepted and +landed, this decision cannot be implemented, and nothing in M5 anticipates +it. ### Seams, in the order they are worth doing @@ -99,23 +107,29 @@ landed. | 4 | Session classification | What kind of work a session is, for listing and residency | The daemon, over sessions it already holds; a daemon-side convenience with no durable effect | | 5 | Offline transcript scoring | Whatever the release check wants to measure about retained transcripts | The release check, over retained evidence, on no live path | -Seams 1 to 4 belong to the milestone after M5 and are implemented in that +All five seams belong to the milestone after M5 and are implemented in that order, because each earlier one is the cheaper proof of the same invariant. -Seam 5 is the one piece admitted earlier; see below. - -### The one experiment allowed inside M5 - -M5's provider workstream already moves to `req_llm` 1.24 for other reasons, so -the evaluation seam becomes reachable there. One bounded experiment is allowed -inside it, and only this one: an **offline scorer in the release check's -real-provider case** that calls `ReqLLM.evaluate/4` against the real endpoint -over retained transcript material, records the typed answers and the reported -`usage`, and touches no part of the agent loop. It exists to prove the 1.24 API -against the real service and to take the first latency and price measurement, -which this decision otherwise has to assert without evidence. It admits no -seam, changes no policy, journals nothing durable, and gates nothing: if it is -removed, the release check is exactly what it was. Anything beyond it waits for -this ADR's acceptance. + +### Nothing here runs inside M5 + +An earlier draft admitted one piece early: an offline scorer in M5's release +check that would call the real endpoint to prove the 1.24 API and take the +first latency and price measurement. That is withdrawn on 2026-09-20. + +The reason is not caution about the scorer itself, which really would have +touched no live path. It is that the release check is a check M5 is *required* +to pass, and putting a real call to a second provider inside it would make +M5's completeness depend on three things this decision has not settled: a +second credential the release check does not carry, a per-provider credential +reference ADR 0034 does not define, and the availability of an external +service whose failure would then be indistinguishable from M5 failing. A +milestone whose required check depends on an unaccepted decision is not a +complete set, whatever the call does. + +So the first real call, and with it the first latency and price measurement, +belongs to the milestone that accepts this decision. M5's move to `req_llm` +1.24 happens for its own dependency reasons and adds no call path: nothing in +M5 calls anything 1.24 makes newly reachable. ### Evidence @@ -164,15 +178,16 @@ Nothing public changes. The `Loopex.Policy` and `Loopex.Model` callbacks, the public protocol and its generations, public events, snapshots, artifacts, the executor protocol and every durable record are untouched. A runtime with no evaluation configured is byte-for-byte the runtime that exists today. The one -compatibility effect is on host composition, and it is ADR 0034's: a credential -reference becomes per provider. +compatibility effect is on host composition, and it arrives with the +prerequisite amendment to ADR 0034 rather than with this pair: a credential +reference becomes one per provider instead of one per call. Rollback is removing the evaluation. Every seam is an input, so a host that stops asking decides as it did before by the same path; a journaled answer remains a true record of what was observed at the time and is not a premise -anything later depends on, so nothing has to be migrated or repaired. The -offline scorer, if it exists from M5, is deleted with no effect on the release -check's other cases. +anything later depends on, so nothing has to be migrated or repaired. Nothing +from this decision exists before its own milestone, so there is nothing in M5 +to roll back. Acceptance binds this complete pair at the exact candidate the maintainer names in the governance record. Its claims remain unproved until the tests above diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md index 58fd47728..4c3b3d466 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -9,8 +9,7 @@ Technical depth: [Typed decision model mechanics](0035-typed-decision-models-as- - **Supersedes:** nothing; it refines where a host may get the *inputs* to the ADR 0009 policy decision, and changes nothing about who makes it - **Prerequisite for:** the milestone after M5. It is **not** an M5 - prerequisite and blocks nothing in M5; one bounded experiment named below is - allowed inside M5's provider workstream + prerequisite, blocks nothing in M5, and no part of it runs inside M5 ### Context and Decision @@ -108,9 +107,11 @@ Three consequences are real costs rather than benefits, and are stated as such. It is a **second provider credential**, `TYPESAFE_API_KEY` alongside the model credential, which means [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept)'s -per-invocation credential reference has to be **per provider** rather than one -per call — this decision depends on that one and cannot be implemented before -it. The **state sent to the model** is bounded, redacted, provenance-typed +per-invocation credential reference has to become **one per provider** rather +than one per call. ADR 0034 fixes one reference per call and does not define +that, so the generalisation is a prerequisite amendment to it, proposed with +the milestone that accepts this decision; this one cannot be implemented +before that lands. The **state sent to the model** is bounded, redacted, provenance-typed data the runtime already holds, under the same context-admission discipline that governs anything else staged for a provider; nothing new becomes sendable. And **latency and price are unmeasured** until the first real call; diff --git a/docs/adr/README.md b/docs/adr/README.md index 9a3a32bc4..0ff4b2d90 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -180,7 +180,7 @@ must be accepted before the outcome that depends on it is implemented. 0035 is Proposed for the milestone after M5 and is not an M5 prerequisite: it decides that a typed decision model — one that returns probabilities and confidences rather than text — may be an input to a host's policy decision and -a journaled plain-data fact, and may never be the decision. It depends on 0034, -because a second provider makes the per-invocation credential reference per -provider. M5 may run one bounded offline experiment against the real endpoint -inside its provider workstream; nothing else waits on it. +a journaled plain-data fact, and may never be the decision. It depends on 0034 +and on a prerequisite amendment to it, because a second provider needs one +credential reference per provider where 0034 fixes one per call. No part of it +runs inside M5. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 027802458..c3788d486 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -127,7 +127,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the real-provider case at closure run against it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything 1.24 makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index ff62cf533..3c92753f0 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -306,9 +306,14 @@ nothing here. proposes that a typed decision model — one returning probabilities and confidences rather than text — may be an input to a host's policy decision and a journaled plain-data fact, never the decision itself. It is not an M5 -prerequisite and no M5 outcome waits on it. M5's provider workstream carries -one bounded experiment from it and nothing more: an offline scorer in the -release check's real-provider case, on no live path. +prerequisite, no M5 outcome waits on it, and M5 runs no part of it. An +earlier draft admitted one bounded experiment inside the provider workstream; +that is withdrawn on 2026-09-20, because it would have put a real call to a +second provider, needing a second credential the release check does not carry +and a per-provider credential reference ADR 0034 does not define, inside a +check M5 is required to pass. A milestone whose required check depends on a +decision that has not been accepted is not a complete set. ADR 0035 stays +Proposed and wholly deferred. Technical depth: [Deferral acceptance points](M5-technical.md#technical-plan-prerequisites). @@ -466,22 +471,22 @@ lease — and the companion's rejoin order says where each part goes. implementer, and the measured effect on the provider suite once its modules can run concurrently. This workstream also carries one bounded dependency item: `req_llm` moves from `~> 1.17.1` to `~> 1.24` in - `apps/loopex_llm_reqllm/mix.exs` and `mix.lock`. It is an ordinary - dependency decision, so it lands as its own reviewed change, naming the - version floor, the reviewed changelog diff across the intervening releases, - the adapter and streaming-conformance suites green, and the real-provider - case at closure. It is sequenced before the credential change where both + `apps/loopex_llm_reqllm/mix.exs` and `mix.lock`. Its M5-specific reason is + stated rather than left implicit: the maintainer's direction of 2026-09-20 + is that the milestone after M5 will accommodate the typesafe.ai model, that + work needs 1.24, and taking a seven-release dependency step inside M5 — + where the adapter and streaming-conformance suites and the existing + real-provider case at closure are already exercised against it — keeps the + later milestone's cost to its own decision rather than bundling a large + dependency move into it. It is an ordinary dependency decision, so it lands + as its own reviewed change, naming the version floor, the reviewed + changelog diff across the intervening releases, the adapter and + streaming-conformance suites green, and the existing real-provider case at + closure run against it. It is sequenced before the credential change where both touch the adapter, so the credential proofs are written once against the - upgraded library rather than twice. Because 1.24 also makes - `ReqLLM.evaluate/4` reachable, this workstream carries one bounded - experiment for - [ADR 0035](../adr/0035-typed-decision-models-as-policy-inputs.md#concept): - an offline scorer in the release check's real-provider case that calls the - real endpoint over retained transcript material and records the typed - answers and the reported `usage`, which is where that decision's latency - and price are first measured. It touches no part of the agent loop, admits - no seam, journals nothing durable and gates nothing; removing it leaves the - release check exactly as it was. It touches no daemon application code, + upgraded library rather than twice. The upgrade adds no call path in M5: + nothing in the milestone calls anything 1.24 makes newly reachable. It + touches no daemon application code, and no daemon workstream touches the adapter's library tree — but it is not file-disjoint from them: host composition, the integration scripts, the provider pages and the closure evidence page are reached by both, and the From 6946fb9d785d4468237ffe86df90fa24763edec3 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:36:46 -0700 Subject: [PATCH 026/585] plan(M5): correct four material claims across the set Second-round material items. Generation 2 does not reuse ADR 0023's request records unchanged: every existing-session mutation adds writer_epoch, which is what the admission check reads. Both plan files and ADR 0032 now say so, with the exception named at the request record rather than buried, because that addition is exactly why generation 2 needs its own schema digest. The host-custody proofs were filed in the adapter's test tree, which cannot prove a claim about the CLI's or the daemon's composition. Each now lives at its subject: apps/loopex_cli/test/, apps/loopex_app_server/test/ and apps/loopex_daemon/test/. The adapter's tree keeps what is the adapter's to prove. "Furthest behind" was undefined across sessions, where sequence numbers are not comparable. It is now encoded bytes owed -- events core has named for an attachment that the daemon has not yet written -- which is a daemon-owned quantity in bytes, comparable across sessions and measuring the thing the ceiling is about. `controlled` and `residency` on lease-owner failure are reconstructed by the daemon restart ADR 0033 now requires. The fast check was said to prove outcomes 1 to 4 "in full", but the cross-UID socket refusal needs a second unprivileged user and can only run on the release check's Linux lane. The claim is corrected, and closure is bound to that lane's recorded result: a foreign uid refused before initialize and the daemon's own accepted. An absent Linux-lane result is missing evidence, not a pass. --- ...tachment-residency-and-replay-technical.md | 8 ++++- ...-daemon-attachment-residency-and-replay.md | 7 +++-- ...andoff-over-bootstrap-channel-technical.md | 15 +++++++--- docs/plans/M5-technical.md | 14 +++++++-- docs/plans/M5.md | 29 ++++++++++++++----- 5 files changed, 56 insertions(+), 17 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index fa4935e39..4236eee2e 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -336,7 +336,13 @@ delivered contiguously after the snapshot. The daemon adds: attachments, in ascending order of the monotonic time of their last delivery, ties broken by session ID bytes ascending; then, if the ceiling is still exceeded, the window of the session whose slowest attachment is - furthest behind, by the same tie-break. Only after every window has been + furthest behind **by encoded bytes owed** — the sum of encoded bytes for + events core has named for that attachment and the daemon has not yet + written, which is a daemon-owned quantity comparable across sessions because + it is measured in bytes rather than in each session's own sequence numbers. + A sequence-distance metric would not be comparable: sequence numbers are + per-session and say nothing about how much memory an attachment is costing. + Ties break by session ID bytes ascending. Only after every window has been released does the daemon detach the slowest attachment at its last emitted cursor. Independently of pressure, a window whose session has had zero attachments for the idle interval is dropped. No reclamation stalls a diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 05a1b2cd4..7de35a1a1 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -31,8 +31,11 @@ durable events and terminal outcomes, not every dropped progress fragment. Decide the transport and the residency rules together, because the numbers only mean something against a transport. The daemon carries the ADR 0023 JSONL protocol over a Unix-domain socket, reusing its framing, initialize -handshake, request, admission, snapshot, event and progress records and -limits unchanged, and serves exactly one generation, +handshake, admission, snapshot, event and progress records and limits +unchanged — and its request records with exactly one addition, the +`writer_epoch` every existing-session mutation carries, which is what makes +generation 2 a new schema digest rather than a rename. It serves exactly one +generation, `loopex.experimental/2`, which adds `session.list`, `daemon.status`, the two control methods and the writer-epoch field ADR 0033 names. It adds no durable method. An earlier draft of this decision also added `session.stop` and called diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 7397e5fd8..27f6ce561 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -319,10 +319,17 @@ Three proofs are new: level over a real invocation shows placeholders where the reply and the resolved value would be, and no credential bytes anywhere in the captured entries. -- **Host custody.** For each reference host — the CLI, the app-server host and - the daemon — composition reads the variable exactly once, deletes it, and - the holding process's `format_status/1` redacts its state under a forced - crash report. +- **Host custody, proved at each host rather than in the adapter.** The + adapter's test tree cannot prove a claim about the CLI's or the daemon's + composition, and an earlier draft filed all three there. Each case lives + where its subject lives: `apps/loopex_cli/test/` for the reference CLI, + `apps/loopex_app_server/test/` for the app-server host, and + `apps/loopex_daemon/test/` for the daemon. Each proves that composition + reads the variable exactly once, deletes it from the VM's environment, and + that the holding process's `format_status/1` redacts its state under a + forced crash report. The adapter's own tree keeps only what is the adapter's + to prove: that it reads no environment variable and that the resolver + contract behaves. The first two, the failure cases and the custody cases belong in `credential_plane_test.exs` beside the cases they generalise; the drift case diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index c3788d486..d88a05bee 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -167,7 +167,12 @@ the floor pair, `mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh` with its own `MIX_BUILD_ROOT`; and `bash scripts/check-release.sh` runs once on the current pair with the provider credential and the pinned Node version in -`scripts/fixtures/m4/client-toolchain.txt`. `loopex_daemon` joins that +`scripts/fixtures/m4/client-toolchain.txt`. That release check is where +Outcome 2's cross-UID witness lives, and closure is bound to it: the Linux +lane must record a connection from a foreign uid refused before initialize and +one from the daemon's own uid accepted. The fast check cannot supply it, +because it has no second user, so an absent Linux-lane result is missing +evidence rather than a pass. `loopex_daemon` joins that script's `release_apps` list in the change that adds its first release case, and only that list: every `release_apps` lane already runs `--include long_bound`, so the daemon's long-duration bound tests are carried @@ -225,7 +230,12 @@ Concept: [Rollout and compatibility](M5.md#concept-plan-rollout). The `v0.2.0` source tag identifies a numbered release, not a compatibility freeze; all surfaces remain experimental. The socket reuses ADR 0023's -framing, handshake, records and limits unchanged. Generation 2 is additive +framing, handshake, limits, and its admission, snapshot, event and progress +records unchanged. Its **request** records are reused with one addition, not +unchanged: every existing-session mutation in generation 2 carries +`writer_epoch`. Saying "records reused unchanged" without that exception would +be wrong in the one place a reader checks it, at the schema digest, which is +precisely why generation 2 needs its own. Generation 2 is additive over generation 1's method set under the exact-generation rule: a generation-1 client sees no daemon method and no lease field, the daemon refuses a generation-1-only initialize, and the foreground server keeps serving diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 3c92753f0..63e6cb1f9 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -68,8 +68,13 @@ provider configuration and project resources when the daemon starts; no client connection replaces any of them, and the daemon's configuration may narrow who may take control but never widens what host policy allows. -The socket reuses ADR 0023's framing, initialize handshake, request, -admission, snapshot, event and progress records and limits unchanged, and +The socket reuses ADR 0023's framing, initialize handshake, admission, +snapshot, event and progress records and limits unchanged. Request records are +reused with one addition rather than unchanged, and the plan says so: every +existing-session mutation in generation 2 carries `writer_epoch`, which is +what ADR 0033's admission check reads. That is the one field generation 2 adds +to a request, and it is additive — a generation-1 client never sees it, +because the daemon serves generation 2 only. The daemon serves generation `loopex.experimental/2` only, which adds `session.list`, `daemon.status`, the two control methods and the writer-epoch field, and lifts the one-attachment-per-process rule to residency limits. It adds no durable @@ -345,12 +350,20 @@ it adds no per-milestone runner and no check of its own. **Change.** Every merge to `main` needs `bash scripts/check.sh` green in hosted CI on that branch and an independent read of the diff. The fast check -is credential-free and needs no network, so it is what proves outcomes 1, 2, 3 -and 4 in full — daemon lifetime and store fault injection on real local -processes, socket framing and generation negotiation, lease admission and -fencing after real kills, and the residency and delivery bounds — and it -proves the parent-environment, concurrency-independence and re-pointed -negative cases of Outcome 6. +is credential-free and needs no network, so it carries most of outcomes 1, 2, +3 and 4 — daemon lifetime and store fault injection on real local processes, +socket framing and generation negotiation, lease admission and fencing after +real kills, and the residency and delivery bounds — and the +parent-environment, concurrency-independence and re-pointed negative cases of +Outcome 6. + +It does not prove them *in full*, and an earlier draft said it did. One +witness cannot be had there: the cross-UID socket refusal needs a second +unprivileged user, so it runs on the release check's Linux lane and nowhere +else. Outcome 2's owner-only claim is therefore complete only at closure, and +closure is bound to that lane's recorded result — a refused connection from a +foreign uid and an accepted one from the daemon's own — rather than to a fast +check that cannot reach it. Beyond the fast check, a change selects only what its boundary asks for. The rows of the From ce10a2e54f5a2bef90c4d321b9d6cfaebb01018d Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 19:37:59 -0700 Subject: [PATCH 027/585] plan(M5): say in Outcome 2 which records generation 2 changes Self-review of the second-round set. Outcome 2 still read "framing, handshake and records reused unchanged" after the companion had been corrected to name writer_epoch as the one request-record addition. The outcome now matches: admission, snapshot, event and progress records unchanged, request records with the one added field. --- docs/plans/M5.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 63e6cb1f9..822280b59 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -48,7 +48,7 @@ loop. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | | 1 | A daemon owns session lifetime for a state root: an activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID and by its create `command_id`, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | -| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake and records reused unchanged, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | +| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | From 245882a9f8178ea60252eab1b255d2159515342f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:10:05 -0700 Subject: [PATCH 028/585] plan(M5): add core's read-only session-existence query Maintainer decision 1A, recorded at the third audit on 2026-09-20. Core's M5 change becomes two narrow things: concurrent attachments, and one read-only query answering whether a session ID exists durably in the root -- no attach, no resume, no side effect, a plain-data answer. What it reverses: the previous set had the daemon learn durable existence by calling core's attach or resume and forwarding the answer. The maintainer rejected that, and the documents now record it as rejected with its reason. Asking a question by performing the operation is not asking: attach establishes a cursor barrier and an attachment incarnation, resume is a durable mutation under ADR 0008's placement rules, and acquire_control has to be safe to call on an ID that turns out not to exist -- it must validate existence before granting a lease, not after taking a side effect. Landed in the plan's purpose, scope and no-durable-method paragraph, Outcomes 1 and 3, the loopex and loopex_daemon ownership rows, the ADR 0032 prerequisite row, the rejoin semantics where "verified dormant session" is now verified by the query, workstream 1's name and scope, ADR 0032's crash-cut recovery, ADR 0033's acquire_control and its concept, the minimalism budget naming what the query unifies and why direct code cannot supply it, and the evidence table -- a core test at apps/loopex/test/session_existence_query_test.exs proving the query creates no attachment, no incarnation, no durable record and no Store write, with the root byte-identical before and after including for unknown IDs, plus the daemon case that uses it. The daemon still reads no Store internals. --- ...tachment-residency-and-replay-technical.md | 31 +++++++---- ...controller-lease-and-takeover-technical.md | 14 +++-- ...aboration-controller-lease-and-takeover.md | 6 ++- docs/plans/M5-technical.md | 24 ++++++--- docs/plans/M5.md | 53 ++++++++++++------- 5 files changed, 89 insertions(+), 39 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 4236eee2e..bc389a1b4 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -186,15 +186,28 @@ attaches, and the snapshot carries them at a committed sequence. **The recovery procedure for the crash cut**, in four parts, needing no new durable record and no Store read by the daemon: -1. **Durable existence is learned only from core.** The daemon never reads - Store internals and never enumerates the log to decide whether a session - exists. It calls core's existing attach or resume on the ID and treats - core's answer as the proof: core resolves it or refuses it, and the daemon - forwards that answer. So `session.acquire_control` on an ID the index does - not hold validates durable existence the only way the daemon is allowed - to — by asking core — and a refusal from core is the refusal the client - sees. Nothing about the index is consulted to decide existence, which is - why an index that is incomplete is not a correctness problem. +1. **Durable existence is learned from core, through a query that asks only + that.** The daemon never reads Store internals and never enumerates the log + to decide whether a session exists. It calls core's read-only + session-existence query on the ID — no attach, no resume, no side effect, + a plain-data answer — and treats core's answer as the proof. + + An earlier draft had the daemon learn existence from `attach` or `resume` + themselves. The maintainer rejected that on 2026-09-20 and admitted the + query instead. Asking a question by performing the operation is not a + question: `attach` establishes a cursor barrier and an attachment + incarnation, `resume` is a durable mutation under ADR 0008's placement + rules, and a daemon that had to run one of them to discover that a session + does not exist would be taking a side effect to learn a fact — worst of all + at `acquire_control`, which must validate existence *before* granting a + lease and must be safe to call on an ID that turns out to be unknown. + + So `session.acquire_control` on an ID the index does not hold validates + durable existence with the query, and a negative answer is the refusal the + client sees, with nothing created and no attachment left behind. Nothing + about the index is consulted to decide existence, which is why an index + that is incomplete is not a correctness problem, and the daemon still reads + no Store internals. 2. **A client that never saw the session ID recovers by command identity.** At the cut where the Store committed the creation and the process died before the reply, the client may hold no ID at all. It is not lost: the diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index b7bb6bf5e..e83c49109 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -81,8 +81,15 @@ the local store's writer marker, unchanged. the new `writer_epoch` and `expires_in_ms`, the remaining term on the daemon's clock. For a known dormant session, a connection may acquire by session ID before attach. The daemon validates durable session existence - first; the held lease lets that connection call `session.resume` and then - attach. Daemon startup recovery of sessions is a root-owner operation under + first, and it does so with core's read-only session-existence query — the + one that asks only whether the root holds that ID, with no attach, no + resume and no side effect. That matters here more than anywhere: acquire + must be safe to call on an ID that turns out to be unknown, and an earlier + draft that learned existence by calling `attach` or `resume` would have + taken a durable or attaching side effect to answer a question. The + maintainer rejected that on 2026-09-20. An unknown ID refuses with nothing + created, nothing attached and no lease granted; a known one grants, and the + held lease lets that connection call `session.resume` and then attach. Daemon startup recovery of sessions is a root-owner operation under the store's writer marker, never a client mutation and never a grant of controller authority. - `session.release_control` (`session_id`, `request_id`): releases the @@ -108,7 +115,8 @@ the local store's writer marker, unchanged. grants control. The caller must acquire control explicitly and use the returned epoch for its first session command. Acquire and attach may be sent in either order, because acquire is keyed by session ID and validates - only durable session existence; the constraint is on the first mutation, + only durable session existence, through the read-only query; the + constraint is on the first mutation, not on the two calls that precede it, and that mutation refuses unless the sending connection is the holder, the epoch matches and the connection holds a controller-capable attachment. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index f5e6d8412..385329c90 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -36,8 +36,10 @@ observer cannot reuse an epoch it learned from a result or status. it creates an uncontrolled session, and control over it is never implicit. Attach and acquire are independent of each other and their order is not -fixed. A connection may acquire control of any session that durably exists, -by session ID, before or after it attaches to that session; what is fixed is +fixed. A connection may acquire control of any session that durably exists — +which the daemon establishes by asking core its read-only existence query, not +by attaching or resuming to find out — by session ID, before or after it +attaches to that session; what is fixed is that no existing-session mutation is admitted until the lease is held by the sending connection, its epoch matches, and — with the single exception of `session.resume` on a verified dormant session — that connection holds a diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d88a05bee..17387c71b 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -18,7 +18,7 @@ decision named only in prose declares nothing. | Decision | Acceptance point | What its acceptance settles | | --- | --- | --- | | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | -| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or the core attachment change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | +| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or either core change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by a `{resolver_module, reference_term}` reference the host owns, resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; the resolver's owner, custody, rotation, deadline bounding and every failure outcome; no environment read anywhere in the adapter's library tree and the launcher's enumeration deleted rather than relocated, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | @@ -37,10 +37,10 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | -| `loopex_daemon` | Marker-first process and socket lifetime, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | +| `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | | `loopex_llm_reqllm` | The credential handoff, its sender, the resolver behaviour it declares, the launcher's fixed closed removal list that replaces its environment enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | @@ -99,7 +99,10 @@ and their order is not fixed, as ADR 0033 settles it: the constraint is on the first mutation, which is admitted only when the sending connection holds the lease, its epoch matches and that connection holds a controller-capable attachment. The single exception is `session.resume` on a verified dormant -session, which the holder may send before attaching. The lease record lives +session, which the holder may send before attaching. "Verified" means verified +by core's read-only existence query, not by having attached or resumed already: +acquire validates existence with that query and refuses an unknown ID with +nothing created. The lease record lives in the daemon's memory, keyed by session, for the daemon process's lifetime; one owner process per session serializes its lease transitions with its admission handoff, and a restart of that owner leaves the session uncontrolled. For @@ -122,10 +125,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID and, by a client that never saw the ID, through the create command's durable `command_id` returning the historical result rather than a second session; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through the create command's durable `command_id` returning the historical result rather than a second session; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers plain data for a session that exists and for one that does not, from a fresh process against a real root, and is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown IDs. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything 1.24 makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -382,7 +385,14 @@ Concept: [Scope](M5.md#concept-plan-scope). The smallest sufficient system wins, and each addition below names what it unifies and why direct code is insufficient. One application, because a daemon is a host and a host is an application. One socket listener, one narrow -core concurrent-attachment change, one in-memory lease record and one +core concurrent-attachment change, one read-only core existence query — which +unifies the three daemon paths that must know whether an ID exists before +doing anything with it (acquire, activation of a session the index does not +hold, and the crash-cut recovery), and which direct code cannot supply, +because the only alternatives are reading Store internals, which the +dependency direction forbids, or calling `attach` or `resume` for their +answer, which takes an attaching or durable side effect to ask a question — +one in-memory lease record and one admission check, one resident window and eviction policy, one per-connection output buffer, one session index with bounded pages, three CLI commands and the Node client's socket mode. Outcome 6 adds exactly one abstraction, the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 822280b59..b3b9f9c58 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -38,18 +38,19 @@ channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above -the core. The core's attachment machinery gains narrow support for several -independent attachments to one session; it gains no lease, transport or second -loop. +the core. Core gains exactly two narrow things: support for several +independent attachments to one session, and one read-only query that answers +whether a session ID exists durably in the root. It gains no lease, no +transport, no second loop and no new durable command. ### Outcomes | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root: an activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID and by its create `command_id`, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root: an activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | -| 3 | One controller drives while observers watch: the daemon checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | +| 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's read of the whole parent environment is deleted outright, replaced by a fixed closed removal list, so no code path reads the environment to build one. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | @@ -61,9 +62,22 @@ Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-pl The daemon owns session lifetime, the socket, attachment residency, the collaboration lease, its session index and the local store root it holds for -its process's lifetime. Core owns durable session truth and supports several +its process's lifetime. Core owns durable session truth, supports several independent attachments to one session through its existing race-free attach -barrier and dispatcher. Hosts still supply workspace, identity, policy, +barrier and dispatcher, and answers one read-only question about it: given a +session ID, does this root hold that session durably. + +That query is the second and last of core's M5 changes, and it exists because +the alternative was worse. The daemon has to validate durable existence before +it grants a lease, and before it records a session its index does not hold, +and it may not read Store internals to do it. Learning existence by *calling* +`attach` or `resume` — the earlier draft, rejected by the maintainer on +2026-09-20 — means taking a side effect to ask a question: `attach` +establishes a cursor barrier and an attachment incarnation, `resume` is a +durable mutation under ADR 0008's placement rules, and neither is safe to run +speculatively on an ID that may not exist. The query answers plain data, +creates nothing, changes nothing, and is the smallest thing that can be asked +honestly. Hosts still supply workspace, identity, policy, provider configuration and project resources when the daemon starts; no client connection replaces any of them, and the daemon's configuration may narrow who may take control but never widens what host policy allows. @@ -78,9 +92,10 @@ because the daemon serves generation 2 only. The daemon serves generation `loopex.experimental/2` only, which adds `session.list`, `daemon.status`, the two control methods and the writer-epoch field, and lifts the one-attachment-per-process rule to residency limits. It adds no durable -method: core owns durable session truth and its only M5 change is concurrent -attachment, so a daemon method that ended a session durably would have to add -a durable command to core, which M5 does not do. Ending a client's involvement +method: core owns durable session truth and its M5 changes are concurrent +attachment and one read-only existence query, neither of which is a durable +command, so a daemon method that ended a session durably would have to add +one, which M5 does not do. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by acquiring control and attaching. @@ -116,10 +131,11 @@ the request path; a client that needs them attaches, and the snapshot carries them authoritatively. A session missing from the list is never a lost session, and the plan says -exactly how it is recovered. The daemon learns durable existence only from -core: it calls core's attach or resume on the ID and forwards core's answer, -reading no Store internals, so an incomplete index is never a correctness -problem. A client that never received the session ID — the cut where the +exactly how it is recovered. The daemon learns durable existence from core, +through a read-only query that asks only that: given a session ID, does the +root hold it durably. No attach, no resume, no side effect, a plain-data +answer. The daemon reads no Store internals, so an incomplete index is never +a correctness problem. A client that never received the session ID — the cut where the Store committed and the process died before the reply — recovers through the create command's durable `command_id`, which returns the historical result instead of creating a second session. If recording the directory entry fails @@ -450,10 +466,11 @@ sixth runs last because it describes what the others built. Workstream 1 lands in two parts — the core change first, its daemon-side residency after the lease — and the companion's rejoin order says where each part goes. -1. **Core concurrent attachments, and the residency above them.** The narrow - core change that lets distinct attachments to one session coexist without - implicit replacement — which the daemon's attach path needs before anything - about it can be proved, so it lands first — and then, once the lease +1. **Core's two changes, and the residency above them.** The narrow core + change that lets distinct attachments to one session coexist without + implicit replacement, and the read-only session-existence query the + daemon's acquire and activation paths need — both land first, because + nothing about the daemon can be proved without them — and then, once the lease exists, the daemon-side residency over it: the resident window as a droppable cache, per-connection output buffers, detachment at the last emitted cursor, idle eviction, dormancy and the aggregate byte ceiling with From cc4cf17a78d9919a95819bf023df26a5adceaf79 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:13:16 -0700 Subject: [PATCH 029/585] adr(M5): make the credential an opaque token over a routing registry Maintainer decision 2A, recorded at the third audit on 2026-09-20. The per-invocation input becomes an opaque token: a bounded identifier that carries no credential, no routing and no authority. Behind it the host owns a routing registry mapping token to custody process -- routing only, never bytes, never material a secret could be derived from -- and the custody process that holds the bytes. The sender resolves the token through the registry to the custody process, whose reply remains the one permitted credential-bearing transfer, and the registry lookup adds no second place a secret can be seen. What it reverses, recorded as rejected in the pair: the {resolver_module, reference_term} reference. It did two jobs in one value -- routing travelled through every copy of adapter configuration, disclosing the host's arrangement -- and a second provider would have widened the value instead of adding a registry row. The guardian now enforces the resolution deadline. The callback loses its deadline argument entirely; the guardian already owns the invocation deadline and supervises the sender, so it bounds the registry lookup, the call and the wait, and kills the sender at the instant. The previous design handed the resolver an absolute instant and trusted it, which made a safety property depend on code the adapter does not write and let a blocking custody process hang the invocation past its deadline. Loss of custody or registry answers :unavailable until the host recomposes and reconstructs nothing -- there is nothing to reconstruct from, since the registry holds no bytes. The closed reason set is unchanged, with :unavailable now also covering a missing row, a gone registry and a dead custody process. The credential-bearing resolver call stays excluded from tracing by the mechanism established last round: ADR 0030's arguments-level redaction class covers a credential reference and any value reachable through it, the token is that reference, and M5 proves the exclusion under a real trace session. ADR 0035 is re-read for consistency: its per-provider generalisation is now per-provider tokens and registry rows, which is what keeps that prerequisite amendment to 0034 small. --- ...andoff-over-bootstrap-channel-technical.md | 255 +++++++++++------- ...edential-handoff-over-bootstrap-channel.md | 95 +++++-- ...ision-models-as-policy-inputs-technical.md | 39 +-- ...-typed-decision-models-as-policy-inputs.md | 12 +- docs/adr/README.md | 2 +- docs/plans/M5-technical.md | 29 +- docs/plans/M5.md | 13 +- 7 files changed, 270 insertions(+), 175 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 27f6ce561..0cbf2fb8c 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -52,42 +52,57 @@ booting — never reaches step 5. That is the property the two existing bootstrap-refusal cases assert, and it is why the credential is not carried by the step-3 frame. -### The reference, its resolver, and its failures - -The per-invocation option is `:credential_reference`, one member of the -configuration map the host already supplies to `complete/3`. Its value is -`{resolver_module, reference_term}`: - -- `resolver_module` is an atom naming a module that implements - `Loopex.LLM.ReqLLM.CredentialResolver`, one callback, - `resolve(reference_term, deadline) :: {:ok, binary()} | {:error, reason}`, - where `deadline` is an **absolute monotonic instant** in native units, not a - remaining duration — a duration is stale the moment it is computed, and the - sender and the resolver are different processes. `reason` comes from the - closed set below and never from the resolver's own vocabulary; -- `reference_term` is bounded plain boundary data — at most 256 bytes when - encoded by the repository's canonical encoding, and never a PID, port, - function, monitor or reference. It names which credential is wanted; it is - not the credential and carries no authority of its own. - -Any other shape, including a bare binary that could be the bytes themselves, -is refused as an invalid option before any child is spawned. The behaviour -exists rather than a closure because the reference travels in configuration -that is copied between processes and may be printed by a crash report, and -plain boundary data is what may travel there. - -**Owner and custody.** The resolver is the host's. The adapter declares the -behaviour, calls it, and knows nothing about where the bytes live. Each -reference implementation states its own custody and proves it for itself: -the reference CLI, the app-server host and the M5 daemon read -`Loopex.LLM.ReqLLM.credential_variable/0` exactly once, where they compose the -runtime, delete that name from the VM's environment in the same step, and hold -the bytes in one host-owned custody process, registered under the runtime -reference rather than a global name, whose `format_status/1` redacts its state -and which answers `resolve/2` only for its own reference term. The -real-provider lane composes the same way. Nothing in the adapter depends on -that arrangement, and a different host may keep the bytes anywhere it can -defend. +### The token, the routing registry, and the custody process + +The per-invocation option is `:credential_token`, one member of the +configuration map the host already supplies to `complete/3`. Its value is an +**opaque token**: a binary of at most 256 bytes from ADR 0023's identifier +alphabet, carrying no structure the adapter interprets and no authority of its +own. It is not the credential, it does not name a module, and it cannot be +resolved by anyone who is not already holding the host's registry. Any other +shape, including a bare binary that could plausibly be the bytes themselves — +anything outside the alphabet or over the bound — is refused as an invalid +option before any child is spawned. + +The token replaces the `{resolver_module, reference_term}` pair an earlier +draft used. The maintainer decided that on 2026-09-20. A pair that named a +module was doing two jobs at once: it carried routing (which process answers) +in the same value that travelled through adapter configuration, so every +copy of that configuration disclosed the shape of the host's credential +arrangement, and adding a second provider would have meant widening the value +rather than adding a row. An opaque token discloses nothing and is the same +size whatever the host is doing behind it. + +**The routing registry is the host's, and holds routing only.** The host +composes a registry that maps token to custody process, and that is the whole +of its contents: no credential bytes, no derived material, nothing from which +a secret could be reconstructed. It is the indirection that lets the token be +opaque. The sender resolves the token through the registry to reach the +custody process; the registry itself never sees or holds a credential, so +reading it discloses which tokens exist and nothing about what they stand +for. + +**Custody is a separate process, and is where the bytes live.** Each reference +implementation states and proves its own: the reference CLI, the app-server +host and the M5 daemon read `Loopex.LLM.ReqLLM.credential_variable/0` exactly +once, where they compose the runtime, delete that name from the VM's +environment in the same step, hold the bytes in one host-owned custody process +registered under the runtime reference rather than a global name, whose +`format_status/1` redacts its state, and register its token in the routing +registry. The real-provider lane composes the same way. Nothing in the adapter +depends on that arrangement, and a different host may keep the bytes anywhere +it can defend. + +**Loss of either is `:unavailable`, and neither is reconstructed.** If the +custody process is gone, or the registry has no row for the token, or the +registry itself is gone, resolution answers `:unavailable` and the invocation +refuses. The adapter does not retry, does not fall back, and above all does +not attempt to rebuild the secret from anything — there is nothing to rebuild +it from, by construction, because the registry holds no bytes. The host +recomposes; until it does, every invocation on that token refuses the same +way. That is the whole recovery story, and it is deliberately the shortest one +available: a mechanism that could restore a credential after its custodian +died would be a mechanism that had kept a second copy somewhere. **Exactly one credential-bearing transfer exists in the parent, and it is named.** An earlier draft said the value never appears in a message while also @@ -96,25 +111,31 @@ true, because answering is a message. The contract is a permission with a boundary, not an absolute: - The **only** permitted credential-bearing transfer in the parent is the - custody process's reply to `resolve/2`, carrying `{:ok, bytes}` to the one - sender process that asked. It is bounded by the same 1..65,536-byte rule as - the frame, it is never logged, never forwarded, and never held after the - frame is written. + custody process's reply to the sender's `resolve` call, carrying + `{:ok, bytes}` to the one sender process that asked. It is bounded by the + same 1..65,536-byte rule as the frame, it is never logged, never forwarded, + and never held after the frame is written. The registry lookup that precedes + it carries no credential, so the token's journey through the registry adds + no second place a secret can be seen. - It is deliberately the same class of act as the credential frame write: one short-lived process receives the bytes, uses them once, and dies. ADR 0019 already protects that process — the sender installs its own group-leader sink so no IO request can carry anything out of it, it is unregistered, and it reports only an atom or a `{:error, atom}` pair to the guardian. -- Observation of the sender is governed by the tracing rules rather than left - to hope. ADR 0030's `arguments` level redacts "a credential reference, model - content, tool arguments and artifact bytes to placeholders" and replaces - "any value reachable through a credential reference". The sender is a - `Loopex.*` module and, spawned beneath runtime-owned processes, is reachable - by `set_on_spawn`, so M5 must **prove** that the reply and the resolved value - fall inside that redaction class: a trace session at the `arguments` level - over a real invocation shows placeholders and no credential bytes. That is a - proof obligation on M5, not a change to ADR 0030, whose redaction class - already names this category. +- **The credential-bearing resolver call is excluded from tracing, and the + mechanism is named.** ADR 0030's `arguments` level redacts "a credential + reference, model content, tool arguments and artifact bytes to placeholders" + and replaces "any value reachable through a credential reference" — the + token and the value it resolves to are inside that class by construction, + since the token *is* the credential reference and the bytes are what it + reaches. The sender is a `Loopex.*` module and, spawned beneath + runtime-owned processes, is reachable by `set_on_spawn`, so being inside + the class is what excludes it rather than being out of scope. M5 must + **prove** it: a trace session at the `arguments` level over a real + invocation shows placeholders for the resolver call, its reply and the + resolved value, and no credential bytes anywhere in the captured entries. + That is a proof obligation on M5, not a change to ADR 0030, whose redaction + class already names this category. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or @@ -125,44 +146,61 @@ process, between the child's `ready` frame and the credential frame — step 5 above and nowhere else. A resolved value is never cached, never reused for a second invocation, and never returned to the guardian. -**Rotation.** Per invocation, by construction: the resolver may answer -different bytes for the same reference on a later call, and no layer holds a -previous answer to contradict it. A rotation that happens while an invocation +**Rotation.** Per invocation, by construction: the custody process may answer +different bytes for the same token on a later call, and no layer holds a +previous answer to contradict it. The host may also rotate by pointing the +token's registry row at a new custody process, which the next invocation +follows and an in-flight one does not. A rotation that happens while an invocation is in flight does not reach that invocation, which has already resolved; it reaches the next one. Nothing is invalidated and no invocation is restarted. -**Timeout.** Resolution is bounded by the invocation's existing deadline and by -nothing else; this decision adds no second clock. The sender passes that -deadline as an absolute monotonic instant, and a resolver that has not answered -when it is reached is a failed resolution reported as `:timeout`. - -**The closed reason set.** A resolver answers `{:error, reason}` only with -`:missing`, `:expired`, `:oversized` or `:unavailable`; the sender itself -produces `:timeout`. Nothing else is admitted — a resolver returning anything -outside the set is treated as `:unavailable`, because a host-authored term is -exactly where a secret could be smuggled into a reason. The five atoms carry no +**The guardian enforces the deadline, not the resolver.** Resolution is +bounded by the invocation's existing deadline and by nothing else; this +decision adds no second clock and, after the maintainer's decision of +2026-09-20, it does not ask the resolver to honour one either. The callback +takes no deadline argument. The guardian already owns the invocation deadline +and already supervises the sender, so it bounds the whole resolution — the +registry lookup, the call, and the wait for a reply — and kills the sender +when the instant is reached, reporting `:timeout`. + +An earlier draft passed an absolute monotonic instant to the resolver and +relied on it to answer in time. That is withdrawn: it made every host's +resolver responsible for a safety property the adapter must have whatever the +host wrote, and a resolver that simply blocked would have hung the invocation +past its deadline. Enforcement belongs to the process that can act on it by +killing something. The resolver's only obligation is to answer or not. + +**The closed reason set is unchanged.** A custody process answers +`{:error, reason}` only with `:missing`, `:expired`, `:oversized` or +`:unavailable`; the guardian produces `:timeout`, and `:unavailable` is also +what a missing registry row, a gone registry and a dead custody process +answer. Nothing else is admitted — anything returned outside the set is +treated as `:unavailable`, because a host-authored term is exactly where a +secret could be smuggled into a reason. The five atoms carry no content, so they are safe in a message, an exit reason and a bounded diagnostic. **What the sender reports.** `:ok` or `{:error, reason}` from that same closed -set, never a bare `:error`. The guardian has to distinguish a resolver that -refused from one that never answered: they are different operational faults and -ADR 0029's bounded status has to say which happened. The reported reason is one -of the five atoms and never the resolved value, the reference, or a -resolver-authored string. +set, never a bare `:error`. The guardian has to distinguish a custody process +that refused from one that never answered — they are different operational +faults and ADR 0029's bounded status has to say which happened — and it can, +because a refusal arrives as one of the four atoms while a silence is the +guardian's own `:timeout`. The reported reason is never the resolved value, +the token, or a host-authored string. **Failures.** Each is a refusal with a bounded non-secret reason, and each leaves no retained copy of anything the resolver may have produced: | Condition | Outcome | | --- | --- | -| No `:credential_reference` in the configuration | Refused before the namespace is created and before any child is spawned, with the adapter's existing missing-credential reason | -| Malformed reference, or a `resolver_module` that does not export the callback | The same refusal, before any child is spawned | -| Resolver answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | -| Resolver answers `{:error, :unavailable}`, or anything outside the closed set | The same path, reported as `:unavailable` | -| Resolver has not answered when the deadline instant is reached | The sender reports `{:error, :timeout}`, distinct from every refusal, and is killed so its stack goes with it | +| No `:credential_token` in the configuration | Refused before the namespace is created and before any child is spawned, with the adapter's existing missing-credential reason | +| Malformed token — outside the identifier alphabet or over 256 bytes | The same refusal, before any child is spawned | +| The registry holds no row for the token, the registry is gone, or the custody process is dead | `:unavailable`. The host recomposes; nothing is reconstructed, because the registry holds no bytes to reconstruct from | +| Custody answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | +| Custody answers `{:error, :unavailable}`, or anything outside the closed set | The same path, reported as `:unavailable` | +| Resolution has not completed when the guardian's invocation deadline is reached | The **guardian** kills the sender and reports `{:error, :timeout}`, distinct from every refusal; the sender's stack goes with it. A custody process that simply blocks cannot hang the invocation, because nothing depends on it noticing the time | | Resolved value outside 1 to 65,536 bytes | Refused in the sender before the frame is written, exactly as the size check refuses today, reported as `{:error, :oversized}` | -| Two resolutions in flight at once | Independent **successes**. Each invocation has its own sender and resolves for itself; the adapter serialises nothing and shares nothing between them, and two answers for the same reference may differ. Concurrency is not a refusal condition, and a custody process that refused concurrent callers would reintroduce exactly the serialisation this decision exists to remove | +| Two resolutions in flight at once | Independent **successes**. Each invocation has its own sender and resolves for itself; the adapter serialises nothing and shares nothing between them, and two answers for the same token may differ. Concurrency is not a refusal condition, and a custody process that refused concurrent callers would reintroduce exactly the serialisation this decision exists to remove | No failure is retried inside the adapter. Whether to attempt again is the coordinator's durable decision under ADR 0018, unchanged. @@ -171,11 +209,13 @@ coordinator's durable decision under ADR 0018, unchanged. - **In the sender.** The minimal credential sender keeps the shape it has today: it is spawned for this one send, it installs its own group leader - sink so no IO request can carry anything out of it, it calls `resolve/2`, - receives the one permitted credential-bearing reply, validates the size - bound, writes the frame itself and reports `:ok` or `{:error, reason}` from - the closed set to the guardian. Its closure holds the reference, never the - resolved value; in the parent the value exists in the custody process and, + sink so no IO request can carry anything out of it, it looks the token up in + the host's routing registry, calls the custody process it names, receives the + one permitted credential-bearing reply, validates the size bound, writes the + frame itself and reports `:ok` or `{:error, reason}` from the closed set to + the guardian — which is supervising it against the invocation deadline + throughout. Its closure holds the token, never the resolved value; in the + parent the value exists in the custody process and, for the duration of one send, in this process's own mailbox and stack, and nowhere else — no guardian state, no exit reason and no crash report can hold it. @@ -234,9 +274,9 @@ coordinator's durable decision under ADR 0018, unchanged. Every case below exists today in `apps/loopex_llm_reqllm/test/credential_plane_test.exs`. Each is re-pointed at -the per-invocation reference — the module's `setup` and the two rotation cases -stop writing the process-wide variable, and each fixture carries its own -credential — and each must hold with its assertion unchanged in meaning: +the per-invocation token — the module's `setup` and the two rotation cases +stop writing the process-wide variable, and each fixture composes its own +custody process and registry row — and each must hold with its assertion unchanged in meaning: | Claim | Case | | --- | --- | @@ -271,8 +311,8 @@ cannot carry over unchanged. The size-bound case in drives the 65,536-byte ceiling, delivers its credential through `System.put_env(Adapter.credential_variable(), …)` in that module's `setup` and again in the case body. Both writes go: the module's fixtures carry their -own credential reference, and the case supplies the 65,536-byte value as that -invocation's reference rather than writing it into the VM. The ceiling it +own custody, and the case has that invocation's custody process hold the +65,536-byte value rather than writing it into the VM. The ceiling it proves, and the refusal above the ceiling, are unchanged. Three proofs are new: @@ -304,12 +344,15 @@ Three proofs are new: captured function. Each route it does not pin is refuted outright. The narrower scan is what lets an environment read return by a name the current expression does not match, which is the drift the case exists to catch. -- **Resolution failures.** One case per row of the failure table above: absent - reference, malformed reference, a resolver module without the callback, each - of the four refusal atoms, a resolver returning a term outside the closed set - (reported `:unavailable`), a resolver silent past the deadline instant - (reported `:timeout`, and asserted **distinct** from every refusal so the - guardian can tell them apart), and a value outside the size bound. Each +- **Resolution failures.** One case per row of the failure table above: + absent token, malformed token, a token with no registry row, a gone + registry, a dead custody process, each of the four refusal atoms, a custody + process returning a term outside the closed set (reported `:unavailable`), a + custody process that blocks past the invocation deadline (the **guardian** + kills the sender and reports `:timeout`, asserted **distinct** from every + refusal so the guardian can tell them apart, and asserted to bound the + invocation whatever the custody process does), and a value outside the size + bound. Each asserts the outcome, its closed-set atom, that no child was spawned where the contract says none is, and that no message but the permitted reply, no exit reason and no crash report carries the resolved value. The @@ -348,22 +391,26 @@ host-facing accessor — the one name an operator configures — and that is wha it should say it is. The neighbouring case `a missing credential is reported before any provider is called` proves the refusal today by deleting the variable from the VM; under this decision it proves the same refusal by -supplying no credential reference with the call, which is the path that +supplying no credential token with the call, which is the path that replaces it. ### Security review The review is an acceptance point of M5 Outcome 6, read by someone other than -the implementer, over the exact diff. It answers: where the reference is held -between the call and the send; that the resolved value has no path into -guardian state, a message, an exit reason, a crash report, an IO request, a -file or the environment; that every row of the failure table refuses without -retaining a copy; that the deadline, cleanup and abandonment paths do not -resurrect one; that a host supplying no reference is refused rather than -falling back to an ambient read; and, on the host side of the boundary, that -each reference implementation reads the operator's variable once, deletes it, -redacts the holding process's state, and hands the adapter a reference that -carries no bytes. Its record is retained with the milestone's evidence. +the implementer, over the exact diff. It answers: that the token is opaque +and carries no credential and no authority; that the routing registry holds +routing only, with no bytes and no material a secret could be derived from; +that the resolved value has no path into guardian state, a message other than +the one permitted reply, an exit reason, a crash report, an IO request, a file +or the environment; that every row of the failure table refuses without +retaining a copy; that the guardian's deadline bounds the whole resolution +whatever a custody process does; that the cleanup and abandonment paths do not +resurrect a value; that loss of custody or registry answers `:unavailable` +rather than reconstructing anything; that a host supplying no token is refused +rather than falling back to an ambient read; and, on the host side of the +boundary, that each reference implementation reads the operator's variable +once, deletes it, redacts its custody process's state, and registers a token +that carries no bytes. Its record is retained with the milestone's evidence. ### Concurrency, as a measurement @@ -391,12 +438,12 @@ child built from the same manifest digest behaves identically; the build manifest is not revised by this decision. The one visible change is host composition: a host that starts a runtime with -this adapter supplies a credential reference with the call and owns the bytes -behind it. The reference CLI, the app-server host, the M5 daemon and the +this adapter passes a credential token with the call and owns both the +registry that routes it and the custody process that holds the bytes. The reference CLI, the app-server host, the M5 daemon and the real-provider lane keep reading `LOOPEX_PROVIDER_API_KEY` where they compose, and delete it there, so an operator's setup is unchanged and the release check's credential frame is unchanged. An embedder that relied on the adapter reading -the environment for it must pass the reference instead; that is the refusal +the environment for it must pass a token instead; that is the refusal path, not a silent fallback, and it is stated in the operator and developer documentation the milestone updates. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 02806e8b7..c74476e50 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -38,16 +38,42 @@ measured the result at M4 closure — that application is the critical path of the fast check, 96% of its time sits in those twelve modules, and no further test change shortens the check while the slot is shared. -**Decide that the credential is a per-invocation input, resolved only inside -the process that writes it to the child's private channel.** The host supplies -the adapter, with each call, a *credential reference*: bounded plain data -naming a host-owned resolver, never the bytes themselves. The adapter resolves -that reference exactly once per invocation, inside the minimal sender process -that writes the credential frame, and only after the child has proved its -nonce, codec version and build manifest digest. The adapter reads no -environment variable for the credential. A call that carries no reference is -refused before any child is spawned, which is the refusal a missing environment -variable produces today. +**Decide that the credential is a per-invocation input, named by an opaque +token and resolved only inside the process that writes it to the child's +private channel.** The host supplies the adapter, with each call, a +*credential token*: an opaque identifier that carries no credential, no +routing and no authority of its own. Behind it the host owns two things the +adapter does not: a **routing registry** that maps a token to a custody +process and holds routing only — never bytes, never anything a secret could be +derived from — and the **custody process** that holds the bytes. The adapter +resolves the token exactly once per invocation, inside the minimal sender +process that writes the credential frame, and only after the child has proved +its nonce, codec version and build manifest digest. The adapter reads no +environment variable for the credential. A call that carries no token is +refused before any child is spawned, which is the refusal a missing +environment variable produces today. + +The token replaces a `{module, term}` reference an earlier draft used; the +maintainer decided that on 2026-09-20 and the companion records why. A value +that named the resolving module carried the host's arrangement through every +copy of the adapter's configuration, and a second provider would have widened +the value rather than added a registry row. An opaque token discloses nothing +and stays the same shape however many credentials sit behind it. + +**The guardian enforces the deadline, and the resolver is not asked to.** The +custody callback takes no deadline. The guardian already owns the invocation +deadline and already supervises the sender, so it bounds the whole resolution +and kills the sender when the instant is reached. An earlier draft handed the +resolver an absolute instant and relied on it to honour one; that is withdrawn +by the same decision, because it made a safety property depend on code the +adapter does not write, and a custody process that simply blocked would have +hung the invocation past its deadline. + +**Losing custody or the registry is a refusal, never a reconstruction.** If +the custody process is gone, the registry has no row, or the registry itself +is gone, resolution answers `:unavailable` and every invocation on that token +refuses the same way until the host recomposes. Nothing rebuilds the secret, +and nothing could: the registry holds no bytes to rebuild it from. **Exactly one credential-bearing transfer exists in the parent, and this pair names it.** A host that keeps the bytes and answers a resolver call has to send @@ -56,17 +82,23 @@ message could never be implemented alongside one. So the rule is a permission with a boundary: the custody process's reply to the sender is the one transfer — bounded, unlogged, never forwarded, never retained after the frame is written — and it is the same class of act as writing the credential frame, -protected the same way ADR 0019 already protects that sender. +protected the same way ADR 0019 already protects that sender. The registry +lookup before it carries no credential, so routing adds no second place a +secret can be seen, and the credential-bearing call is excluded from tracing +by ADR 0030's existing redaction class, which the companion names and M5 +proves. **Everywhere else the boundary is where the adapter's claims stop.** Inside it -— the reference, the sender, the frame, the child — the adapter proves what it +— the token, the sender, the frame, the child — the adapter proves what it says: the value is never in the child's environment, in argv, in the journal, in a public event, a snapshot, a progress item or a diagnostic, in adapter process state, in any message but that one, in an exit reason, a crash report or an IO request, and never written to a file. Outside it, custody belongs to the host and the adapter -proves nothing about it. This pair therefore states the reference -implementations' custody as their own obligation rather than claiming a -property of every host that might supply a resolver. +proves nothing about it beyond the two structural rules it does impose: the +registry holds routing only, and losing custody or the registry answers +`:unavailable` rather than reconstructing anything. This pair therefore states +the reference implementations' custody as their own obligation rather than +claiming a property of every host that might compose a registry. The operator still names the credential once, through the same environment variable, and the reference implementations — the CLI, the app-server host and @@ -108,7 +140,7 @@ the existing bootstrap frame to carry the credential alongside the manifest digest was rejected because the child must prove its identity before it is handed a secret, and that frame is sent before the child has proved anything. Carrying the credential bytes in the per-invocation configuration, rather than -a reference, was rejected because the bytes would then sit in adapter state, +a token, was rejected because the bytes would then sit in adapter state, in the messages that configuration travels in, and in any crash report that prints it — the retention this decision exists to remove. A single adapter-level credential set once at composition was rejected because it is @@ -126,16 +158,20 @@ unchanged in meaning; the parent VM's environment is proved empty of the credential from the completion of composition onward — before, during and after a call; two invocations running at once are proved unable to observe each other's credential; every resolution failure the contract names — absent -reference, refusing resolver, a resolver that does not answer before the -deadline instant, and a value outside the size bound — is proved to refuse -with one of the five closed reason atoms and to leave no retained copy, with -the timeout proved distinguishable from every refusal; two resolutions in +token, malformed token, no registry row, a gone registry, a dead custody +process, a refusing custody process, one that blocks past the invocation +deadline, and a value outside the size bound — is proved to refuse with one of +the five closed reason atoms and to leave no retained copy, with the +guardian's timeout proved distinguishable from every refusal and proved to +bound the invocation whatever the custody process does; two resolutions in flight at once are proved to be independent successes rather than a refusal; -the one permitted credential-bearing reply is proved redacted under a trace -session at the `arguments` level; the adapter's library tree is proved to read +the one permitted credential-bearing reply, and the resolver call that +carries it, are proved excluded from tracing under a trace session at the +`arguments` level; the adapter's library tree is proved to read no environment variable by any route; and a named reviewer reads -the handoff — resolution point, frame ordering, failure paths, the host -reference implementations' custody, and every place a value could be retained +the handoff — the token's opacity, the registry's routing-only contents, +resolution point, frame ordering, failure paths, the host implementations' +custody, and every place a value could be retained — and records the reading with the milestone. The real-provider lane in `bash scripts/check-release.sh` proves the path still reaches a real provider. The concurrency result is a measurement @@ -155,11 +191,12 @@ plane, and in no message but the one reply this pair permits. Two invocations in one VM become independent, so the twelve provider test modules can run concurrently and the fast check stops being pinned by that application. Host composition gains one explicit input and one explicit obligation: a host that -starts a runtime with this adapter says which credential reference the adapter -is to use, instead of relying on the VM's environment being right at call -time, and it owns where the bytes live behind that reference. A host that -supplies no reference gets the adapter's ordinary refusal to dispatch, which -is what a missing environment variable produces today. +starts a runtime with this adapter passes a credential token with the call, +instead of relying on the VM's environment being right at call time, and it +owns both the registry that routes the token and the custody process the +bytes live in. A host that supplies no token gets the adapter's ordinary +refusal to dispatch, which is what a missing environment variable produces +today. Nothing public changes. This is adapter-internal: no Model callback, no public event, snapshot, artifact, wire method or protocol generation, no durable diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index b902a8fe9..4707b854f 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -80,22 +80,26 @@ bounded plain-data contract stay out by the rules that already exclude them. `TYPESAFE_API_KEY` is a **second** provider credential, and this is the one place where this decision constrains an earlier one. [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) -fixes a per-invocation credential reference the host owns and the sender -resolves, and it fixes **one** reference per call, which is right for the one -provider that exists today. A second provider needs one reference per -provider: a call names which credential is wanted, and a host composing both -supplies two references. ADR 0034 does not define that, and this pair does not -pretend it does — the generalisation is **a prerequisite change to ADR 0034**, -made by its own amendment or by an ADR superseding it, proposed with the -milestone that accepts this decision. - -Its shape is small and is named here only so the later change is cheap to -scope: the option becomes a map keyed by provider rather than one -`{resolver_module, reference_term}` pair, resolution picks the entry for the -provider being invoked, and nothing about custody, rotation, the deadline -instant or the closed reason set changes. Until that change is accepted and -landed, this decision cannot be implemented, and nothing in M5 anticipates -it. +fixes a per-invocation credential **token**, opaque to the adapter, routed by +a host-owned registry to the custody process that holds the bytes — and it +fixes **one** token per call, which is right for the one provider that exists +today. A second provider needs one token per provider: a call says which +credential is wanted, and a host composing both registers two tokens. ADR 0034 +does not define that, and this pair does not pretend it does — the +generalisation is **a prerequisite change to ADR 0034**, made by its own +amendment or by an ADR superseding it, proposed with the milestone that +accepts this decision. + +The token shape makes that change smaller than it would otherwise have been, +which is worth recording because it is the practical consequence of the +maintainer's decision of 2026-09-20. The registry already maps token to +custody process, so a second provider is a second row and a second token, not +a wider value: the option becomes one token per provider being invoked, +resolution looks up the row for the token that call carries, and nothing about +the registry's routing-only contents, custody, rotation, the +guardian-enforced deadline or the closed reason set changes. Until that change +is accepted and landed, this decision cannot be implemented, and nothing in M5 +anticipates it. ### Seams, in the order they are worth doing @@ -180,7 +184,8 @@ executor protocol and every durable record are untouched. A runtime with no evaluation configured is byte-for-byte the runtime that exists today. The one compatibility effect is on host composition, and it arrives with the prerequisite amendment to ADR 0034 rather than with this pair: a credential -reference becomes one per provider instead of one per call. +token becomes one per provider instead of one per call, and a host registers a +second routing row. Rollback is removing the evaluation. Every seam is an input, so a host that stops asking decides as it did before by the same path; a journaled answer diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md index 4c3b3d466..25fd87d75 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -107,11 +107,13 @@ Three consequences are real costs rather than benefits, and are stated as such. It is a **second provider credential**, `TYPESAFE_API_KEY` alongside the model credential, which means [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept)'s -per-invocation credential reference has to become **one per provider** rather -than one per call. ADR 0034 fixes one reference per call and does not define -that, so the generalisation is a prerequisite amendment to it, proposed with -the milestone that accepts this decision; this one cannot be implemented -before that lands. The **state sent to the model** is bounded, redacted, provenance-typed +per-invocation credential **token** has to become one per provider rather than +one per call. ADR 0034 fixes one token per call and does not define that, so +the generalisation is a prerequisite amendment to it, proposed with the +milestone that accepts this decision; this one cannot be implemented before +that lands. Because a token is routed through a host-owned registry, a second +provider is a second row and a second token rather than a wider value, which +is what keeps that amendment small. The **state sent to the model** is bounded, redacted, provenance-typed data the runtime already holds, under the same context-admission discipline that governs anything else staged for a provider; nothing new becomes sendable. And **latency and price are unmeasured** until the first real call; diff --git a/docs/adr/README.md b/docs/adr/README.md index 0ff4b2d90..356262568 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -182,5 +182,5 @@ decides that a typed decision model — one that returns probabilities and confidences rather than text — may be an input to a host's policy decision and a journaled plain-data fact, and may never be the decision. It depends on 0034 and on a prerequisite amendment to it, because a second provider needs one -credential reference per provider where 0034 fixes one per call. No part of it +credential token per provider where 0034 fixes one per call. No part of it runs inside M5. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 17387c71b..e4718f36a 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -20,7 +20,7 @@ decision named only in prose declares nothing. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or either core change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by a `{resolver_module, reference_term}` reference the host owns, resolved only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; the resolver's owner, custody, rotation, deadline bounding and every failure outcome; no environment read anywhere in the adapter's library tree and the launcher's enumeration deleted rather than relocated, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by an opaque token, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; custody and registry ownership, rotation, the guardian-enforced deadline, `:unavailable` on lost custody or registry with no reconstruction, and every failure outcome; no environment read anywhere in the adapter's library tree and the launcher's enumeration deleted rather than relocated, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | ADR 0031 decides one thing, the `0.2.0` local-adapter selection and its documented limits. It prescribes no successor engine, experiment or migration; @@ -75,7 +75,7 @@ to the integrator, who resolves them rather than either writer: | Shared surface | Why both reach it | | --- | --- | -| Host composition — `apps/loopex_composition`, `apps/loopex_app_server/lib/loopex_app_server/host.ex`, `apps/loopex_cli` | The credential item changes how every host supplies a credential reference and deletes the operator's variable; the daemon *is* a new host composed the same way, and `host.ex:221` is where the variable is read today | +| Host composition — `apps/loopex_composition`, `apps/loopex_app_server/lib/loopex_app_server/host.ex`, `apps/loopex_cli` | The credential item makes every host compose a routing registry and a custody process, pass a token with the call and delete the operator's variable; the daemon *is* a new host composed the same way, and `host.ex:221` is where the variable is read today | | The integration scripts — `scripts/check-release.sh` and its fixtures | Workstream 5 selects the real-provider lane; the daemon workstreams add `loopex_daemon` to `release_apps` and the Linux cross-uid case | | Provider and credential documentation under `docs/operator/` and `docs/developer/` | Workstream 5 adds the operator credential sentence and the host-composition note; workstream 6 rewrites the same pages for the daemon | | Closure evidence — `docs/evidence/M5-closure-runs.md` and `docs/evidence/README.md` | Every workstream's runs, the security review and the demonstration are retained on one page | @@ -252,7 +252,7 @@ Outcome 6 changes no public surface. The `Loopex.Model` callbacks, the private provider codec's version and frame kinds, the build manifest and ADR 0019's process topology are all unchanged. Its one compatibility effect is on host composition: an embedder that relied on the adapter reading the environment -for it supplies a credential reference with the call instead, and gets the +for it passes a credential token with the call instead, over a registry and custody it composes, and gets the adapter's ordinary refusal to dispatch rather than a silent fallback if it does not. @@ -395,16 +395,19 @@ answer, which takes an attaching or durable side effect to ask a question — one in-memory lease record and one admission check, one resident window and eviction policy, one per-connection output buffer, one session index with bounded pages, three CLI commands and -the Node client's socket mode. Outcome 6 adds exactly one abstraction, the -one-callback `Loopex.LLM.ReqLLM.CredentialResolver` behaviour, because the -reference has to travel in configuration that is copied between processes and -may be printed by a crash report, so it must be plain boundary data and a -closure cannot be: it unifies the three reference hosts that hold a credential -today — the CLI, the app-server host and the daemon — and any embedder that -holds one elsewhere. Beside it, each reference host gains one holding process -for the one value it already reads. Nothing else: the change otherwise moves -where one value is resolved and deletes two environment reads from the call -path. +the Node client's socket mode. Outcome 6 adds exactly one indirection, the +credential token and the host-owned routing registry it is resolved through, +because the value that travels in adapter configuration is copied between +processes and may be printed by a crash report: an opaque token is the +smallest thing that can travel there while disclosing neither the credential +nor the host's arrangement of it, and a registry row is what a host adds for a +second credential instead of widening the value. It unifies the three +reference hosts that hold a credential today — the CLI, the app-server host +and the daemon — and any embedder that holds one elsewhere. Beside it, each +reference host gains one custody process for the one value it already reads +and one registry row for it. Nothing else: the change otherwise moves where +one value is resolved and deletes the credential environment read from the +call path. Nothing else. No lease, transport, byte limit or residency policy in core; no second loop, event dispatcher, cancellation path or protocol codec; no diff --git a/docs/plans/M5.md b/docs/plans/M5.md index b3b9f9c58..6a1a1aa6d 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -53,7 +53,7 @@ transport, no second loop and no new durable command. | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the host-owned resolver contract is exact about custody, rotation, bounding and every failure, and each refusal is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's read of the whole parent environment is deleted outright, replaced by a fixed closed removal list, so no code path reads the environment to build one. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the per-invocation input is an opaque token, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's read of the whole parent environment is deleted outright, replaced by a fixed closed removal list, so no code path reads the environment to build one. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -217,8 +217,8 @@ than failing a startup that never reads it. The credential handoff to a provider child moves from the process-wide environment variable the adapter reads inside each call to the per-invocation private channel the launcher already opens for the nonce and the build -manifest. The host supplies a credential reference with each call and owns -where the bytes live behind it; the reference hosts — the CLI, the app-server +manifest. The host passes an opaque credential token with each call and owns +both the registry that routes it and the custody process the bytes live in; the reference hosts — the CLI, the app-server host and the daemon — read the operator's variable once where they compose and delete it there, so the claim about the parent VM's environment is stated from the completion of composition onward rather than for all time. ADR 0034 fixes @@ -331,7 +331,7 @@ prerequisite, no M5 outcome waits on it, and M5 runs no part of it. An earlier draft admitted one bounded experiment inside the provider workstream; that is withdrawn on 2026-09-20, because it would have put a real call to a second provider, needing a second credential the release check does not carry -and a per-provider credential reference ADR 0034 does not define, inside a +and a per-provider credential token ADR 0034 does not define, inside a check M5 is required to pass. A milestone whose required check depends on a decision that has not been accepted is not a complete set. ADR 0035 stays Proposed and wholly deferred. @@ -448,7 +448,7 @@ stopping the daemon and using the M4 foreground server and CLI on the same root, which nothing durable prevents, because no journal record depends on the lease, the session index or any residency state. Outcome 6 changes no public or durable surface at all; its one visible effect is that a host composing -this adapter supplies a credential reference with the call. +this adapter passes a credential token with the call and composes a routing registry and a custody process behind it. Technical depth: [Compatibility mechanics](M5-technical.md#technical-plan-compatibility). @@ -496,7 +496,8 @@ lease — and the companion's rejoin order says where each part goes. 5. **The credential handoff and the provider dependency.** ADR 0034's change to the provider adapter and to the host composition sites that read the operator's variable, the re-pointed credential-plane proofs, the new proofs - of the resolver contract and its failures, the deletion of the launcher's + of the token, the routing registry, the guardian-enforced deadline and + every failure, the deletion of the launcher's environment enumeration, its own security review by someone other than its implementer, and the measured effect on the provider suite once its modules can run concurrently. This workstream also carries one bounded dependency From b3af02e0812ec571c16231c69b300e9cfcb08590 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:14:50 -0700 Subject: [PATCH 030/585] adr(M5): keep ADR 0019's launch-time environment enumeration Maintainer decision 3B, recorded at the third audit on 2026-09-20. It reverses last round's removal. ProviderLauncher keeps its launch-time System.get_env/0 enumeration, exactly where it is, solely for ADR 0019 scrubbing: the first spawned image is /usr/bin/env itself, whose environment env -i does not clear, so every name present at that launch has to be removed by name. A fixed closed list cannot do it, because the set present is not knowable before the launch -- which is why ADR 0019 reads it then. ProviderBridge, which holds the sender and the whole credential path, reads no environment variable at all. What this reverses, recorded in the pair with its reason: last round deleted the enumeration in favour of a fixed closed removal list, and the round before moved the snapshot to composition. Both are withdrawn. The composition snapshot claimed an immutability ADR 0019 never gave; the fixed list silently gave up removing names nobody listed. Outcome 6 and ADR 0034 now prohibit CREDENTIAL environment reads in the call path rather than every environment read. The drift proof's allowlist is exact: provider_bridge.ex -> [], provider_launcher.ex -> the arity-zero enumeration only, provider_worker.ex -> its two non-secret crash-dump names, [] everywhere else. Because the launcher's read survives, the case carries a second obligation a count cannot meet: it asserts the read's *use* -- the enumeration's result flows only into the Port's removal list, every name is mapped to false, none is compared against credential_variable/0, and no value reaches the sender, the frame or any caller. The Port {:env, ...} merge measurement is retained as a recorded fact, since it is a fact about the platform and is now the reason the enumeration exists, rather than the rationale for a design that is gone. --- ...andoff-over-bootstrap-channel-technical.md | 144 ++++++++++-------- ...edential-handoff-over-bootstrap-channel.md | 39 +++-- docs/plans/M5-technical.md | 6 +- docs/plans/M5.md | 13 +- 4 files changed, 116 insertions(+), 86 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 0cbf2fb8c..d0a5afeca 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -219,52 +219,50 @@ coordinator's durable decision under ADR 0018, unchanged. for the duration of one send, in this process's own mailbox and stack, and nowhere else — no guardian state, no exit reason and no crash report can hold it. -- **In the parent's environment.** The adapter performs no environment read - for the credential by any route. `Loopex.LLM.ReqLLM.credential_variable/0` - remains as the one name the *host* reads when it composes a runtime — the - reference CLI at start, and the real-provider lane when it names the - variable in its own failure message — and the host deletes that name once it - has read it. `ProviderLauncher.spawn_environment/0`'s enumeration of the live - environment — `System.get_env/0` on every launch — is **deleted**, and - nothing replaces it: no enumeration at launch, and none at composition - either. The launcher passes the Port a fixed, closed list instead — the - `@excluded` names removed unconditionally, plus the explicit downstream - names — which is a constant in the source, so no code path reads the - environment to build it. The fixed `env -i` argument lists stay as they are. - - An earlier draft moved the snapshot to composition. That is withdrawn on - 2026-09-20, because it quietly weakened an accepted decision. ADR 0019's - companion requires that the trusted host "must not mutate unrelated launch - environment **during this operation**" — a constraint on one launch, not a - promise of immutability for the runtime's lifetime. A snapshot taken at - composition and reused would let a name introduced afterwards reach a later - launch's first image, which is a property ADR 0019 never gave away. Deleting - the enumeration rather than relocating it needs no amendment to ADR 0019. - - What the fixed list preserves exactly is ADR 0019's actual guarantee, which - its companion states as "Explicit credential removals are unconditional": no - credential name and no loader or startup-injection name reaches the first - image, whether or not it was present. What it does not preserve — stated - rather than implied — is the clearing of *unlisted* names from the - `/usr/bin/env` image's own environment block in the microseconds before it - execs. Three things bound that. `/usr/bin/env` acts on none of them; `env -i` - clears every one of them for the exec'd child, so the M0 child-environment - conformance case, which asserts about the worker and not the first image, is - untouched; and the block is readable only by the same user who can already - read the parent VM's own environment, which is the case ADR 0019 explicitly - declines to defend — "This is not a new guarantee against hostile same-VM - code". After this decision the credential is not in the parent's environment - at all, so the enumeration's protective value against the credential is zero - by then. - - One mechanical note for whoever writes the change, measured rather than - assumed: `Port.open`'s `{:env, …}` option **merges** into the inherited - environment; it does not replace it. A probe on this toolchain spawned - `/usr/bin/env` with `{:env, [{~c"PATH", …}]}` and the first image still - received all 67 of the parent's names, including a planted sentinel. So - "pass an exact environment and receive exactly that set" is not reachable - through the Port option, and the closed unconditional removal list above is - what is actually implementable for the same purpose. +- **In the parent's environment.** The adapter performs no *credential* + environment read by any route. That is the property this decision owns, and + it is narrower than "no environment read at all" on purpose. + `Loopex.LLM.ReqLLM.credential_variable/0` remains as the one name the *host* + reads when it composes a runtime — the reference CLI at start, and the + real-provider lane when it names the variable in its own failure message — + and the host deletes that name once it has read it. `ProviderBridge`, which + holds the sender and the whole credential path, reads no environment + variable at all. + + `ProviderLauncher.spawn_environment/0` keeps its launch-time + `System.get_env/0` enumeration, and keeps it exactly where it is. The + maintainer decided this on 2026-09-20, reversing an earlier draft of this + pair that deleted the enumeration in favour of a fixed closed removal list, + and an earlier one still that moved the snapshot to composition. Both are + withdrawn, and the reason is that the enumeration is not part of the + credential plane at all — it is ADR 0019's scrubbing, and ADR 0019 is + accepted. + + What it does: at each launch it reads the live environment so the Port can + remove every name in it, plus the unconditional `@excluded` credential and + loader names, from the first spawned image. That image is `/usr/bin/env` + itself, whose environment `env -i` does not clear, so without the + enumeration an unlisted name introduced after some earlier snapshot would + reach it. A fixed list cannot have that property, because the set of names + present is not known until the launch. Reading it at launch, per launch, is + what makes ADR 0019's first-image scrubbing true rather than approximately + true, and it needs no amendment to ADR 0019 because it is ADR 0019's own + design left alone. + + The line this decision draws is therefore between *a credential read* and + *an environment read*. The launcher's read is never consulted for a + credential: it does not look up the credential name, it does not pass a + value anywhere, and every name it finds it uses only to remove. The proof + below asserts that directly rather than inferring it from the absence of + reads. + + One measurement is retained from the withdrawn design, because it is a fact + about the platform rather than about the design: `Port.open`'s `{:env, …}` + option **merges** into the inherited environment and does not replace it. A + probe on this toolchain spawned `/usr/bin/env` with + `{:env, [{~c"PATH", …}]}` and the first image still received all 67 of the + parent's names, including a planted sentinel. That is why removal is name by + name, and therefore why the enumeration exists. - **In the child.** Unchanged: the child receives the credential on the socket and nowhere else. Its environment at entry is the fixed `PATH`, `LANG`, `LC_ALL` and the two crash-dump suppressions, and ADR 0029's bounded @@ -332,18 +330,38 @@ Three proofs are new: exact `System.get_env` arguments per library file, including `"provider_bridge.ex" -> ["\"LOOPEX_PROVIDER_API_KEY\""]` and `"provider_launcher.ex" -> [""]`, the arity-zero enumeration. That case must - survive, strengthened rather than deleted, in two ways. Both of those - expected lists become `[]`, leaving only `provider_worker.ex`'s two - non-secret crash-dump names, so the case then proves that no file in the - adapter's library tree reads any environment variable at all except those - two. And its scan is widened from one regular expression over - `System.get_env(...)` to every route by which an environment read can be - written: `System.get_env/0` and `/1`, `System.fetch_env/1` and - `fetch_env!/1`, `System.get_env/2`, `:os.getenv/0`, `/1` and `/2`, - `:os.env/0`, and indirect application of any of them through `apply/3` or a - captured function. Each route it does not pin is refuted outright. The - narrower scan is what lets an environment read return by a name the current - expression does not match, which is the drift the case exists to catch. + survive, strengthened rather than deleted, and the allowlist it ends with is + exact: + + | File | Expected reads | Why | + | --- | --- | --- | + | `provider_bridge.ex` | `[]` | The credential path reads no environment variable at all; this is the read the decision removes | + | `provider_launcher.ex` | the arity-zero enumeration, and only that | ADR 0019's first-image scrubbing, which stays. It is not a credential read | + | `provider_worker.ex` | its two non-secret crash-dump names | Unchanged | + | every other file | `[]` | Unchanged | + + So the claim the case proves is "**no credential** environment read in the + adapter's library tree", not "no environment read at all". The maintainer's + decision of 2026-09-20 draws it there, and the earlier draft that expected + `[]` for the launcher too is withdrawn with the deletion it belonged to. + + Because the launcher's read survives, the case carries one more obligation + than a count: it must show that read is **never consulted for a credential**. + Pinning an argument list cannot show that on its own, so the case asserts + the use as well as the read — the enumeration's result flows only into the + Port's removal list, every name it yields is mapped to `false`, no name it + yields is compared against `credential_variable/0`, and no value it yields + reaches the sender, the frame or any caller. A refactor that started reading + a credential out of that enumeration would fail there. + + Its scan is widened from one regular expression over `System.get_env(...)` + to every route by which an environment read can be written: + `System.get_env/0` and `/1`, `System.fetch_env/1` and `fetch_env!/1`, + `System.get_env/2`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect + application of any of them through `apply/3` or a captured function. Each + route the allowlist does not name is refuted outright. The narrow scan is + what lets an environment read return by a name the current expression does + not match, which is the drift the case exists to catch. - **Resolution failures.** One case per row of the failure table above: absent token, malformed token, a token with no registry row, a gone registry, a dead custody process, each of the four refusal atoms, a custody @@ -371,8 +389,8 @@ Three proofs are new: reads the variable exactly once, deletes it from the VM's environment, and that the holding process's `format_status/1` redacts its state under a forced crash report. The adapter's own tree keeps only what is the adapter's - to prove: that it reads no environment variable and that the resolver - contract behaves. + to prove: that it reads no environment variable for a credential and that + the token and resolution contract behaves. The first two, the failure cases and the custody cases belong in `credential_plane_test.exs` beside the cases they generalise; the drift case @@ -383,9 +401,9 @@ Two details of that case matter to whoever writes the change. The literal `provider_bridge.ex:401`, inside the credential sender, while `credential_variable/0` and its module attribute live in `req_llm.ex:49` and `:149-150`; only the first disappears. The arity-zero enumeration the case -also pins lives in `provider_launcher.ex:23-27`, and it does not disappear — -it moves to composition, so the file that holds it afterwards is a host -composition site rather than the adapter's call path. So `adapter_test.exs:50`'s +also pins lives in `provider_launcher.ex:23-27`, and it stays exactly there, +doing exactly what it does now: ADR 0019's first-image scrubbing, per launch. +So `adapter_test.exs:50`'s `assert variable == "LOOPEX_PROVIDER_API_KEY"` is, afterwards, a pin on the host-facing accessor — the one name an operator configures — and that is what it should say it is. The neighbouring case `a missing credential is reported diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index c74476e50..174e49369 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -111,20 +111,27 @@ Outcome 6's claim is stated at that boundary: a claim that the variable is never set at all would contradict the way an operator supplies a secret to a process they start. -One enumeration goes with it. The launcher reads the whole parent environment -on every launch, to clear it name by name from the first spawned image. That -read is deleted outright rather than relocated: the launcher passes a fixed, -closed removal list — the credential and loader names it already removes -unconditionally — so no code path reads the environment to build it, at launch -or anywhere else. Moving the read to composition was considered and withdrawn, -because ADR 0019 constrains the host only *during one launch* and a snapshot -reused across launches would claim an immutability that decision never gave. -What the fixed list keeps is ADR 0019's actual guarantee, that credential and -loader names never reach the first image; what it gives up, and this pair says -so, is clearing unlisted names from one short-lived `/usr/bin/env` image that -acts on none of them, whose child is cleared by `env -i` regardless, and whose -environment block is readable only by the user who can already read the parent -VM's. +**One environment read stays, and this pair says why.** The launcher reads the +whole parent environment on every launch, so the Port can clear it name by +name from the first spawned image — `/usr/bin/env` itself, whose environment +`env -i` does not clear. That read is ADR 0019's scrubbing, not part of the +credential plane, and the maintainer decided on 2026-09-20 that it stays +exactly where it is. + +Two earlier drafts of this pair touched it and both are withdrawn. Moving the +snapshot to composition was withdrawn because ADR 0019 constrains the host +only *during one launch*, so a snapshot reused across launches would claim an +immutability that decision never gave. Replacing it with a fixed closed +removal list was withdrawn because a fixed list cannot remove a name nobody +knew was there: the set present at a launch is not knowable before it, which +is precisely why ADR 0019 reads it then. Neither weakening is worth taking, +and leaving the read alone needs no amendment to ADR 0019. + +So the prohibition this decision makes is narrower and exact: no **credential** +environment read in the adapter's call path. `ProviderBridge`, which holds the +sender and the whole credential path, reads no environment variable at all. +The launcher's read remains and is proved never to be consulted for a +credential — every name it yields is used only to remove that name. **Alternatives rejected.** Keeping the environment variable and buying the speed by sharding the provider suite across test VMs was rejected: it is @@ -168,7 +175,9 @@ flight at once are proved to be independent successes rather than a refusal; the one permitted credential-bearing reply, and the resolver call that carries it, are proved excluded from tracing under a trace session at the `arguments` level; the adapter's library tree is proved to read -no environment variable by any route; and a named reviewer reads +no environment variable for a credential by any route, with the launcher's +ADR 0019 scrubbing read proved never to be consulted for one; and a named +reviewer reads the handoff — the token's opacity, the registry's routing-only contents, resolution point, frame ordering, failure paths, the host implementations' custody, and every place a value could be retained diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index e4718f36a..35cefd3d4 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -20,7 +20,7 @@ decision named only in prose declares nothing. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or either core change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by an opaque token, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; custody and registry ownership, rotation, the guardian-enforced deadline, `:unavailable` on lost custody or registry with no reconstruction, and every failure outcome; no environment read anywhere in the adapter's library tree and the launcher's enumeration deleted rather than relocated, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by an opaque token, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; custody and registry ownership, rotation, the guardian-enforced deadline, `:unavailable` on lost custody or registry with no reconstruction, and every failure outcome; no credential environment read anywhere in the adapter's library tree, with `provider_bridge` reading none at all and the launcher's ADR 0019 scrubbing enumeration kept exactly where it is, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | ADR 0031 decides one thing, the `0.2.0` local-adapter selection and its documented limits. It prescribes no successor engine, experiment or migration; @@ -43,7 +43,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | -| `loopex_llm_reqllm` | The credential handoff, its sender, the resolver behaviour it declares, the launcher's fixed closed removal list that replaces its environment enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | +| `loopex_llm_reqllm` | The credential handoff, its sender, the token it accepts, the launcher's unchanged ADR 0019 scrubbing enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | **Rejoin order.** Prerequisite decisions first. Then the new application with @@ -130,7 +130,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers plain data for a session that exists and for one that does not, from a fresh process against a real root, and is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown IDs. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened twice: empty expected lists for both `provider_bridge.ex` and `provider_launcher.ex`, leaving only `provider_worker.ex`'s two non-secret crash-dump names, and a scan widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything 1.24 makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything 1.24 makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 6a1a1aa6d..465a9bbda 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -53,7 +53,7 @@ transport, no second loop and no new durable command. | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the per-invocation input is an opaque token, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable at all except the child's two non-secret crash-dump names, by every route such a read can be written; and the launcher's read of the whole parent environment is deleted outright, replaced by a fixed closed removal list, so no code path reads the environment to build one. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the per-invocation input is an opaque token, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -221,7 +221,11 @@ manifest. The host passes an opaque credential token with each call and owns both the registry that routes it and the custody process the bytes live in; the reference hosts — the CLI, the app-server host and the daemon — read the operator's variable once where they compose and delete it there, so the claim about the parent VM's environment is stated from -the completion of composition onward rather than for all time. ADR 0034 fixes +the completion of composition onward rather than for all time. The claim is +about *credential* reads: `ProviderLauncher` keeps reading the live +environment at each launch, because that read is ADR 0019's scrubbing of the +first spawned image and removing it would weaken an accepted decision, and the +proof shows it is never consulted for a credential. ADR 0034 fixes the reference's shape, the resolver's owner, when it is resolved, how rotation behaves, what bounds it, and what every failure does. The maintainer set this as an M5 outcome on 2026-09-19 for two reasons. A credential that must sit in the parent VM's environment for the @@ -349,7 +353,7 @@ implementation that depends on it, not before unrelated work. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence and the operator root-retirement procedure documented; a daemon-grade adapter and any migration are left open for a separate decision and prescribed nowhere | 1, 5 | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by a host-owned reference and resolved only inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the reference's shape, the resolver's owner, custody, rotation, bounding and every failure are exact; the adapter reads no environment variable for it and the launcher's enumeration of the parent environment is deleted rather than relocated | 6 | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by an opaque token, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | Three accepted decisions remain load-bearing and are not reopened: M4's ADR 0023 fixes the protocol M5's generation 2 extends, M4's ADR 0030 fixes the @@ -497,8 +501,7 @@ lease — and the companion's rejoin order says where each part goes. to the provider adapter and to the host composition sites that read the operator's variable, the re-pointed credential-plane proofs, the new proofs of the token, the routing registry, the guardian-enforced deadline and - every failure, the deletion of the launcher's - environment enumeration, its own security review by someone other than its + every failure, its own security review by someone other than its implementer, and the measured effect on the provider suite once its modules can run concurrently. This workstream also carries one bounded dependency item: `req_llm` moves from `~> 1.17.1` to `~> 1.24` in From 6ca90be2219bb3d9784954c74ab4aef0dfb827a8 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:15:27 -0700 Subject: [PATCH 031/585] plan(M5): pin the req_llm upgrade to ~> 1.24.0 as explicit M5 scope Maintainer decision 4B, recorded at the third audit on 2026-09-20. The upgrade stays in workstream 5 as explicit M5 scope rather than a convenience, and the pin is stated as `~> 1.24.0` everywhere it appears -- not `~> 1.24` -- so the version reviewed is the version built against and a later minor cannot arrive unreviewed. It is separate from ADR 0035 and not conditional on it: that decision is deferred, no part of it runs in M5, and the upgrade stands on its own dependency reasoning whatever happens to it. It adds no M5 call path, and it carries its own dependency review: changelog reviewed across the intervening releases, the version floor unchanged, the adapter and conformance suites green, and the existing real-provider case at closure run against it. ADR 0035 is re-read for consistency and now says the same: `~> 1.24.0` is M5 scope for its own reasons, separate from that decision and not conditional on it. --- ...ision-models-as-policy-inputs-technical.md | 7 +-- docs/plans/M5-technical.md | 2 +- docs/plans/M5.md | 49 ++++++++++++------- 3 files changed, 35 insertions(+), 23 deletions(-) diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 4707b854f..04186e1f0 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -117,7 +117,7 @@ order, because each earlier one is the cheaper proof of the same invariant. ### Nothing here runs inside M5 An earlier draft admitted one piece early: an offline scorer in M5's release -check that would call the real endpoint to prove the 1.24 API and take the +check that would call the real endpoint to prove the `1.24.0` API and take the first latency and price measurement. That is withdrawn on 2026-09-20. The reason is not caution about the scorer itself, which really would have @@ -132,8 +132,9 @@ complete set, whatever the call does. So the first real call, and with it the first latency and price measurement, belongs to the milestone that accepts this decision. M5's move to `req_llm` -1.24 happens for its own dependency reasons and adds no call path: nothing in -M5 calls anything 1.24 makes newly reachable. +`~> 1.24.0` is explicit M5 scope for its own dependency reasons, separate from +this decision and not conditional on it, and adds no call path: nothing in M5 +calls anything `1.24.0` makes newly reachable. ### Evidence diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 35cefd3d4..d2efa63c3 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,7 +130,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers plain data for a session that exists and for one that does not, from a fresh process against a real root, and is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown IDs. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24` lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything 1.24 makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 465a9bbda..f471bdccd 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -53,7 +53,7 @@ transport, no second loop and no new durable command. | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the per-invocation input is an opaque token, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `1.24` in the same workstream, on the ordinary dependency evidence. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the per-invocation input is an opaque token, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -321,7 +321,7 @@ changes where a credential is resolved and nothing about what a child may do with it: no new credential scope, no credential store, vault or rotation service beyond each reference host holding the one value it already reads at composition, no change to the `Loopex.Model` callbacks or to ADR 0019's -process topology. The `req_llm` move to `1.24` is an ordinary dependency +process topology. The `req_llm` move to `~> 1.24.0` is an ordinary dependency change and adds no dependency, no adapter capability and no provider surface. Those capabilities retain their vision barriers and require their own evidence. @@ -503,24 +503,35 @@ lease — and the companion's rejoin order says where each part goes. of the token, the routing registry, the guardian-enforced deadline and every failure, its own security review by someone other than its implementer, and the measured effect on the provider suite once its modules - can run concurrently. This workstream also carries one bounded dependency - item: `req_llm` moves from `~> 1.17.1` to `~> 1.24` in - `apps/loopex_llm_reqllm/mix.exs` and `mix.lock`. Its M5-specific reason is - stated rather than left implicit: the maintainer's direction of 2026-09-20 - is that the milestone after M5 will accommodate the typesafe.ai model, that - work needs 1.24, and taking a seven-release dependency step inside M5 — - where the adapter and streaming-conformance suites and the existing - real-provider case at closure are already exercised against it — keeps the - later milestone's cost to its own decision rather than bundling a large - dependency move into it. It is an ordinary dependency decision, so it lands - as its own reviewed change, naming the version floor, the reviewed - changelog diff across the intervening releases, the adapter and - streaming-conformance suites green, and the existing real-provider case at - closure run against it. It is sequenced before the credential change where both + can run concurrently. + + This workstream also carries one bounded dependency item, which is + **explicit M5 scope** rather than a convenience: `req_llm` moves from + `~> 1.17.1` to `~> 1.24.0` in `apps/loopex_llm_reqllm/mix.exs` and + `mix.lock`. The pin is `~> 1.24.0`, not `~> 1.24`, so the version reviewed + is the version built against and a later minor cannot arrive unreviewed. + + Its M5-specific reason is stated rather than left implicit: the + maintainer's direction of 2026-09-20 is that the milestone after M5 will + accommodate the typesafe.ai model, that work needs `1.24.0`, and taking a + seven-release dependency step inside M5 — where the adapter and + streaming-conformance suites and the existing real-provider case at closure + already exercise it — keeps the later milestone's cost to its own decision + rather than bundling a large dependency move into it. + + It is separate from + [ADR 0035](../adr/0035-typed-decision-models-as-policy-inputs.md#concept) + and not conditional on it: that decision is deferred, no part of it runs in + M5, and the upgrade stands on its own dependency reasoning whatever happens + to it. It is an ordinary dependency decision, so it lands as its own + reviewed change carrying its own dependency review: the version floor, the + reviewed changelog diff across the intervening releases, the adapter and + conformance suites green, and the existing real-provider case at closure + run against it. It is sequenced before the credential change where both touch the adapter, so the credential proofs are written once against the - upgraded library rather than twice. The upgrade adds no call path in M5: - nothing in the milestone calls anything 1.24 makes newly reachable. It - touches no daemon application code, + upgraded library rather than twice. It adds no M5 call path: nothing in the + milestone calls anything `1.24.0` makes newly reachable. It touches no + daemon application code, and no daemon workstream touches the adapter's library tree — but it is not file-disjoint from them: host composition, the integration scripts, the provider pages and the closure evidence page are reached by both, and the From fcf6665cea088bc067378421dc14608b97ac6674 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:17:02 -0700 Subject: [PATCH 032/585] adr(M5): write out command-ID recovery and correct what core fences Maintainer ADR dispositions relayed with the decisions round. ADR 0032 now writes the command-identity recovery out as a seven-step sequence with a table, rather than gesturing at it: the client replays session.create with its original command_id, the daemon forwards it, core returns the historical result and so the session ID, the client holds the ID for the first time, the daemon validates it with the read-only existence query, records the missing directory entry, and control is then acquired and the session driven. Steps five and six are what turn a recovery into a repair. Its witness injects the exact cut and asserts exactly one session in the root, the returned ID equal to the committed one, the directory entry present afterwards, the session listed, and a later prompt landing on the same session rather than a second one. ADR 0033 loses a claim that was simply untrue. It said core would fence a forgotten admission by the writer epoch. Core knows nothing of that epoch: session_coordinator.ex fences on the Store's {owner_epoch, owner_incarnation_id} pair under ADR 0006 and on runtime control's post-commit fence admitting the exact generation and owner pair, plus command identity for idempotency -- all of which answer which coordinator owner may commit, not which client may drive. The writer epoch is a daemon-owned value on a daemon-owned wire, checked by the daemon before it forwards anything. The "defence in depth" sentence goes with it: the daemon-fatal rule for a lease owner's failure now stands on its own, which is the honest position, because nothing else prevents a successor's grant from racing a forgotten admission. Acquisition calls the read-only existence operation rather than attach or resume, as decision 1A already established. ADR 0035 stays Proposed and wholly deferred, and the plan now says once that the req_llm upgrade neither accepts nor partially implements it. ADRs 0019 and 0030 are stated as Accepted and unchanged, with no M5 document asking for a change to either. --- ...tachment-residency-and-replay-technical.md | 36 +++++++++++++++---- ...controller-lease-and-takeover-technical.md | 34 +++++++++++++----- ...edential-handoff-over-bootstrap-channel.md | 4 +-- docs/plans/M5-technical.md | 4 +-- docs/plans/M5.md | 18 ++++++---- 5 files changed, 71 insertions(+), 25 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index bc389a1b4..f8d9bdbb3 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -208,13 +208,35 @@ durable record and no Store read by the daemon: about the index is consulted to decide existence, which is why an index that is incomplete is not a correctness problem, and the daemon still reads no Store internals. -2. **A client that never saw the session ID recovers by command identity.** - At the cut where the Store committed the creation and the process died - before the reply, the client may hold no ID at all. It is not lost: the - create command's `command_id` is durable and re-presenting it returns the - historical result rather than creating a second session — the idempotency - the session directory and the resume path already rely on. That is the - named route, and the operator page states it. +2. **A client that never saw the session ID recovers by command identity, and + the sequence is written out here rather than left as a gesture.** At the + cut where the Store committed the creation and the process died before the + reply, the client holds no session ID at all — only the `command_id` it + chose for its own `session.create`. Every step below uses something the + client already has or something already durable: + + | Step | Who acts | What happens | + | --- | --- | --- | + | 1 | Client | Reconnects to the daemon and re-presents `session.create` with **the same `command_id`** it used before. It knows no session ID, so it cannot ask for one | + | 2 | Daemon | Forwards it as an ordinary create. It does not consult the index, which by construction may not hold this session | + | 3 | Core | Recognises the command identity as already resolved and returns the **historical result** — the same session ID it committed before — rather than creating a second session. This is the command idempotency the resume path already relies on, not a new mechanism | + | 4 | Client | Now holds the session ID for the first time | + | 5 | Daemon | Validates durable existence with the read-only existence query on that ID, which answers yes because the Store committed it in the first place | + | 6 | Daemon | Records the directory entry it is missing, so every later `session.list` shows the session. If that write fails, step 3 of this procedure applies: the client is told, the session stays usable, and the record is retried next time | + | 7 | Client | Acquires control and attaches in either order, and drives the session normally | + + Steps 5 and 6 are what turn a recovery into a repair: the session is not + merely reachable once, it stops being missing. A client that *does* still + hold the session ID skips steps 1 to 4 and enters at step 5. + + **Its witness.** One case injects the exact cut — Store commit of the + create followed by process death before the directory write and before the + reply — then, from a client that never received the session ID, replays + `session.create` with the original `command_id` and asserts: exactly one + session exists in the root, the returned ID equals the committed one, the + existence query answers yes for it, the directory entry is present + afterwards, the session appears in `session.list`, and a prompt sent after + acquiring control lands on the same session rather than a second one. 3. **Recording can fail, and says so.** If writing the directory entry fails during activation, the failure is reported to the client that triggered it, as an explicit warning that this session will not appear in `session.list` diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index e83c49109..699d8396c 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -25,9 +25,17 @@ not across a restart of the daemon, which is the only restart that exists because a lease owner's failure takes the daemon with it. Clients treat the epoch as opaque and compare it only for equality. The daemon incarnation is a fresh opaque identifier generated at each daemon start and reported by `daemon.status` as a -diagnostic; it confers nothing and is not part of the epoch. It is a daemon -fact: core session epochs, owner incarnations and receipts are unchanged and -remain the commit-authority fence. +diagnostic; it confers nothing and is not part of the epoch. + +The writer epoch is a **daemon** fact and stays one. Core never receives it, +never stores it and never checks it; the daemon checks it before forwarding a +mutation and core is handed an ordinary command afterwards. Core's own +fences are untouched and unrelated: the Store's `{owner_epoch, +owner_incarnation_id}` pair under ADR 0006, runtime control's post-commit +fence admitting the exact generation and owner pair, and command identity for +idempotency. Those remain the commit-authority fence, and they answer a +different question — which coordinator owner may commit — than the writer +epoch does, which is which client may drive. One owner process per session serializes every lease read, grant, renewal, release and expiry transition with that session's mutation-admission handoff, @@ -48,11 +56,21 @@ So the session-owner tree is supervised `one_for_all` up to the listener: an owner's failure closes the listener and every connection, the daemon exits, and the daemon restarts with no lease anywhere, no connection, and no session activated. No successor acquire exists to be granted wrongly, because -no connection survives to make one. Core fences the forgotten admission by -epoch regardless of any of this — a fresh epoch is minted at the next grant -and nothing from before can match — so the daemon-side rule is defence in -depth over a fence that already holds, not the only thing standing between a -crash and interleaving. +no connection survives to make one. + +That rule stands on its own, and this pair does not lean on core to help it. +An earlier draft said core would fence the forgotten admission by epoch +regardless, making the daemon-fatal rule defence in depth. That is wrong and +is withdrawn on the maintainer's decision of 2026-09-20: **core knows nothing +of the writer epoch.** The epoch is a daemon-owned value on a daemon-owned +wire, checked by the daemon before it forwards anything, and core never sees +it. What core does fence is its own: the Store's `{owner_epoch, +owner_incarnation_id}` pair under ADR 0006, runtime control's post-commit +fence admitting the exact generation and owner pair, and command identity for +idempotency. Those protect against a stale *coordinator owner*, not against a +stale *controller*, which is exactly the gap this ADR exists to fill. So the +only thing preventing a successor's grant from racing a forgotten admission +is the daemon rule above, and it has to be absolute for that reason. Retaining the in-flight set in a survivor was the alternative and was rejected: whichever process held it would then be the process whose failure diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 174e49369..a765e3566 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -103,8 +103,8 @@ claiming a property of every host that might compose a registry. The operator still names the credential once, through the same environment variable, and the reference implementations — the CLI, the app-server host and the M5 daemon — read it exactly once where they compose the runtime and delete -it from the VM's environment in the same step, holding the bytes behind the -resolver from then on. The variable is a configuration input consumed at +it from the VM's environment in the same step, holding the bytes in their +custody process and registering its token from then on. The variable is a configuration input consumed at composition, not a live transport for every call, and from the moment composition completes the parent VM's environment carries no credential. M5 Outcome 6's claim is stated at that boundary: a claim that the variable is diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d2efa63c3..3ec696604 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -125,12 +125,12 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through the create command's durable `command_id` returning the historical result rather than a second session; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID, the existence query confirms it, the daemon records the missing directory entry, and control is then acquired and the session driven — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the directory entry present afterwards, the session listed, and a later prompt landing on the same session rather than a second one; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers plain data for a session that exists and for one that does not, from a fresh process against a real root, and is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown IDs. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent reference, malformed reference, a resolver module without the callback, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a resolver silent past the deadline instant reported as `:timeout` and asserted distinct from every refusal, so the guardian can tell a refusal from a silence. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — is proved redacted under a trace session at the `arguments` level, which shows placeholders and no credential bytes. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; it supplies the oversized value as that invocation's reference instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent token, malformed token, a token with no registry row, a gone registry, a dead custody process, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — and the resolver call that carries it are proved excluded from tracing under a trace session at the `arguments` level, which shows placeholders and no credential bytes; the registry lookup before it is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index f471bdccd..6fc477934 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -338,7 +338,9 @@ second provider, needing a second credential the release check does not carry and a per-provider credential token ADR 0034 does not define, inside a check M5 is required to pass. A milestone whose required check depends on a decision that has not been accepted is not a complete set. ADR 0035 stays -Proposed and wholly deferred. +Proposed and wholly deferred, and the `req_llm` upgrade neither accepts it +nor partially implements it: that upgrade is M5 scope on its own dependency +reasoning and would stand unchanged if ADR 0035 were never accepted. Technical depth: [Deferral acceptance points](M5-technical.md#technical-plan-prerequisites). @@ -355,11 +357,15 @@ implementation that depends on it, not before unrelated work. | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by an opaque token, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | -Three accepted decisions remain load-bearing and are not reopened: M4's -ADR 0023 fixes the protocol M5's generation 2 extends, M4's ADR 0030 fixes the -closed telemetry inventory M5 emits nothing outside of and would have to amend -to add a daemon event, and the post-M2 ADR 0019 fixes the provider process -topology ADR 0034 refines. +Three accepted decisions remain load-bearing, are not reopened, and are left +**Accepted and unchanged** by everything M5 does: M4's ADR 0023 fixes the +protocol M5's generation 2 extends; M4's ADR 0030 fixes the closed telemetry +inventory M5 emits nothing outside of and the trace scope M5 claims no witness +beyond, so M5 proposes no amendment to it; and the post-M2 ADR 0019 fixes the +provider process topology and the first-image environment scrubbing, both of +which ADR 0034 refines around rather than alters — its launch-time enumeration +stays exactly where ADR 0019 put it. No M5 document asks for a change to +either 0019 or 0030. ### How Each Outcome Is Verified From ac7ae989e57919c6725c7d759172792d01520ffc Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:18:45 -0700 Subject: [PATCH 033/585] plan(M5): correct the set's authority dates and attributions The third audit reported incorrect 2026-09-20 authority dates across the set. Every date in docs/plans/M5*.md and docs/adr/0031-0035 was audited against the maintainer's timeline: Outcome 6 and the credential handoff on 2026-09-19; the ReqLLM direction and the four decisions on 2026-09-20; ADRs 0031-0033 proposed and revised 2026-09-14; the plan pair rewritten 2026-09-20. Six dates were wrong. ADR 0031's withdrawal of its successor half, its rejection of deciding a successor engine ahead of evidence, and its rejection of a survivable capacity refusal all read 2026-09-19; they belong to the 2026-09-20 rewrite. ADR 0032's rejection of Store-level enumeration and an atomic inventory transaction read 2026-09-19 for the same reason. ADR 0035's Date and its "read from source on" line read 2026-09-19, but that pair exists because of the typesafe/ReqLLM direction the maintainer dates 2026-09-20. Four attributions were wrong in kind rather than in date. ADR 0031's successor-half withdrawal, ADR 0033's rejection of restarting a failed lease owner beneath live sockets, and its companion's matching sentence read as undated decisions when they were independent-review findings; they now say so. ADR 0035's withdrawal of the M5 experiment and the plan's matching sentence read as findings when the maintainer decided them; they now say that. A progress entry for 2026-09-20 records the revision itself and the four decisions in a table with what each displaced, so the durable record shows which changes were repairs and which were decisions. It also states that ADR 0031 carries no decision from this round, that ADR 0035 stays Proposed and wholly deferred with decision 4 neither accepting nor partially implementing it, and that ADRs 0019 and 0030 remain Accepted and unchanged. A duplicated passage about what core fences, introduced by the previous commit, is reduced to one statement. --- ...mon-grade-store-selection-and-migration.md | 8 +++--- ...-daemon-attachment-residency-and-replay.md | 2 +- ...controller-lease-and-takeover-technical.md | 25 ++++++++----------- ...aboration-controller-lease-and-takeover.md | 3 ++- ...ision-models-as-policy-inputs-technical.md | 5 ++-- ...-typed-decision-models-as-policy-inputs.md | 2 +- docs/plans/M5.md | 23 ++++++++++++++++- 7 files changed, 44 insertions(+), 24 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 55ba676c4..2c87eb04a 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -62,8 +62,8 @@ makes the durable-service claim truthful without adding an engine. successor milestone's engine candidates, its experiment procedure and its migration, then said that half bound nothing — while its companion said acceptance binds the pair. Those cannot both be true, and an ADR that carries -a non-binding half is not one decision. The successor half is withdrawn on -2026-09-19. A daemon-grade adapter behind the unchanged private Store ports +a non-binding half is not one decision. The successor half was withdrawn in +this pair's revision of 2026-09-20, on an independent review's finding. A daemon-grade adapter behind the unchanged private Store ports remains an open question, and the questions it must answer — which engine, on what measured evidence, with what migration, what interrupted-import recovery, what backup and restore, and which binary is the oldest reader of the new root @@ -82,7 +82,7 @@ inside M5 was rejected because it doubles the milestone's evidence — a new engine, its fault matrix, its migration and its rollback — without adding a proved capability to the durable-service question M5 exists to answer. Deciding the successor's engine and migration procedure here, ahead of the -experiments that would inform them, was rejected on 2026-09-19: a decision +experiments that would inform them, was rejected on 2026-09-20: a decision recorded before its evidence is a preference, and one that has to call itself non-binding to be tolerable is not a decision at all. Raising or removing the local log's 256 MiB capacity to postpone retirement @@ -90,7 +90,7 @@ was rejected because a silently growing log trades a truthful refusal for an unbounded replay at open. Changing the local adapter so that a capacity refusal is definite and survivable — answered as a plain refusal without terminating the Store, so a daemon could keep its observers attached and stop -in an orderly way — was rejected for M5 on 2026-09-19. It is a change to the +in an orderly way — was rejected for M5 on 2026-09-20. It is a change to the Store's own behaviour at the one point where that behaviour is most load-bearing: today every append error is commit-ambiguous, and separating one error class from the rest means proving, through the shared conformance suite diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 7de35a1a1..adb14b1ce 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -142,7 +142,7 @@ was rejected the same day because an observer without filesystem access to the root would have no way to discover sessions. Rebuilding an authoritative inventory by enumerating the Store, and writing the inventory entry inside the session-creating transaction so it is crash-atomic with the commit, were both -rejected on 2026-09-19: each is a change to the Store port or to the local +rejected on 2026-09-20: each is a change to the Store port or to the local adapter's transaction shape, and both are exactly what M5's selection of the unchanged adapter declines to buy. Activating every recorded session at daemon start was rejected the same day: the local adapter replays a full log diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 699d8396c..ac29a6986 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -40,8 +40,8 @@ epoch does, which is which client may drive. One owner process per session serializes every lease read, grant, renewal, release and expiry transition with that session's mutation-admission handoff, so a takeover cannot pass a mutation whose holder check has already started -but whose core admission is unresolved; that admission first resolves or -remains fenced. +but whose core admission is unresolved; that admission first resolves, or the +daemon's own holder-and-epoch check refuses it before it ever reaches core. **A lease owner's failure is fatal to that daemon instance, deliberately.** The owner holds the session's in-flight admission set in its own memory, and @@ -49,7 +49,8 @@ that set is the whole basis of the expiry rule below: a takeover is granted only when it is empty. An owner that dies takes the set with it, so a restarted owner cannot know whether an admission is still on its way into core. An earlier draft had the daemon restart the owner and carry on with its -sockets intact; that is withdrawn on 2026-09-20, because a successor acquire +sockets intact; that was withdrawn on 2026-09-20, on an independent review's +finding, because a successor acquire could then be granted while a forgotten admission was still able to settle. So the session-owner tree is supervised `one_for_all` up to the listener: an @@ -60,17 +61,13 @@ no connection survives to make one. That rule stands on its own, and this pair does not lean on core to help it. An earlier draft said core would fence the forgotten admission by epoch -regardless, making the daemon-fatal rule defence in depth. That is wrong and -is withdrawn on the maintainer's decision of 2026-09-20: **core knows nothing -of the writer epoch.** The epoch is a daemon-owned value on a daemon-owned -wire, checked by the daemon before it forwards anything, and core never sees -it. What core does fence is its own: the Store's `{owner_epoch, -owner_incarnation_id}` pair under ADR 0006, runtime control's post-commit -fence admitting the exact generation and owner pair, and command identity for -idempotency. Those protect against a stale *coordinator owner*, not against a -stale *controller*, which is exactly the gap this ADR exists to fill. So the -only thing preventing a successor's grant from racing a forgotten admission -is the daemon rule above, and it has to be absolute for that reason. +regardless, making the daemon-fatal rule defence in depth. The maintainer +withdrew that on 2026-09-20 because it was not true: core never sees the +writer epoch, as the lease record above sets out, and the fences core does +have protect against a stale *coordinator owner* rather than a stale +*controller* — which is the gap this ADR exists to fill. So the daemon rule +is the only thing preventing a successor's grant from racing a forgotten +admission, and it has to be absolute for that reason. Retaining the in-flight set in a survivor was the alternative and was rejected: whichever process held it would then be the process whose failure diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index 385329c90..c5a41aeb5 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -90,7 +90,8 @@ requires the holder connection, so durability could only preserve a counter nothing needs. A counter-based epoch scoped to the daemon incarnation was rejected on 2026-09-14 because a lease-owner restart under the same incarnation would mint values already issued. Restarting a failed lease owner -beneath live sockets was rejected on 2026-09-20: the owner holds the session's +beneath live sockets was rejected on 2026-09-20, on an independent review's +finding: the owner holds the session's in-flight admission set, a takeover waits on that set being empty, and a restarted owner cannot know what it has forgotten. Retaining the set in a survivor moves the same window one process up; making it survivable at all diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 04186e1f0..6b3fef18d 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -10,7 +10,7 @@ Concept: [Context and decision](0035-typed-decision-models-as-policy-inputs.md#c ### What the model is, exactly -Everything below was read from `req_llm` 1.24.0's own source on 2026-09-19, +Everything below was read from `req_llm` 1.24.0's own source on 2026-09-20, not from a description of it. - `ReqLLM.Evaluation.evaluate/4`, reached as `ReqLLM.evaluate/4`, takes a model @@ -118,7 +118,8 @@ order, because each earlier one is the cheaper proof of the same invariant. An earlier draft admitted one piece early: an offline scorer in M5's release check that would call the real endpoint to prove the `1.24.0` API and take the -first latency and price measurement. That is withdrawn on 2026-09-20. +first latency and price measurement. The maintainer withdrew it on +2026-09-20. The reason is not caution about the scorer itself, which really would have touched no live path. It is that the release check is a check M5 is *required* diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md index 25fd87d75..7bdbd8568 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -4,7 +4,7 @@ Technical depth: [Typed decision model mechanics](0035-typed-decision-models-as-policy-inputs-technical.md#technical-depth). - **Status:** Proposed -- **Date:** 2026-09-19 +- **Date:** 2026-09-20 - **Decision owner:** Maintainer - **Supersedes:** nothing; it refines where a host may get the *inputs* to the ADR 0009 policy decision, and changes nothing about who makes it diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 6fc477934..d38b0d1cf 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -333,7 +333,7 @@ confidences rather than text — may be an input to a host's policy decision and a journaled plain-data fact, never the decision itself. It is not an M5 prerequisite, no M5 outcome waits on it, and M5 runs no part of it. An earlier draft admitted one bounded experiment inside the provider workstream; -that is withdrawn on 2026-09-20, because it would have put a real call to a +the maintainer withdrew that on 2026-09-20, because it would have put a real call to a second provider, needing a second credential the release check does not carry and a per-provider credential token ADR 0034 does not define, inside a check M5 is required to pass. A milestone whose required check depends on a @@ -628,6 +628,27 @@ and the two check commands and the maintainer decide. The purpose, the outcomes and the scope are unchanged by that rewrite except for Outcome 6, which the maintainer added on the same day. +**Revision of 2026-09-20, and four decisions.** This pair and its four +proposed ADRs were revised across three independent reviews on 2026-09-20. +Most of that was repair — claims the code did not support, obligations no +check could meet, and contradictions between a concept file and its +companion — and it changed no outcome's purpose. Four things were decisions +rather than repairs, and the maintainer recorded them at the third review; +each is written into the document it governs, together with the alternative +it displaced and why: + +| # | Decision | What it displaced | +| --- | --- | --- | +| 1 | Core gains a read-only session-existence query alongside concurrent attachments, and the daemon validates existence with it | Learning existence by calling `attach` or `resume`, which takes an attaching or durable side effect to ask a question | +| 2 | The credential is an opaque token routed by a host-owned registry that holds routing only, resolved from a host-owned custody process, with the guardian enforcing the deadline and `:unavailable` on loss with no reconstruction | A `{module, term}` reference that carried the host's arrangement through adapter configuration, and a resolver trusted to honour a deadline it was handed | +| 3 | `ProviderLauncher` keeps its launch-time environment enumeration for ADR 0019 scrubbing; the prohibition narrows to credential reads | Deleting the enumeration for a fixed closed removal list, and before that moving the snapshot to composition — both of which weakened an accepted decision | +| 4 | The `req_llm` upgrade is explicit M5 scope pinned at `~> 1.24.0`, separate from ADR 0035 and adding no M5 call path | Leaving the pin loose at `~> 1.24`, and running one bounded ADR 0035 experiment inside M5's required release check | + +ADR 0031 carries no decision from this round and is unchanged by it. ADR 0035 +remains Proposed and wholly deferred; decision 4 neither accepts nor partially +implements it. ADRs 0019 and 0030 remain Accepted and unchanged, and nothing +in this pair asks for an amendment to either. + ## Governance Records | Decision | Authority | Authority evidence | Bound bytes | From 79bda2af3cab7ee9a13f3db4242113dcf1a7248b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:47:02 -0700 Subject: [PATCH 034/585] plan(M5): fix the daemon's operator contracts and shutdown sequence Fourth-review items 1 and 2. The set described a daemon that starts and said almost nothing about running one. Item 1, verified first: docs/operator/coding-sessions.md:368 documents the released `loopex sessions [--state-root DIR]` as an offline directory read. It is preserved unchanged -- no flag an operator types today acquires a new meaning -- and the live listing is a separate explicit form, `loopex sessions --daemon `, with --limit, --after, a visible index_full warning on stderr and --status. `loopex daemon` gets root and socket selection defaulting to /daemon/daemon.sock, one readiness line on stdout printed only after the marker is held and the socket is bound and permission-checked, everything else on stderr, SIGTERM/SIGINT as the stop, and exit 0 for an operator stop or non-zero with a named reason class. `loopex attach` gets observer and controller roles, takeover, cursor reconnect and exit codes. There is no daemon.stop method on the wire: ending every other client's session residency is not authority a connection carries. Each contract names the operator page row that documents it. Item 2 writes the lifecycle out as a sequence. Startup ordering with its failure classes; shutdown in six steps -- refuse new connections and admissions, drain admitted work within the composed cleanup grace and settle the rest through the paths core already commits to (ADR 0016's configured cancellation sequence with its bounds, ADR 0012's truthful outcome_unknown, and commit_unknown left fenced for the ADR 0006/0018 reconciliation) so nothing admitted is abandoned silently, a final frame naming the reason, socket unlink, then the Store stopped last because that is when its terminate/2 releases the marker, then exit. Abrupt death runs none of it and is safe for the reasons the durability rules already give. Witnesses added for idle shutdown, in-flight shutdown, fatal exit and readiness ordering, all on real operating-system processes. --- docs/plans/M5-technical.md | 194 ++++++++++++++++++++++++++++++++++++- docs/plans/M5.md | 36 +++++-- 2 files changed, 220 insertions(+), 10 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 3ec696604..47ff0f7a2 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -125,7 +125,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID, the existence query confirms it, the daemon records the missing directory entry, and control is then acquired and the session driven — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the directory entry present afterwards, the session listed, and a later prompt landing on the same session rather than a second one; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID, the existence query confirms it, the daemon records the missing directory entry, and control is then acquired and the session driven — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the directory entry present afterwards, the session listed, and a later prompt landing on the same session rather than a second one; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers plain data for a session that exists and for one that does not, from a fresh process against a real root, and is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown IDs. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -313,9 +313,10 @@ the classic backend exposes neither the named option nor the raw one, while over the socket backend with its handle reachable satisfies this; no library is added either way. -Supply `loopex daemon`, `loopex attach` and `loopex sessions` in the reference -CLI, and extend the client in `clients/node` to connect over the socket, to -follow as an observer and to take over. It stays a plain client with no build +Supply `loopex daemon`, `loopex attach` and a live form of `loopex sessions` +in the reference CLI, on the contracts below, and extend the client in +`clients/node` to connect over the socket, to follow as an observer and to +take over. It stays a plain client with no build step, package manifest or dependency, as the maintainer decided for M4 on 2026-09-15. The Node version stays pinned in `scripts/fixtures/m4/client-toolchain.txt` and `scripts/check-release.sh` @@ -377,6 +378,191 @@ annotated, `v0.2.0^{commit}` is the reviewed integration commit and reachable from `main`, and `git show :VERSION` is exactly `0.2.0`. Do not move the tag, and publish no package, binary, installer or service unit. + +### The Daemon's Operator Contracts + +Concept: [Scope](M5.md#concept-plan-scope). + +A daemon is not finished when it starts. These are the contracts M5 owes an +operator for running one, and each names the operator page that documents it. +The reference CLI is where they land; the Node client implements only the +attach side. + +#### `loopex sessions`: the released form is preserved, the live form is new + +`loopex sessions [--state-root DIR]` is a released command, documented in +`docs/operator/coding-sessions.md`, and it reads the state root's session +directory with no runtime and no daemon. M5 does not change it: an operator +whose daemon is stopped, or who never ran one, keeps exactly the behaviour +`0.1.0` gave them, and no flag they type today acquires a new meaning. + +The live listing is a **separate form**, `loopex sessions --daemon `, +which connects and issues `session.list`. It is additive and explicit — +without `--daemon` nothing reaches a socket — and it presents: + +- one page per request, with `--limit` (1 to 256, default 256) and + `--after `, printing the continuation cursor when the daemon + returns one, so paging is the operator's step and never a silent loop; +- the four fields the index carries — session identity, recorded placement + identity, `residency`, `controlled` — and nothing it does not have; +- `index_full` as a visible warning on `stderr` when the daemon sets it: *the + daemon's index is full, so this listing may omit sessions this root + contains*. A warning rather than a failure, because the page it accompanies + is still true as far as it goes; +- `--status`, which issues `daemon.status` and prints placement identity, + daemon incarnation, socket path, attachment, activation and index counts + against their limits, and uptime. + +Exit status: `0` for a page printed, including an empty one; non-zero with the +reason on `stderr` when the socket cannot be reached, the peer check refuses, +or the daemon refuses the arguments. + +#### `loopex daemon`: starting, readiness, stopping + +**Selection.** `loopex daemon [--state-root DIR] [--socket PATH]`. The root +resolves as every other command resolves it. The socket defaults to +`/daemon/daemon.sock` in the `0700` daemon-owned subdirectory; a +`--socket` beyond the platform's derived `sun_path` bound is refused at start +with `socket_path_too_long` before anything else happens. + +**Readiness.** Exactly one line on `stdout`, and nothing else on that stream: + +```text +loopex daemon ready root= socket= incarnation= +``` + +It is printed **only after** all of: the Store is open and its writer marker +held, the `0700` subdirectory and `0600` socket exist with their ownership and +mode read back and verified, and the listener is accepting. A process manager +that waits for that line is waiting for a daemon that can actually serve, +which is why it is printed there and not earlier; anything sooner would invite +a client to connect to a socket the daemon has not finished checking. Every +diagnostic, warning and failure goes to `stderr`, so `stdout` carries the +readiness line alone and stays machine-readable. + +**Stopping.** `SIGTERM` and `SIGINT` both begin the orderly shutdown below. +There is no `daemon.stop` method on the wire: stopping is an operator act +against the process, and a client-issued stop would let one connection end +every other client's session residency, which is authority the socket does not +carry and this milestone does not grant. + +**Exit status.** `0` when an orderly shutdown completes, whatever the sessions +were doing. Non-zero, with one reason line on `stderr`, for every fatal exit, +naming its class rather than a stack: `store_writer_active`, +`store_writer_unverifiable`, `store_log_too_large`, `socket_path_too_long`, +`socket_permission_unverified`, `session_index_too_large`, `store_lost`, and +`supervision_fault` for the daemon-fatal rules ADR 0032 and ADR 0033 define. + +#### `loopex attach`: driving and watching + +`loopex attach --daemon [--observe] [--take-over]`. + +- Default is **controller**: acquire control, then attach, then drive. If + another connection holds the lease the command refuses with `control_held`, + naming the epoch that holds it, rather than waiting. +- `--observe` attaches without acquiring and never sends a mutation. An + observer that tries is refused by the daemon, not by the client, which is + where the rule belongs. +- `--take-over` asks for control on a lease that is released or expired and + waits while an in-flight admission settles, as ADR 0033's linearization + requires. It never forces a live holder off. +- **Cursor and reconnect.** The client remembers the last event cursor it + emitted and, on transport loss, reconnects at it, deduplicating by session + ID, event sequence and event ID. Delivery is contiguous and at least once, + so a duplicate at the seam is expected and a gap is a defect. + +Exit status: `0` when the session reaches a terminal outcome or the operator +detaches; non-zero on a refusal, or on a transport loss reconnection could not +repair, with the reason class on `stderr`. + +#### Where these are documented + +| Contract | Operator page | +| --- | --- | +| `loopex sessions` offline, unchanged | `docs/operator/coding-sessions.md`, its existing command rows, reviewed unchanged | +| `loopex sessions --daemon`, `--limit`, `--after`, `--status`, `index_full` | `docs/operator/daemon.md`, listing section | +| `loopex daemon` selection, readiness line, signals, exit classes | `docs/operator/daemon.md`, running section | +| `loopex attach` roles, takeover, reconnect, exit classes | `docs/operator/daemon.md`, attaching section | + + +### Daemon Lifecycle and Orderly Shutdown + +Concept: [Scope](M5.md#concept-plan-scope). + +Outcome 1 requires that an orderly stop and an abrupt death both leave only +what the journal proves. That is a claim about a sequence, so the sequence is +written out rather than left implied by the words "foreground process". + +**Startup, in order.** Resolve root and socket path; open the Store and +acquire the writer marker, with `recover_stale_writer: true` and the three +holder outcomes ADR 0032 fixes; read the session directory and build the +index, refusing at the recorded-entry bound; create the `0700` subdirectory +and bind the `0600` socket, then read back and verify ownership and mode; +begin accepting; print the readiness line. A failure at any step exits +non-zero with that step's reason class and touches nothing after it — in +particular, a daemon that does not hold the marker never reads, unlinks or +binds the socket path. + +**Shutdown, in order.** `SIGTERM` or `SIGINT` starts it, and from that instant: + +1. **Refuse new work.** The listener stops accepting, so a new connection is + refused rather than queued, and the daemon admits no new mutation on any + existing connection. Queries and attach-state reads still answer, because + they change nothing and a client deserves to learn what is happening. +2. **Drain what was already admitted.** Work in flight — a provider call, a + dispatched tool effect, an unresolved mutation — gets the composed cleanup + grace to finish on its own. Nothing here is a new mechanism, and the plan + names the existing ones rather than gesturing at "cleanup": a running + effect enters the configured cancellation sequence ADR 0016 fixes, with its + bounds, and terminates as `cancelled` or with the truthful + `outcome_unknown` ADR 0012 admits; a mutation whose commit is ambiguous is + left as `commit_unknown` and fenced, to be resolved by the reconciliation + ADR 0006 and ADR 0018 already define when the root is next opened. **No + admitted work is abandoned silently**, which is the property this step + exists for. +3. **Tell every client, then close.** Each connection receives one final frame + naming the reason — the operator stop, or the fatal class — and the daemon + then closes it. A client learns why its session went away from the wire + rather than from a socket that simply stopped answering. +4. **Unlink the socket.** The path is removed, so no later client connects to + a dead endpoint and the next daemon binds cleanly rather than inheriting a + stale file. +5. **Stop the Store, last.** The marker is released by the Store's own + `terminate/2` at that moment — see the marker invariant in ADR 0031 — so + stopping the Store last is exactly what makes the marker outlive every + session operation that might still have needed it. Only after it returns + does the daemon exit. +6. **Exit.** `0` for an operator stop; non-zero with the reason class on + `stderr` for a fatal one, which runs the same steps 1 to 5 and differs only + in what it tells clients and what it returns. + +**An abrupt death** — `SIGKILL`, power loss — runs none of this, and is safe +for the reasons the durability rules already give: nothing the journal does +not hold was ever promised, the marker left behind is reclaimed by the next +daemon's verified stale-writer recovery, and the socket file is a stale path +the next marker holder removes. + +**Witnesses**, all on real operating-system processes: + +- **Idle shutdown.** A daemon with sessions activated and no work in flight + receives `SIGTERM`, writes nothing further to `stdout`, closes every + connection with the stop reason, unlinks the socket, releases the marker and + exits `0`; the foreground server then opens the same root immediately, which + is what proves the marker was actually released. +- **In-flight shutdown.** A daemon with a dispatched tool effect and an + unresolved mutation receives `SIGTERM`; the effect terminates through the + configured cancellation sequence with a truthful terminal, the ambiguous + mutation is left as `commit_unknown` rather than reported committed, every + client receives the stop reason, and the exit is still `0`. Reopening the + root afterwards resolves that transaction to exactly one outcome. +- **Fatal exit.** Store loss under a live listener closes the listener and + every connection with `store_lost`, unlinks the socket, and exits non-zero + with that class on `stderr`. +- **Readiness ordering.** A client that connects the instant the readiness + line appears is served; no readiness line is printed when the marker is + held elsewhere, the socket permission check fails, or the index bound is + exceeded, and each of those exits non-zero with its own class. + ### Proportional Minimalism Budget diff --git a/docs/plans/M5.md b/docs/plans/M5.md index d38b0d1cf..abc721021 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -48,7 +48,7 @@ transport, no second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root: an activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, drains admitted work within the cleanup grace and settles the rest through cancellation bounds and fenced `commit_unknown` rather than abandoning it, tells every client the reason, unlinks the socket and stops the Store last, exiting `0`; a fatal exit runs the same sequence and returns a named reason class. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -272,9 +272,30 @@ under the ordinary umask, so requiring `0700` there would reject every existing M4 root and contradict the rollback claim — and second by a fail-closed peer-credential read whose mechanism is named per platform because no portable one exists: the supported OTP 29 Darwin toolchain offers no `peercred` socket option at all. -A foreign peer is refused before initialize; the daemon never runs as a service-manager unit by itself, and the -documented launch is a foreground command an operator or their service manager -runs. +A foreign peer is refused before initialize. + +The daemon never runs as a service-manager unit by itself: the documented +launch is a foreground command an operator or their service manager runs. That +makes its operator contracts part of the milestone rather than an afterthought, +so M5 fixes them. `loopex daemon` selects a root and a socket, prints exactly +one readiness line on standard output — and only once the marker is held and +the socket is bound and permission-checked — sends everything else to standard +error, stops on `SIGTERM` or `SIGINT`, and exits `0` for an operator stop or +non-zero with a named reason class for a fatal one. There is no stop method on +the wire, because ending every client's session residency is not authority a +connection carries. `loopex attach` drives or observes, takes over an expired +or released lease, and reconnects at its cursor. The released offline +`loopex sessions` is unchanged, and the live listing is a separate explicit +form of it. + +An orderly stop is a sequence, not a word, so the plan writes it out: refuse +new connections and new admissions, drain what was already admitted within the +composed cleanup grace and settle the rest through the paths core already +commits to — the configured cancellation sequence with its bounds, and +`commit_unknown` left fenced for reconciliation — never abandoning admitted +work silently, tell every client the reason on the wire, unlink the socket, +and stop the Store last, which is when its `terminate/2` releases the marker. +The technical companion fixes each contract and each step exactly. At the closure candidate, every tracked file under `docs/operator/` and `docs/developer/` is read for consistency with M5, for relevance, links and @@ -493,8 +514,11 @@ lease — and the companion's rejoin order says where each part goes. activation refusal for a session this composition cannot serve, shutdown on store loss, capacity as one such loss, and reopening under the foreground server after an orderly stop. -3. **The socket transport.** The listener, its owner-only peer check and path - bound, ADR 0023's framing and records reused, generation 2's schema and +3. **The socket transport and the daemon's operator contracts.** The + listener, its owner-only peer check and path bound, the startup ordering + and its readiness line, signal handling and the orderly-shutdown sequence, + the exit-status classes, `loopex daemon`, `loopex attach` and the live form + of `loopex sessions` beside the unchanged offline one, ADR 0023's framing and records reused, generation 2's schema and vectors beside generation 1's, negotiation and the generation-1-only refusal, and the differential conformance that the facade, the foreground server and the socket produce the same durable identities. From 6ad215ef8082246d53bbf44c63a37e99e6cfa900 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:54:07 -0700 Subject: [PATCH 035/585] adr(M5): explicit lease release only, coordinator loss fatal Fourth-review items 3, 5 and 7. Item 3: ADR 0033 said an orderly connection close released the lease while an abrupt loss waited for expiry. Over a Unix-domain socket the daemon sees EOF either way, so the rule was not executable. Early release is now bound to a successful explicit session.release_control; every transport loss -- close, EOF, kill -- waits for expiry. The three are required as separate witnesses, because only one of them is early and the transport cannot tell the other two apart. Item 5, verified in code: Loopex.Runtime.Control monitors each coordinator and, at control.ex:821-822, an :active coordinator going down releases the dispatcher fence and returns without altering the session entry -- so the entry stays with a dead pid and no notification reaches the daemon. Combined with residency being set active once and never back, a dead coordinator would have left the index asserting `active` about a session that has none. Losing an activated session's coordinator is therefore fatal to the daemon instance, the same one_for_all rule ADR 0033 gives a lease owner's loss, and the activation count starts again because the ceiling counts per lifetime. The alternative is recorded as rejected: a lifecycle notification, an index transition and a recovery route back to active would be deciding when a session may leave active, which is deciding when its coordinator may stop -- the core deactivation operation M5 does not have, wearing a different name. Item 7: M5-technical still said an owner restart leaves the session uncontrolled, contradicting ADR 0033's daemon-fatal rule. The restart wording is deleted and the fatal rule carried in the plan. --- ...tachment-residency-and-replay-technical.md | 41 +++++++++++++++---- ...-daemon-attachment-residency-and-replay.md | 4 ++ ...controller-lease-and-takeover-technical.md | 22 ++++++++-- ...aboration-controller-lease-and-takeover.md | 11 +++-- docs/plans/M5-technical.md | 10 +++-- docs/plans/M5.md | 6 ++- 6 files changed, 75 insertions(+), 19 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index f8d9bdbb3..691a72555 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -167,15 +167,38 @@ the daemon itself owns or reads once: - `residency`, a daemon fact, set to `active` at activation and never set back within a daemon's lifetime, because activation is one-way; - `controlled`, a daemon fact, updated on every lease grant, release and - expiry by the same per-session owner ADR 0033 gives those transitions — - **and on that owner's failure**, which is not a transition the owner can - record for itself. Under ADR 0033 a lease owner's failure is fatal to the - daemon instance, so both fields are reconstructed by the restart rather than - repaired in place: after it, every session is `dormant` and `controlled` is - false, which is exactly true of a daemon that has activated nothing and - granted nothing. A coordinator that fails is core's to supervise; the daemon - does not invent a `residency` value for it, and a client learns of it by - attaching, where core answers authoritatively. + expiry by the same per-session owner ADR 0033 gives those transitions. + +**Keeping `residency` honest costs a rule, and this pair pays it.** `active` +means the daemon holds a live coordinator. The index sets it once and never +back. Put those together and a coordinator that dies would leave the index +saying `active` about a session that has none — a field that is silently +false, which is worse than an absent one and is exactly what the four list +fields were narrowed to avoid. + +Core does not close that gap for us. `Loopex.Runtime.Control` monitors each +coordinator, and when an `:active` one goes down it releases the dispatcher +fence and returns without altering the session entry, which keeps the entry in +place with a dead coordinator pid. That is the right thing for core to do and +it is not a defect; it simply means no notification arrives that the daemon +could use to move the index. + +So **the loss of an activated session's coordinator is fatal to the daemon +instance**, by the same rule and the same supervision shape ADR 0033 gives a +lease owner's failure: `one_for_all` up to the listener, every connection +closed, the daemon exits and restarts with nothing activated, no lease, and an +index rebuilt from the directory in which every session is `dormant` and +`controlled` is false — which is exactly true of a daemon that has activated +nothing. The activation count starts again with it, since the ceiling counts +activations per daemon lifetime and a restart is a new lifetime. + +The alternative — a lifecycle notification from core, an index transition to +some third state, and a recovery route back to `active` — was rejected. A +transition out of `active` is a deactivation, and deciding when a session may +leave `active` is deciding when its coordinator may stop: that is the core +deactivation operation M5 does not have and cannot invent here, wearing a +different name. Taking the daemon down instead costs an outage and buys a +listing that is never wrong. Lineage, lifecycle state and last committed sequence are deliberately absent. A daemon index cannot keep them current without reading the Store on the diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index adb14b1ce..35e163caf 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -105,6 +105,10 @@ unresolved `commit_unknown` or an executing admission in flight, and because stopping one would need a core deactivation operation M5 does not add. The cost is stated rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th refuses, and the remedy is to restart the daemon. +Losing an activated session's coordinator is fatal to the daemon instance for +the same reason a lease owner's loss is — core signals no lifecycle transition +the daemon could use, so the only way to keep `active` from meaning something +false is to stop being a daemon that claims it. Lazy recovery is what a daemon can honestly promise on a store whose session directory is not Store truth and whose every open replays a full log. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index ac29a6986..e521cc0aa 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -135,8 +135,19 @@ the local store's writer marker, unchanged. not on the two calls that precede it, and that mutation refuses unless the sending connection is the holder, the epoch matches and the connection holds a controller-capable attachment. -- An orderly connection close by the holder releases the lease; an abrupt - loss leaves it to expire. +- **Only an explicit release releases early.** A successful + `session.release_control` from the holder frees the lease at once. Every + other way a connection ends — an orderly close, an EOF, a killed client, a + severed socket — leaves the lease to expire on its term. + + An earlier draft said an orderly close released the lease while an abrupt + loss waited. That cannot be implemented over a Unix-domain socket and is + withdrawn: the daemon sees EOF, and EOF is EOF. A client that closed + politely and a client that was killed present the reading end with exactly + the same event, so a rule that distinguishes them is a rule the daemon + cannot execute. Binding early release to a message the client actually sent + is the only version of this the transport can support, and it is also the + more honest one — a controller that wants to hand over says so. ### Expiry against an in-flight admission @@ -212,7 +223,12 @@ stable reason when its own deadline elapses first, the holder's connection disconnecting while its mutation is in flight, and the per-session lease owner failing while a mutation is in flight — in every case exactly one of settle or refuse, never both, and no epoch reused; takeover only after release or expiry -with a fresh epoch minted before the successor's first command; a controller +with a fresh epoch minted before the successor's first command; the three ways +a controller stops holding proved separately, because only one of them is +early and the transport cannot tell the other two apart — an explicit +`session.release_control` frees the lease at once, while an EOF from a politely +closed client and a killed client both wait for expiry, with a takeover +refused before the deadline and granted after it in both cases; a controller killed mid-run fenced after takeover, its late commands refused; a per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index c5a41aeb5..7adeed350 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -47,8 +47,12 @@ controller-capable attachment. So a newly created session is driven by attaching and acquiring in either order and then sending the first command with the granted epoch, and a known dormant session is driven by acquiring by ID, resuming with the granted epoch and attaching. A -controller renews its lease while it lives and releases it on an orderly -disconnect; a lease that is not renewed expires. Takeover is explicit: an +controller renews its lease while it lives and releases it early only by +sending `session.release_control` and having it succeed; a lease that is not +renewed expires. Nothing about how the connection ended shortens the term, +because over a Unix-domain socket the daemon cannot tell a polite close from a +killed client — both are EOF — so only a message the client actually sent can +mean "I am done". Takeover is explicit: an observer asks for control and receives it only when the lease is released or expired, and the grant mints a new writer epoch before the new controller's first command can be admitted, so a controller that was killed mid-run and @@ -69,7 +73,8 @@ daemon's own configuration may narrow who may take over; it cannot widen what the host's policy allows a command to do. The proposed lease terms are exact and are bound at acceptance: a thirty-second lease renewed every ten seconds, takeover eligible at the live daemon's steady-clock expiry, and immediate -release on orderly disconnect. Expiry and an unresolved admission meet on one +release only on a successful explicit release. Expiry and an unresolved +admission meet on one rule, so neither promise is quietly broken by the other: a mutation whose holder check completed before the deadline settles under its lease even if the deadline passes while core is still deciding; at the deadline the holder gains diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 47ff0f7a2..ac1b0925d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -105,7 +105,11 @@ acquire validates existence with that query and refuses an unknown ID with nothing created. The lease record lives in the daemon's memory, keyed by session, for the daemon process's lifetime; one owner process per session serializes its lease transitions with its admission -handoff, and a restart of that owner leaves the session uncontrolled. For +handoff, and that owner's failure is fatal to the daemon instance rather than +survivable — it holds the session's in-flight admission set, which a takeover +waits on, so a restart beneath live sockets could grant a successor while a +forgotten admission could still settle. ADR 0033 fixes the rule; the daemon +restarts with no lease, no connection and no activated session. For every existing-session mutation the daemon checks the requesting connection identity, the current epoch, the held state and the unexpired term together before forwarding to core; an epoch alone is not authority, and every epoch is @@ -125,9 +129,9 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID, the existence query confirms it, the daemon records the missing directory entry, and control is then acquired and the session driven — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the directory entry present afterwards, the session listed, and a later prompt landing on the same session rather than a second one; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator takes the listener, every connection and the daemon down with it, after which the rebuilt index reports every session `dormant` and `controlled` false; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID, the existence query confirms it, the daemon records the missing directory entry, and control is then acquired and the session driven — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the directory entry present afterwards, the session listed, and a later prompt landing on the same session rather than a second one; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers plain data for a session that exists and for one that does not, from a fresh process against a real root, and is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown IDs. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent token, malformed token, a token with no registry row, a gone registry, a dead custody process, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — and the resolver call that carries it are proved excluded from tracing under a trace session at the `arguments` level, which shows placeholders and no credential bytes; the registry lookup before it is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index abc721021..0f6c52405 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -114,7 +114,11 @@ coordinator lifetime and M5's only core change is concurrent attachment. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation refuses with a stable reason, and the operator's remedy is to restart the -daemon. Lifting it needs a core operation that can tell quiescent from idle, +daemon. Losing an activated session's coordinator is fatal to the daemon +instance, the same rule a lease owner's loss carries: core signals no +lifecycle transition the daemon could act on, so the alternative is an index +that says `active` about a session with no coordinator, and a listing field +that is silently false is worse than an outage. Lifting it needs a core operation that can tell quiescent from idle, which is its own decision and not M5's. `session.list` is a daemon convenience, not an enumeration of durable truth. From 2693303dd3d615277ee452e554302646bce54e41 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:49:35 -0700 Subject: [PATCH 036/585] adr(0032): end recovery in activation, close the existence result set Fourth-review items 4 and 6. Item 4, verified in code: Loopex.Runtime.Control.create_session/4 resolves a replayed create and replies {:ok, session_id} on its `not fresh?` branch at control.ex:901-907 WITHOUT calling start_owner. So the recovery sequence as written ended with an identity and nothing running -- the session durable and idle. It now runs to ten steps: recover the ID by command identity, existence query, repair the directory entry and index row, return the ID, acquire control, session.resume with a FRESH resume command ID under the granted writer epoch, activation, attach, drive. Step 8 is named as the one that activates, and the witness asserts a live coordinator, the activation count risen by one, and a prompt landing and producing events -- not merely an ID returned. Item 6: "a plain-data answer" was not a contract a caller about to grant authority could rely on. The result set is now closed -- present, absent, invalid_id, store_unavailable, unexpected -- with a table saying what each obliges. Control acquisition proceeds only on present; the other four fail closed identically in what they leave behind (no attachment, no lease, no activation, nothing created) and differ only in what the client is told, which matters because a refusal reporting an unknown session when the store was unreadable would send an operator looking for a session that exists. One witness per result, with store_unavailable injected by making the root unreadable and unexpected by a stub answering outside the set. --- ...tachment-residency-and-replay-technical.md | 80 ++++++++++++++----- docs/plans/M5-technical.md | 4 +- docs/plans/M5.md | 17 +++- 3 files changed, 76 insertions(+), 25 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 691a72555..9d0ade5aa 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -225,12 +225,36 @@ durable record and no Store read by the daemon: at `acquire_control`, which must validate existence *before* granting a lease and must be safe to call on an ID that turns out to be unknown. - So `session.acquire_control` on an ID the index does not hold validates - durable existence with the query, and a negative answer is the refusal the - client sees, with nothing created and no attachment left behind. Nothing - about the index is consulted to decide existence, which is why an index - that is incomplete is not a correctness problem, and the daemon still reads - no Store internals. + **The query's result set is closed, and only one member is a yes.** "A + plain-data answer" is not a contract on its own — a caller has to know what + it may receive and what each result obliges it to do, especially a caller + about to grant authority on the strength of it. The query answers exactly + one of: + + | Result | Means | What the daemon does | + | --- | --- | --- | + | `present` | The root holds this session durably | Proceed: acquire may be granted, activation may follow | + | `absent` | The root does not hold it, and core is certain of that | Refuse, naming the session as unknown | + | `invalid_id` | The argument is not a well-formed session identifier | Refuse as an invalid argument, before anything is looked up | + | `store_unavailable` | Core could not read the root to decide | Refuse, naming the store as unavailable — **not** as an unknown session, because those are different facts and an operator acts on them differently | + | `unexpected` | Anything else, including a result shape the daemon does not recognise | Refuse, the same way as `store_unavailable`, because an answer that cannot be interpreted is not a yes | + + **Control acquisition proceeds only on `present`.** Every other result + fails closed and identically in what it leaves behind: no attachment, no + lease, no activation, no index row, nothing created. What differs is only + what the client is told, and the client is always told which — a refusal + that said "unknown session" when the store was unreadable would send an + operator looking for a session that exists. + + Nothing about the index is consulted to decide existence, which is why an + index that is incomplete is not a correctness problem, and the daemon still + reads no Store internals. + + Each of the five results is a witness: `present` granting, `absent`, + `invalid_id`, `store_unavailable` injected by making the root unreadable, + and `unexpected` injected by a stub that answers outside the set. All five + assert the same absence afterwards — no attachment, no lease, no activation + — and assert that the four refusals name distinct reasons. 2. **A client that never saw the session ID recovers by command identity, and the sequence is written out here rather than left as a gesture.** At the cut where the Store committed the creation and the process died before the @@ -243,23 +267,41 @@ durable record and no Store read by the daemon: | 1 | Client | Reconnects to the daemon and re-presents `session.create` with **the same `command_id`** it used before. It knows no session ID, so it cannot ask for one | | 2 | Daemon | Forwards it as an ordinary create. It does not consult the index, which by construction may not hold this session | | 3 | Core | Recognises the command identity as already resolved and returns the **historical result** — the same session ID it committed before — rather than creating a second session. This is the command idempotency the resume path already relies on, not a new mechanism | - | 4 | Client | Now holds the session ID for the first time | - | 5 | Daemon | Validates durable existence with the read-only existence query on that ID, which answers yes because the Store committed it in the first place | - | 6 | Daemon | Records the directory entry it is missing, so every later `session.list` shows the session. If that write fails, step 3 of this procedure applies: the client is told, the session stays usable, and the record is retried next time | - | 7 | Client | Acquires control and attaches in either order, and drives the session normally | - - Steps 5 and 6 are what turn a recovery into a repair: the session is not - merely reachable once, it stops being missing. A client that *does* still - hold the session ID skips steps 1 to 4 and enters at step 5. + | 4 | Client | Now holds the session ID for the first time. **No coordinator is running for it** — see below | + | 5 | Daemon | Validates durable existence with the read-only existence query on that ID, which answers `present` because the Store committed it in the first place | + | 6 | Daemon | Repairs what is missing: writes the directory entry and adds the index row, so every later `session.list` shows the session. If that write fails, step 3 of this procedure applies | + | 7 | Client | Acquires control, receiving the writer epoch | + | 8 | Client | Sends `session.resume` with a **fresh resume `command_id`** and that writer epoch. This is the step that activates the session: it is a new command, not a replay, because the create's identity is spent | + | 9 | Daemon | Activates the session — a live coordinator now exists — and counts it against the activation ceiling | + | 10 | Client | Attaches and drives | + + **Step 8 is the one an earlier draft left out, and without it the recovery + ends with nothing running.** Replaying a completed create does not start a + coordinator: `Loopex.Runtime.Control.create_session/4` resolves the + transaction, sees the command was already resolved, and replies `{:ok, + session_id}` on the `not fresh?` branch *without* calling `start_owner`. + That is correct — a replay must not create a second owner — but it means + steps 1 to 4 return an identity and nothing more. The session is durable + and idle. `session.resume`, with its own fresh command identity and under + the lease acquired at step 7, is what brings it back, and the sequence is + only a recovery once it reaches there. + + Steps 5 and 6 turn the recovery into a repair: the session is not merely + reachable once, it stops being missing. A client that *does* still hold the + session ID skips steps 1 to 4 and enters at step 5. **Its witness.** One case injects the exact cut — Store commit of the create followed by process death before the directory write and before the reply — then, from a client that never received the session ID, replays - `session.create` with the original `command_id` and asserts: exactly one - session exists in the root, the returned ID equals the committed one, the - existence query answers yes for it, the directory entry is present - afterwards, the session appears in `session.list`, and a prompt sent after - acquiring control lands on the same session rather than a second one. + `session.create` with the original `command_id` and runs the sequence to + the end. It asserts: exactly one session exists in the root; the returned + ID equals the committed one; the replay itself started no coordinator; the + existence query answers `present`; the directory entry and index row are + present afterwards and the session appears in `session.list`; the resume + under the granted epoch activates it, so a **live coordinator exists** and + the activation count has risen by one; and a prompt sent afterwards lands + on that session and produces its events, rather than on a second session or + on nothing at all. 3. **Recording can fail, and says so.** If writing the directory entry fails during activation, the failure is reported to the client that triggered it, as an explicit warning that this session will not appear in `session.list` diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index ac1b0925d..fe6b3316f 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -129,10 +129,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator takes the listener, every connection and the daemon down with it, after which the rebuilt index reports every session `dormant` and `controlled` false; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID, the existence query confirms it, the daemon records the missing directory entry, and control is then acquired and the session driven — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the directory entry present afterwards, the session listed, and a later prompt landing on the same session rather than a second one; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator takes the listener, every connection and the daemon down with it, after which the rebuilt index reports every session `dormant` and `controlled` false; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers plain data for a session that exists and for one that does not, from a fresh process against a real root, and is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown IDs. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent token, malformed token, a token with no registry row, a gone registry, a dead custody process, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — and the resolver call that carries it are proved excluded from tracing under a trace session at the `arguments` level, which shows placeholders and no credential bytes; the registry lookup before it is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 0f6c52405..26ffe565e 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -137,12 +137,21 @@ them authoritatively. A session missing from the list is never a lost session, and the plan says exactly how it is recovered. The daemon learns durable existence from core, through a read-only query that asks only that: given a session ID, does the -root hold it durably. No attach, no resume, no side effect, a plain-data -answer. The daemon reads no Store internals, so an incomplete index is never -a correctness problem. A client that never received the session ID — the cut where the +root hold it durably. No attach, no resume, no side effect. Its answer is one +of a closed set — `present`, `absent`, `invalid_id`, `store_unavailable`, +`unexpected` — and only `present` lets control be granted. The other four fail +closed, leaving nothing created, nothing attached and no lease, and each names +its own reason, because an unreadable store and an unknown session are +different facts an operator acts on differently. The daemon reads no Store +internals, so an incomplete index is never a correctness problem. A client that never received the session ID — the cut where the Store committed and the process died before the reply — recovers through the create command's durable `command_id`, which returns the historical result -instead of creating a second session. If recording the directory entry fails +instead of creating a second session — and then, because a replayed create +starts no coordinator, `session.resume` with a fresh resume command ID under +the acquired writer epoch is what actually brings the session back. ADR 0032 +writes that sequence out step by step, and its witness asserts a live +coordinator and a prompt landing at the end of it, not merely an identity +returned. If recording the directory entry fails during activation, that failure is reported to the client, the session is fully usable anyway, and the record is retried at the next activation. And if the index is already at its 4,096-entry ceiling, a session reached by ID is From 6d364d587ec6911534dc8f4063a6b1d59627c67f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:54:11 -0700 Subject: [PATCH 037/585] adr(0034): registry routing, trace exclusion, closed reasons Fourth-review items 8, 9 and 15. Item 8, verified in code: session_coordinator.ex:3231 calls module.complete(request, options, progress) -- three arguments, no more -- so a token in the per-invocation configuration names which credential but not where to ask. The registry reference is now a per-runtime capability carried in the model configuration's `options`, which runtime.ex:932-934 validates as %{module:, model:, options:} with options a keyword list handed to complete/3 unchanged. It is a runtime-scoped registered NAME rather than a pid, which keeps it plain data under the boundary rule and survives the registry being restarted by its own supervisor; it is scoped per runtime so two runtimes in one VM cannot reach each other's, with nothing in application environment and no fixed global name. The lookup is one operation, route(registry_ref, token) -> {:ok, custody_ref} | {:error, :unavailable}, returning where to ask and never bytes. Its lifetime is the host's and dies with recomposition; the adapter neither starts nor supervises it. Item 9: the pair said in one place that the credential-bearing call is excluded from tracing and in another that M5 would prove placeholders appear for it. Both cannot be true -- a placeholder is a trace entry and an excluded call produces none. Accepted ADR 0030 technical already fixes the mechanism, "the key-bearing call is excluded by match specification", so this names which calls that covers: the sender's registry route call, its custody reply handling, and the credential frame write. The proof is an absence -- no trace entry names any of the three, the tracer receives no raw trace message for them, and a placeholder entry fails the case as surely as the bytes would. Every placeholder expectation is removed, including from the plan's evidence row. Item 15: three real failures had no atom. The set is now seven and closed in both directions, with a table: :no_token, :invalid_token, :missing, :expired, :oversized, :unavailable (which now also carries a malformed successful reply) and :timeout. --- ...andoff-over-bootstrap-channel-technical.md | 127 ++++++++++++++---- ...edential-handoff-over-bootstrap-channel.md | 6 +- docs/plans/M5-technical.md | 2 +- 3 files changed, 102 insertions(+), 33 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index d0a5afeca..c0d31d600 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -82,6 +82,42 @@ custody process; the registry itself never sees or holds a credential, so reading it discloses which tokens exist and nothing about what they stand for. +**How the sender reaches it, given what `complete/3` actually receives.** The +callback takes three arguments and no more — `module.complete(request, +options, progress)` is the exact call the coordinator makes — so a token in +the per-invocation configuration names *which* credential but says nothing +about *where* to ask. Those are two different things and this pair keeps them +separate: + +- **The registry reference is a per-runtime capability, carried in + `options`.** The model configuration a host composes is + `%{module:, model:, options:}` with `options` a keyword list the runtime + validates and hands to `complete/3` unchanged, so it is the seam that + already exists for exactly this: something the host decides once, per + runtime, that every invocation needs. Composition puts the registry + reference there, under its own key, beside the token the caller supplies per + invocation. +- **It is plain data, and a name rather than a pid.** The reference is a + runtime-scoped registered name — bounded, serializable, meaningless in + another VM and in another runtime — never a pid, port or function. The + boundary rule that keeps PIDs out of durable and public data is not + negotiated here; a registered name satisfies it and a pid would not, and a + name also survives the registry process being restarted by its own + supervisor, which a pid does not. +- **No global state.** The name is scoped to the runtime, so two runtimes in + one VM have two registries and neither can reach the other's. Nothing is + read from application environment and nothing is looked up by a fixed + global name, which is the rule core already holds itself to. +- **The lookup is one operation, and it is the host's.** + `route(registry_ref, token) -> {:ok, custody_ref} | {:error, :unavailable}`. + It returns *where to ask*, never bytes; `:unavailable` covers a registry + that is gone and a token with no row, because from the sender's side those + are the same fact and neither is recoverable by asking again. +- **Its lifetime is the host's.** The host starts the registry when it + composes the runtime and it dies with recomposition. The adapter neither + starts it, supervises it nor restarts it, and a sender that finds it absent + refuses rather than waiting for it to come back. + **Custody is a separate process, and is where the bytes live.** Each reference implementation states and proves its own: the reference CLI, the app-server host and the M5 daemon read `Loopex.LLM.ReqLLM.credential_variable/0` exactly @@ -122,20 +158,37 @@ boundary, not an absolute: already protects that process — the sender installs its own group-leader sink so no IO request can carry anything out of it, it is unregistered, and it reports only an atom or a `{:error, atom}` pair to the guardian. -- **The credential-bearing resolver call is excluded from tracing, and the - mechanism is named.** ADR 0030's `arguments` level redacts "a credential - reference, model content, tool arguments and artifact bytes to placeholders" - and replaces "any value reachable through a credential reference" — the - token and the value it resolves to are inside that class by construction, - since the token *is* the credential reference and the bytes are what it - reaches. The sender is a `Loopex.*` module and, spawned beneath - runtime-owned processes, is reachable by `set_on_spawn`, so being inside - the class is what excludes it rather than being out of scope. M5 must - **prove** it: a trace session at the `arguments` level over a real - invocation shows placeholders for the resolver call, its reply and the - resolved value, and no credential bytes anywhere in the captured entries. - That is a proof obligation on M5, not a change to ADR 0030, whose redaction - class already names this category. +- **The credential-bearing calls are excluded from tracing by match + specification, and are named exactly.** Accepted ADR 0030 already fixes the + mechanism — "the key-bearing call is excluded by match specification" — so + this pair does not invent one, it names which calls that covers. They are + three, all in the sender: + + | Excluded call | Why | + | --- | --- | + | The registry route call | Its arguments carry the token, and the token is the credential reference | + | The custody reply handling | Its argument is the resolved credential | + | The credential frame write | Its argument is the resolved credential | + + Exclusion by match specification means the trace session never matches + those functions, so the VM emits **no raw trace message** for them and the + tracer never sees one. That is stronger than redaction and it is the + difference an earlier draft blurred: it said in one breath that the call was + excluded from tracing and in the next that M5 would prove placeholders + appear for it. Both cannot be true — a placeholder is a trace entry, and an + excluded call produces none — and the placeholder expectation is withdrawn + wherever it appeared, here and in the plan's evidence row. Redaction remains + the safety net for everything that *is* traced; it is not the mechanism for + these three. + + **The proof is an absence, and is stated as one.** Under a real trace + session at the `arguments` level over a real invocation, the case asserts + that no trace entry names any of the three functions, that the tracer + received no raw trace message for them, and that no credential bytes and no + token appear anywhere in the captured entries. An entry bearing a + placeholder for one of them fails the case exactly as an entry bearing the + bytes would, because it would prove the match specification did not + exclude what it was supposed to. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or @@ -170,15 +223,26 @@ host wrote, and a resolver that simply blocked would have hung the invocation past its deadline. Enforcement belongs to the process that can act on it by killing something. The resolver's only obligation is to answer or not. -**The closed reason set is unchanged.** A custody process answers -`{:error, reason}` only with `:missing`, `:expired`, `:oversized` or -`:unavailable`; the guardian produces `:timeout`, and `:unavailable` is also -what a missing registry row, a gone registry and a dead custody process -answer. Nothing else is admitted — anything returned outside the set is -treated as `:unavailable`, because a host-authored term is exactly where a -secret could be smuggled into a reason. The five atoms carry no -content, so they are safe in a message, an exit reason and a bounded -diagnostic. +**The closed reason set, complete.** Every way resolution can fail maps to one +of seven atoms, and the set is closed in both directions: nothing else is +produced, and nothing else is accepted. + +| Atom | Produced by | For | +| --- | --- | --- | +| `:no_token` | The adapter | The configuration carries no `:credential_token` at all | +| `:invalid_token` | The adapter | A token outside the identifier alphabet or over 256 bytes, refused before any lookup | +| `:missing` | A custody process | It has no credential for this token | +| `:expired` | A custody process | It has one and considers it no longer valid | +| `:oversized` | The sender | A successful reply whose bytes fall outside 1 to 65,536 | +| `:unavailable` | The registry or a custody process | A missing registry row, a gone registry, a dead custody process, a custody process that answers `:unavailable`, or **a successful reply that is malformed** — not a binary, or a shape the sender does not recognise — because a reply it cannot read is not a credential it can send | +| `:timeout` | The guardian | Resolution had not completed when the invocation deadline was reached | + +An earlier draft left the first two unnamed and folded a malformed successful +reply nowhere at all, which meant three real failures had no atom to carry. +Anything returned outside this set is treated as `:unavailable`, because a +host-authored term is exactly where a secret could be smuggled into a reason. +All seven atoms carry no content, so they are safe in a message, an exit +reason and a bounded diagnostic. **What the sender reports.** `:ok` or `{:error, reason}` from that same closed set, never a bare `:error`. The guardian has to distinguish a custody process @@ -193,8 +257,9 @@ leaves no retained copy of anything the resolver may have produced: | Condition | Outcome | | --- | --- | -| No `:credential_token` in the configuration | Refused before the namespace is created and before any child is spawned, with the adapter's existing missing-credential reason | -| Malformed token — outside the identifier alphabet or over 256 bytes | The same refusal, before any child is spawned | +| No `:credential_token` in the configuration | `:no_token`, refused before the namespace is created and before any child is spawned | +| Malformed token — outside the identifier alphabet or over 256 bytes | `:invalid_token`, refused before any lookup and before any child is spawned | +| A successful custody reply that is malformed — not a binary, or a shape the sender does not recognise | `:unavailable`; a reply the sender cannot read is not a credential it can send | | The registry holds no row for the token, the registry is gone, or the custody process is dead | `:unavailable`. The host recomposes; nothing is reconstructed, because the registry holds no bytes to reconstruct from | | Custody answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | | Custody answers `{:error, :unavailable}`, or anything outside the closed set | The same path, reported as `:unavailable` | @@ -376,10 +441,14 @@ Three proofs are new: exit reason and no crash report carries the resolved value. The two-resolutions-at-once case is a **success** case, not a refusal: both invocations complete with their own credentials. -- **The permitted reply is redacted.** A trace session at the `arguments` - level over a real invocation shows placeholders where the reply and the - resolved value would be, and no credential bytes anywhere in the captured - entries. +- **The credential-bearing calls are not traced at all.** Under a trace + session at the `arguments` level over a real invocation, no trace entry + names the registry route call, the custody reply handling or the credential + frame write; the tracer received no raw trace message for any of them; and + no credential bytes and no token appear anywhere in the captured entries. A + placeholder entry for one of the three fails the case as surely as the bytes + would, because it would prove the match specification did not exclude what + it was supposed to. - **Host custody, proved at each host rather than in the adapter.** The adapter's test tree cannot prove a claim about the CLI's or the daemon's composition, and an earlier draft filed all three there. Each case lives diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index a765e3566..a7108c02a 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -166,9 +166,9 @@ credential from the completion of composition onward — before, during and after a call; two invocations running at once are proved unable to observe each other's credential; every resolution failure the contract names — absent token, malformed token, no registry row, a gone registry, a dead custody -process, a refusing custody process, one that blocks past the invocation -deadline, and a value outside the size bound — is proved to refuse with one of -the five closed reason atoms and to leave no retained copy, with the +process, a refusing custody process, a malformed successful reply, one that +blocks past the invocation deadline, and a value outside the size bound — is +proved to refuse with one of the seven closed reason atoms and to leave no retained copy, with the guardian's timeout proved distinguishable from every refusal and proved to bound the invocation whatever the custody process does; two resolutions in flight at once are proved to be independent successes rather than a refusal; diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index fe6b3316f..b56f3c4d3 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -134,7 +134,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: absent token, malformed token, a token with no registry row, a gone registry, a dead custody process, each of `:missing`, `:expired`, `:oversized` and `:unavailable`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The one permitted credential-bearing message — the custody process's reply to the sender — and the resolver call that carries it are proved excluded from tracing under a trace session at the `arguments` level, which shows placeholders and no credential bytes; the registry lookup before it is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The three credential-bearing calls in the sender — the registry route call, the custody reply handling and the credential frame write — are excluded from tracing by match specification, as accepted ADR 0030 already requires of a key-bearing call, and the proof is an absence: under a real trace session at the `arguments` level no trace entry names any of the three, the tracer receives no raw trace message for them, and no credential bytes and no token appear in any captured entry. A placeholder entry for one of them fails the case as surely as the bytes would. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the From 76cef7ebc7761b8510399c09880f6dbba1b81a96 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:51:41 -0700 Subject: [PATCH 038/585] plan(M5): give the cross-UID witness a selector and widen the docs gate Fourth-review items 10 and 16. Item 10, verified in code: scripts/check-release.sh:33 runs each lane as mix test --only real_provider --only node_client --include long_bound. A cross-UID case belongs to none of those three, so the witness the plan bound closure to had no way to run. The cases are now tagged @tag :cross_uid and the script runs, on the Linux lane only, (cd apps/loopex_daemon && mix test --only cross_uid). Two cases carry the tag -- foreign uid refused before initialize, own uid accepted -- and both must execute. The script already pipes each lane through scripts/suite-summary.sh and fails when a lane executed no test; the plan now says that judge governs this lane and a zero executed count is red rather than a skip, which matters because a cross-UID case is exactly the kind that quietly excludes itself when the second user is missing. Item 16: the gate derived only *.md. It now derives over every tracked file in both trees, git ls-files -- docs/operator docs/developer, so the promise that every file under them was read stays true if a diagram, fixture or data file appears later rather than slipping through a filter that was accurate when written. Verified at this SHA: the directory form returns 26 paths, 18 developer and 8 operator, all Markdown today -- the same count the previous glob form produced, so nothing is lost by widening it. --- docs/plans/M5-technical.md | 38 ++++++++++++++++++++++++++++---------- docs/plans/M5.md | 11 ++++++----- 2 files changed, 34 insertions(+), 15 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index b56f3c4d3..53a6b0b70 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,10 +130,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator takes the listener, every connection and the daemon down with it, after which the rebuilt index reports every session `dormant` and `controlled` false; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success proved on the release check's Linux lane. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs on the Linux lane as `mix test --only cross_uid`, where the suite-summary judge makes a zero executed count red rather than a skip. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The pathspec glob magic is load-bearing and was checked rather than assumed: without `:(glob)`, git's default pathspec treats `**` as an ordinary wildcard that does not cross directory separators the same way and the command returns **no paths at all**, which would have made the gate pass vacuously. With it, the command returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/` — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The three credential-bearing calls in the sender — the registry route call, the custody reply handling and the credential frame write — are excluded from tracing by match specification, as accepted ADR 0030 already requires of a key-bearing call, and the proof is an absence: under a real trace session at the `arguments` level no trace entry names any of the three, the tracer receives no raw trace message for them, and no credential bytes and no token appear in any captured entry. A placeholder entry for one of them fails the case as surely as the bytes would. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every @@ -174,14 +174,32 @@ the floor pair, `mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh` with its own `MIX_BUILD_ROOT`; and `bash scripts/check-release.sh` runs once on the current pair with the provider credential and the pinned Node version in -`scripts/fixtures/m4/client-toolchain.txt`. That release check is where -Outcome 2's cross-UID witness lives, and closure is bound to it: the Linux -lane must record a connection from a foreign uid refused before initialize and -one from the daemon's own uid accepted. The fast check cannot supply it, -because it has no second user, so an absent Linux-lane result is missing -evidence rather than a pass. `loopex_daemon` joins that -script's `release_apps` list in the change that adds its first release case, -and only that list: every `release_apps` lane already runs +`scripts/fixtures/m4/client-toolchain.txt`. + +That release check is where Outcome 2's cross-UID witness lives, and it needs +a selector it does not have today. `scripts/check-release.sh` runs each +`release_apps` lane as `mix test --only real_provider --only node_client +--include long_bound`: three selectors, none of which a cross-UID case +belongs to. So M5 adds one — the cases are tagged `@tag :cross_uid` — and the +script runs, on the Linux lane only, for `loopex_daemon`: + +```text +(cd apps/loopex_daemon && mix test --only cross_uid) +``` + +Two cases carry that tag and both must execute: a connection from a foreign +uid refused before initialize, and one from the daemon's own uid accepted. +The script already pipes each lane through `scripts/suite-summary.sh` and +fails the check when a lane executed no test — "a run that executed nothing +is not a pass", as its own comment puts it — and that judge governs this lane +too: **a zero executed count is red**, not a skip. That matters more here than +elsewhere, because a cross-UID case is exactly the kind that quietly excludes +itself when the second user is missing, and a silent zero would turn the one +witness the fast check cannot supply into no witness at all. Closure is bound +to that lane's recorded result. + +`loopex_daemon` joins the `release_apps` list in the change that adds its +first release case, and only that list: every `release_apps` lane already runs `--include long_bound`, so the daemon's long-duration bound tests are carried there and the application does not also join `long_bound_apps`, which exists for applications with no other release test. Each run's revision, platform, diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 26ffe565e..1b8a00ac7 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -318,12 +318,13 @@ candidate, as it is for every milestone. That gate is only worth keeping if a reviewer can check it, so it leaves a record rather than an assurance. The closure evidence carries a checklist -derived from the candidate itself — every tracked Markdown path under +derived from the candidate itself — every tracked path under `docs/operator/` and `docs/developer/` as -`git ls-files -- ':(glob)docs/operator/**/*.md' ':(glob)docs/developer/**/*.md'` -lists them at that commit, sorted, one row each, with the count stated so an -empty derivation is visible rather than silently passing; the command returns -26 paths as of this revision — and every row is marked either *updated* or *reviewed +`git ls-files -- docs/operator docs/developer` lists them at that commit, +sorted, one row each, with the count stated so an empty derivation is visible +rather than silently passing. It covers every tracked file rather than only +Markdown, so the promise stays true if another kind of artifact appears +there; the command returns 26 paths as of this revision, all Markdown today — and every row is marked either *updated* or *reviewed unchanged*, with any finding named and resolved before the packet is assembled. A path present in the tree and absent from the list, or a row with neither mark, is an unfinished gate. Deriving the list from the candidate From fc0c6833c941b1ca2349a676d21277a4e943003b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:52:59 -0700 Subject: [PATCH 039/585] plan(M5): sweep the material corrections across the set Fourth-review items 11, 12, 13, 14 and 17. Item 11: ADR 0032 technical still said request records were reused unchanged while generation 2 adds writer_epoch, and three passages still called concurrent attachment M5's only core change after decision 1A added the existence query. Both swept. Item 12: "dormancy costs a dormant session nothing" ignored what it does cost. A dormant session holds an index row against the 4,096-entry ceiling and its history sits in the root's shared append-only log against the 256 MiB capacity -- the two resources whose exhaustion stops the daemon -- which is why retiring a root is what frees them. What it costs nothing in is what activation buys. The directory-write retry "at the next activation of that session" was impossible under one-way activation; it is now at the next daemon start, when the index is rebuilt from the directory, with the session reachable by ID and absent from the listing until then. Item 13: the pagination statement described deletion and duplication an append-only index keyed by unique session ID cannot produce. Corrected to the one anomaly it can show -- a session recorded between reads whose ID sorts before the cursor already passed is missed -- with a row unable to vanish or repeat, so a complete view is a fresh paging pass rather than deduplication. Item 14: ADR 0034 assigned the host-custody cases to their owning applications and then took it back two lines later by filing them in credential_plane_test.exs. The assignment that holds is the per-host one, and the closing sentence now says which cases stay in the adapter's tree and which do not. Item 17, verified in code: local.ex:166 releases the writer marker in the Store's own terminate/2, so the daemon neither holds nor releases it. The invariant is restated as what it is -- the daemon owns the Store process, starts it before the socket is bound and stops it last in shutdown, so the marker is held while any session operation could need it and released by that terminate/2 at that moment; an abrupt kill runs no terminate/2 at all, which is why stale-writer recovery exists. The loopex_cli ownership row is updated to the contracts item 1 defines. --- ...store-selection-and-migration-technical.md | 16 ++++++- ...tachment-residency-and-replay-technical.md | 46 +++++++++++++++---- ...-daemon-attachment-residency-and-replay.md | 4 +- ...andoff-over-bootstrap-channel-technical.md | 12 +++-- docs/plans/M5-technical.md | 4 +- docs/plans/M5.md | 12 ++++- 6 files changed, 74 insertions(+), 20 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 300adfa6f..e8b0ff01e 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -11,8 +11,20 @@ Concept: [Context and decision](0031-daemon-grade-store-selection-and-migration. ### M5 selection: the local adapter and its limits The M5 daemon opens the state root through `loopex_store_local` exactly as -the foreground server does, and holds its writer marker from before the -socket is bound until the daemon process exits. The adapter's limits are the +the foreground server does. + +**The marker invariant, stated as it actually works.** The daemon does not +hold the marker itself and cannot release it itself: `Loopex.Store.Local` +takes it at start and releases it in its own `terminate/2`. What the daemon +owns is the Store *process* — it starts it before the socket is bound and +stops it last in shutdown, after the listener is closed, every connection is +closed and the socket is unlinked — so the marker is held for as long as any +session operation could still need it, and is released by that `terminate/2` +at the moment the daemon stops the Store. An abrupt kill runs no `terminate/2` +at all, which is why the marker is left behind and why the next daemon's +verified stale-writer recovery exists. The shutdown ordering that makes this +true is fixed in the M5 plan's lifecycle section, and it is ordering rather +than a new mechanism: stopping the Store last is the whole of it. The adapter's limits are the daemon's limits, and every one is an existing constant or refusal of `Loopex.Store.Local.Log`: diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 9d0ade5aa..25f5b0d9a 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -105,9 +105,13 @@ proved held, it closes the listener and every connection before anything else and then exits; no connection outlives the daemon's ownership of the root. -Framing, the initialize handshake, request and admission records, snapshot, +Framing, the initialize handshake, admission records, snapshot, event and progress records, the frame ceiling, the strict UTF-8/LF rule and -the unknown-field rule are reused from ADR 0023 unchanged. A connection is +the unknown-field rule are reused from ADR 0023 unchanged. **Request records +are the one exception**, and they are reused with one addition rather than +unchanged: every existing-session mutation in generation 2 carries +`writer_epoch`. That is the addition, and it is the reason generation 2 needs +a schema digest of its own. A connection is one attachment after `session.attach`; generation 2 permits a connection to hold at most one attachment at a time and a client process to hold as many connections as the residency limits admit. @@ -307,7 +311,13 @@ durable record and no Store read by the daemon: as an explicit warning that this session will not appear in `session.list` — the reference CLI already reports exactly that failure today. The activation itself succeeds, the session is fully usable, and the daemon - retries the record on the next activation of that session. + retries the record at the next **daemon start**, when the index is rebuilt + from the directory and the missing entry is written then. It cannot be + "the next activation of that session", which an earlier draft said: + activation is one-way, so within a daemon's lifetime there is no next + activation to retry at. Until the restart, the session is reachable by ID + and absent from `session.list`, which is exactly what the client was + told. 4. **A full index still activates.** If the index already holds 4,096 entries and a client reaches an unrecorded session by ID, the session is activated and is **not** recorded. Reachability never depends on the ceiling. What @@ -320,10 +330,18 @@ sessions this root contains*, and the operator documentation states all four parts, because an operator who lost a terminal mid-creation is exactly who meets them. -A page is consistent with the index at the moment it is read; no consistency -is promised across pages, so a session created or dropped between pages may -appear in neither or both, and a client that needs a stable view deduplicates -by session ID. A `limit` outside 1 to 256 or an `after_session_id` that is not +A page is consistent with the index at the moment it is read, and no +consistency is promised across pages. What that can actually produce is +narrower than an earlier draft claimed, because the index is append-only +within a daemon's lifetime and keyed by unique session ID: rows are added, +never removed and never renumbered, and ordering is by session ID bytes. So a +session recorded between two page reads may be **missed** — if its ID sorts +before the cursor the client has already passed — and that is the only +anomaly paging can show. A row cannot vanish between pages and cannot be +returned twice, because nothing deletes a row and no two rows share an ID. A +client that needs a complete view pages again from the start; deduplication is +unnecessary here, though a client that deduplicates by session ID loses +nothing. A `limit` outside 1 to 256 or an `after_session_id` that is not a well-formed session ID refuses with the existing invalid-argument reason; an `after_session_id` naming an unknown session is admitted and pages from its byte position. @@ -333,7 +351,16 @@ byte position. A session is **active** when the daemon holds a live coordinator for it and **dormant** when the index records it and the daemon has never activated it in this process's lifetime. Nothing durable distinguishes the two; dormancy is a -daemon fact and costs a dormant session nothing. +daemon fact. + +A dormant session costs less than an active one, but not nothing, and the +plan should not pretend otherwise. It holds one index row against the +4,096-entry ceiling, and its history sits in the root's single append-only log +against the 256 MiB capacity that every session in the root shares — so a +dormant session still consumes the two resources whose exhaustion stops the +daemon, and retiring a root is what actually frees them. What it costs nothing +in is the things activation buys: no coordinator, no replay at start, no +attachment, no window, no buffer. **Activation is one-way for the daemon's lifetime.** A session the daemon has activated keeps its coordinator until the daemon exits. Dormancy is *not* @@ -348,7 +375,8 @@ awaiting an answer, a recovery in progress, an unresolved `commit_unknown`, or an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and -M5's only core change is concurrent attachment, so a deactivation call would +M5's core changes are concurrent attachment and a read-only existence query, +neither of which stops anything, so a deactivation call would be a second core change this milestone does not make. - **What dormancy applies to.** Attachments, resident windows and socket diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 35e163caf..f46a98319 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -40,8 +40,8 @@ generation, control methods and the writer-epoch field ADR 0033 names. It adds no durable method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core -has no durable stop command, and M5's only core change is concurrent -attachment. Ending a client's involvement is releasing control and +has no durable stop command, and M5's core changes are concurrent attachment +and a read-only existence query, neither of which is a durable command. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by acquiring control and attaching. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index c0d31d600..261f07e9c 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -461,9 +461,15 @@ Three proofs are new: to prove: that it reads no environment variable for a credential and that the token and resolution contract behaves. -The first two, the failure cases and the custody cases belong in -`credential_plane_test.exs` beside the cases they generalise; the drift case -stays where it is. +The parent-environment and concurrent-independence proofs and the resolution +failure cases belong in `credential_plane_test.exs` beside the cases they +generalise; the drift case and the trace-exclusion case stay in the adapter's +tree with it. The **host-custody cases do not**: each lives at its own host, +as the bullet above assigns them — `apps/loopex_cli/test/`, +`apps/loopex_app_server/test/` and `apps/loopex_daemon/test/` — because the +adapter's tree cannot prove a claim about another application's composition. +An earlier draft assigned them correctly and then took it back two lines +later; this is the assignment that holds. Two details of that case matter to whoever writes the change. The literal `"LOOPEX_PROVIDER_API_KEY"` it pins today lives in diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 53a6b0b70..44fe7d4b9 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -42,7 +42,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | -| `loopex_cli` | `loopex daemon`, `loopex attach`, `loopex sessions` and takeover presentation | Normative lease or session semantics | +| `loopex_cli` | `loopex daemon` with its readiness line, signal handling and exit classes, `loopex attach` with its roles, takeover presentation and cursor reconnect, the live `loopex sessions --daemon` form beside the unchanged offline one, and the host-side credential custody and registry it composes | Normative lease or session semantics, and any change to the released offline `loopex sessions` | | `loopex_llm_reqllm` | The credential handoff, its sender, the token it accepts, the launcher's unchanged ADR 0019 scrubbing enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | @@ -129,7 +129,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator takes the listener, every connection and the daemon down with it, after which the rebuilt index reports every session `dormant` and `controlled` false; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable, and is retried at the next activation; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator takes the listener, every connection and the daemon down with it, after which the rebuilt index reports every session `dormant` and `controlled` false; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written at the next daemon start when the index is rebuilt; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs on the Linux lane as `mix test --only cross_uid`, where the suite-summary judge makes a zero executed count red rather than a skip. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 1b8a00ac7..cb6e3dfb6 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -109,7 +109,8 @@ effect dispatched, an interaction awaiting an answer, a recovery running, an unresolved `commit_unknown` or an admission executing inside core, so "idle" is not "quiescent" and stopping on idleness would destroy exactly what Outcome 1 exists to prove. And there is nothing to stop it with: core owns -coordinator lifetime and M5's only core change is concurrent attachment. +coordinator lifetime, and M5's two core changes — concurrent attachment and a +read-only existence query — neither of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation @@ -129,6 +130,11 @@ session the Store holds and the directory does not. So `session.list` promises exactly what it can keep true — the sessions this root records, each with its identity, its recorded placement identity, whether the daemon currently holds it active, and whether a controller lease is currently held — and no more. +Dormancy is cheap but not free: a dormant session still holds an index row +against the entry ceiling and its history still sits in the root's shared +append-only log against the capacity ceiling, which is why retiring a root is +what frees them. What it costs nothing in is what activation buys — no +coordinator, no replay at start, no attachment, no window, no buffer. Lineage, lifecycle state and committed sequence are not in a list entry, because a daemon index cannot keep them current without reading the Store on the request path; a client that needs them attaches, and the snapshot carries @@ -153,7 +159,9 @@ writes that sequence out step by step, and its witness asserts a live coordinator and a prompt landing at the end of it, not merely an identity returned. If recording the directory entry fails during activation, that failure is reported to the client, the session is -fully usable anyway, and the record is retried at the next activation. And if +fully usable anyway, and the record is retried at the next daemon start, when +the index is rebuilt from the directory — not at a next activation, because +activation is one-way and there is no second one within a lifetime. And if the index is already at its 4,096-entry ceiling, a session reached by ID is still activated, simply not recorded, with `session.list` carrying `index_full` so an operator is told the listing is incomplete rather than From a46d3d98481956690270c861441050b6bde85f17 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 20:54:46 -0700 Subject: [PATCH 040/585] plan(M5): link the new technical sections reciprocally The CLI-contracts and lifecycle sections added for items 1 and 2 carried their Concept backlinks but the Scope section had no forward link to either, which mix loopex.status rejects as a non-reciprocal labelled relationship. Both forward links added; the status check passes. --- docs/plans/M5.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docs/plans/M5.md b/docs/plans/M5.md index cb6e3dfb6..6beaf2600 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -344,6 +344,10 @@ Technical depth: [Prerequisites and acceptance points](M5-technical.md#technical Technical depth: [Ownership and rejoin order](M5-technical.md#technical-plan-ownership). +Technical depth: [The daemon's operator contracts](M5-technical.md#technical-plan-cli). + +Technical depth: [Daemon lifecycle and orderly shutdown](M5-technical.md#technical-plan-lifecycle). + Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan-minimalism). From 6601e9916db79f9a4abb27fc5fc7a281fef6f6ba Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:15:53 -0700 Subject: [PATCH 041/585] plan(M5): split store-loss fail-stop from the orderly stop Fifth-review decisions 1 and 2, both resting on code read first. Decision 1. local.ex:251-270 answers an append error with {:stop, reason, unknown(transaction), state} -- the Store terminates itself -- and local.ex:166 releases the writer marker in its own terminate/2. So on a store loss the marker is released before the daemon can react, and a sequence ending "stop the Store last" is unrunnable because the Store is what died. Store loss is now a separate fail-stop: observe, refuse service, close every connection with a best-effort final record carrying store_lost or store_capacity_exceeded, unlink, exit non-zero. How it is observed is named from the code: LoopexComposition.start_edge/2 (composition.ex:302-307) uses start_link, so the adapter is linked to the composing process; the daemon traps exits there and also monitors the adapter. The ordered sequence now applies only to daemon-initiated shutdown, in the plan, the lifecycle section and ADR 0031. Decision 2. The claim that running effects enter the configured cancellation sequence is deleted, with every daemon-side cancellation claim. What has not settled within the composed cleanup grace is ended by stopping the runtime: Runtime.stop/1 is Supervisor.stop(supervisor, :normal) (runtime.ex:115-121), and each coordinator is a restart: :temporary child with shutdown: 5_000 (session_coordinator.ex:134-142) that neither traps exits in init nor defines terminate/2 -- so it dies on the shutdown exit, bounded, running no terminal code. Crash-equivalent by construction, and no terminal mutation is claimed; commit_unknown stays fenced for the reconciliation ADR 0006 and ADR 0018 already define. The rejected options are recorded: host-authorized durable aborts would have the daemon issuing mutations on nobody's authority at the moment it can least see them through, and an unbounded natural drain would make SIGTERM unbounded, which is not a stop. Adds the fatal-class map and the reverse-cleanup rule, and re-points the in-flight witness at the negative that matters: no cancelled, no outcome_unknown, no abort record on the way down, and a journal byte-identical to what an abrupt death at the same instant would leave. --- ...store-selection-and-migration-technical.md | 36 +++-- docs/plans/M5-technical.md | 135 ++++++++++++++---- docs/plans/M5.md | 28 ++-- 3 files changed, 153 insertions(+), 46 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index e8b0ff01e..10ae4aae5 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -16,15 +16,33 @@ the foreground server does. **The marker invariant, stated as it actually works.** The daemon does not hold the marker itself and cannot release it itself: `Loopex.Store.Local` takes it at start and releases it in its own `terminate/2`. What the daemon -owns is the Store *process* — it starts it before the socket is bound and -stops it last in shutdown, after the listener is closed, every connection is -closed and the socket is unlinked — so the marker is held for as long as any -session operation could still need it, and is released by that `terminate/2` -at the moment the daemon stops the Store. An abrupt kill runs no `terminate/2` -at all, which is why the marker is left behind and why the next daemon's -verified stale-writer recovery exists. The shutdown ordering that makes this -true is fixed in the M5 plan's lifecycle section, and it is ordering rather -than a new mechanism: stopping the Store last is the whole of it. The adapter's limits are the +owns is the Store *process*. It starts it before the socket is bound and, in a +**daemon-initiated** shutdown, stops it last — after the listener is closed, +every connection is closed and the socket is unlinked — so the marker is held +for as long as any session operation could still need it and is released by +that `terminate/2` at the moment the daemon stops the Store. That ordering is +the whole mechanism; it is fixed in the M5 plan's lifecycle section. + +**Store loss inverts it, and the daemon cannot order what it does not +control.** This adapter answers an append error with +`{:stop, reason, commit_unknown, state}` — it terminates *itself* — and its +`terminate/2` releases the marker as it goes. So on a store loss the marker is +released **before** the daemon can react, and any sequence ending "then stop +the Store" is unrunnable, because the Store is what died. The daemon's only +correct response is a fail-stop: observe the termination — it composes the +adapter through `LoopexComposition.start_edge/2`, which uses `start_link`, so +the adapter is linked to the composing process, and the daemon both traps +exits there and monitors the adapter so the signal cannot be missed — then +refuse service, close every connection with `store_lost`, or +`store_capacity_exceeded` where that was the store's own reason, unlink the +socket and exit non-zero. The next daemon finds no marker to recover, because +the dying store already gave it back. + +An abrupt kill of the daemon runs no `terminate/2` at all, which is why *that* +leaves a marker behind and why the next daemon's verified stale-writer +recovery exists. The three cases are distinct and the operator documentation +keeps them so: an orderly stop releases the marker in order, a store loss +releases it early and unexpectedly, and a kill leaves it for recovery. The adapter's limits are the daemon's limits, and every one is an existing constant or refusal of `Loopex.Store.Local.Log`: diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 44fe7d4b9..52b674cc2 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -525,27 +525,50 @@ non-zero with that step's reason class and touches nothing after it — in particular, a daemon that does not hold the marker never reads, unlinks or binds the socket path. -**Shutdown, in order.** `SIGTERM` or `SIGINT` starts it, and from that instant: +There are **two** ways a daemon ends, and conflating them was a defect. A +daemon-initiated shutdown is the ordered sequence below and stops the Store +last. A **store loss is a fail-stop**, and it cannot be the ordered sequence, +for a reason that is in the code rather than in taste: `Loopex.Store.Local` +answers an append error with `{:stop, reason, commit_unknown, state}`, so it +terminates *itself*, and its `terminate/2` releases the writer marker on the +way out. By the time the daemon observes anything, the store is gone and the +marker is already released. A sequence that ends "then stop the Store" cannot +run when the Store is what died. + +**Daemon-initiated shutdown, in order.** `SIGTERM` or `SIGINT` starts it, and +from that instant: 1. **Refuse new work.** The listener stops accepting, so a new connection is refused rather than queued, and the daemon admits no new mutation on any existing connection. Queries and attach-state reads still answer, because they change nothing and a client deserves to learn what is happening. -2. **Drain what was already admitted.** Work in flight — a provider call, a - dispatched tool effect, an unresolved mutation — gets the composed cleanup - grace to finish on its own. Nothing here is a new mechanism, and the plan - names the existing ones rather than gesturing at "cleanup": a running - effect enters the configured cancellation sequence ADR 0016 fixes, with its - bounds, and terminates as `cancelled` or with the truthful - `outcome_unknown` ADR 0012 admits; a mutation whose commit is ambiguous is - left as `commit_unknown` and fenced, to be resolved by the reconciliation - ADR 0006 and ADR 0018 already define when the root is next opened. **No - admitted work is abandoned silently**, which is the property this step - exists for. -3. **Tell every client, then close.** Each connection receives one final frame - naming the reason — the operator stop, or the fatal class — and the daemon - then closes it. A client learns why its session went away from the wire - rather than from a socket that simply stopped answering. +2. **Drain, then end what has not settled — without claiming an outcome.** + Admitted work gets the composed cleanup grace to finish on its own. What + has not settled when the grace elapses is ended by stopping the runtime: + `Loopex.Runtime.stop/1` is `Supervisor.stop(supervisor, :normal)`, and each + session coordinator is a `restart: :temporary` child with `shutdown: 5_000` + that neither traps exits nor defines `terminate/2` — so it receives the + shutdown exit and dies, bounded, without running any terminal code. That is + **crash-equivalent by construction**, and it is the point: the daemon + claims no terminal mutation for work it ended. A mutation whose commit was + ambiguous stays `commit_unknown` and fenced, and the reconciliation + ADR 0006 and ADR 0018 already define settles it at the next activation — + exactly as it would after an abrupt death. + + An earlier draft said running effects enter the configured cancellation + sequence. That is withdrawn: cancellation is the coordinator's to run as + part of a session's own durable command, not something a daemon may drive + from outside, and a daemon-side cancellation path is precisely the second + loop this milestone forbids. Two alternatives were rejected with it. + Host-authorized durable aborts — the daemon admitting an abort per session + on the way down — would have the daemon issuing mutations on nobody's + authority, at the moment it is least able to see them through. An unbounded + natural drain — waiting for every effect to finish — would make `SIGTERM` + unbounded, which is not a stop. +3. **Tell every client, then close.** Each connection receives one + `daemon.stopping` notification naming the reason, and the daemon then + closes it. Delivery is bounded best-effort; the record and its bound are + fixed in ADR 0032, and a backpressured or dead client may not receive it. 4. **Unlink the socket.** The path is removed, so no later client connects to a dead endpoint and the next daemon binds cleanly rather than inheriting a stale file. @@ -554,16 +577,57 @@ binds the socket path. stopping the Store last is exactly what makes the marker outlive every session operation that might still have needed it. Only after it returns does the daemon exit. -6. **Exit.** `0` for an operator stop; non-zero with the reason class on - `stderr` for a fatal one, which runs the same steps 1 to 5 and differs only - in what it tells clients and what it returns. - -**An abrupt death** — `SIGKILL`, power loss — runs none of this, and is safe +6. **Exit `0`.** + +**Store loss, a fail-stop path.** The daemon composes its runtime through +`LoopexComposition`, whose `start_edge/2` starts the adapter with +`start_link`, so the Store is **linked** to the composing process; the daemon +traps exits there and additionally monitors the adapter, so a store that +terminates itself is observed either way rather than taking the daemon down +as an untrapped exit. On that signal, and without the ordered sequence: + +1. Refuse service immediately — no further admission, no further attach, and + the listener closed. +2. Close every connection, after one bounded best-effort `daemon.stopping` + carrying `store_lost`, or `store_capacity_exceeded` when the store's own + reason was the capacity refusal. +3. Unlink the socket. +4. Exit non-zero with that class on `stderr`. **There is no "stop the Store" + step**, because the Store already stopped and the marker is already + released; the next daemon finds no marker to recover rather than a stale + one. + +Nothing durable is at risk in that ordering: whatever was ambiguous is +`commit_unknown` in the journal and is reconciled at the next activation, and +whatever was not committed was never promised. + +**An abrupt death** — `SIGKILL`, power loss — runs neither path, and is safe for the reasons the durability rules already give: nothing the journal does not hold was ever promised, the marker left behind is reclaimed by the next daemon's verified stale-writer recovery, and the socket file is a stale path the next marker holder removes. +**The fatal-class map.** Every non-zero exit names one class on `stderr`: + +| Class | When | +| --- | --- | +| `store_writer_active` | Startup: the marker is held by a live holder | +| `store_writer_unverifiable` | Startup: the marker's holder cannot be decided | +| `store_log_too_large` | Startup: the log is already past the capacity bound | +| `session_index_too_large` | Startup: the directory holds more than the index bound | +| `socket_path_too_long` | Startup: the path exceeds the derived `sun_path` bound | +| `socket_permission_unverified` | Startup: subdirectory or socket ownership/mode could not be verified | +| `store_lost` | Fail-stop: the Store terminated under a live listener | +| `store_capacity_exceeded` | Fail-stop: the Store terminated on the capacity refusal specifically | +| `supervision_fault` | Fail-stop: a lease owner failed, under ADR 0033's daemon-fatal rule | + +**Reverse cleanup.** Every startup failure *after* the marker is acquired +unwinds what it has done, in reverse: an unlinked-and-bound socket is closed +and its path unlinked, a created `daemon/` subdirectory it made is removed, +and the Store is stopped so its `terminate/2` releases the marker. A daemon +that refuses to start leaves no marker and no socket file behind, which is +what lets an operator fix the cause and try again without a recovery step. + **Witnesses**, all on real operating-system processes: - **Idle shutdown.** A daemon with sessions activated and no work in flight @@ -572,14 +636,27 @@ the next marker holder removes. exits `0`; the foreground server then opens the same root immediately, which is what proves the marker was actually released. - **In-flight shutdown.** A daemon with a dispatched tool effect and an - unresolved mutation receives `SIGTERM`; the effect terminates through the - configured cancellation sequence with a truthful terminal, the ambiguous - mutation is left as `commit_unknown` rather than reported committed, every - client receives the stop reason, and the exit is still `0`. Reopening the - root afterwards resolves that transaction to exactly one outcome. -- **Fatal exit.** Store loss under a live listener closes the listener and - every connection with `store_lost`, unlinks the socket, and exits non-zero - with that class on `stderr`. + unresolved mutation receives `SIGTERM`. What has not settled within the + cleanup grace is ended crash-equivalently, and the case asserts the negative + that matters: **no terminal mutation is claimed** for it — no `cancelled`, + no `outcome_unknown`, no abort record appears in the journal on the way + down. The ambiguous mutation stays `commit_unknown`, every client receives + the stop reason, and the exit is still `0`. Activating that session again + afterwards resolves the transaction to exactly one outcome through the + existing reconciliation, and the journal is byte-identical to what an + abrupt death at the same instant would have left. +- **Store-loss fail-stop.** The Store is made to terminate under a live + listener. The case asserts the daemon observed it, closed the listener and + every connection with `store_lost`, unlinked the socket, and exited non-zero + with that class on `stderr` — and that it did **not** attempt the ordered + sequence, because the marker was already released by the Store's own + `terminate/2` before the daemon could act. A second daemon starts on that + root immediately with no stale marker to recover. The capacity variant + reports `store_capacity_exceeded` instead. +- **Reverse cleanup.** A startup made to fail after the marker is acquired — + at the socket permission check and at the index bound, separately — leaves + no marker held and no socket file behind, proved by a second daemon starting + cleanly on the same root with no recovery step. - **Readiness ordering.** A client that connects the instant the readiness line appears is served; no readiness line is printed when the marker is held elsewhere, the socket permission check fails, or the index bound is diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 6beaf2600..888d1e4aa 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -309,14 +309,26 @@ or released lease, and reconnects at its cursor. The released offline `loopex sessions` is unchanged, and the live listing is a separate explicit form of it. -An orderly stop is a sequence, not a word, so the plan writes it out: refuse -new connections and new admissions, drain what was already admitted within the -composed cleanup grace and settle the rest through the paths core already -commits to — the configured cancellation sequence with its bounds, and -`commit_unknown` left fenced for reconciliation — never abandoning admitted -work silently, tell every client the reason on the wire, unlink the socket, -and stop the Store last, which is when its `terminate/2` releases the marker. -The technical companion fixes each contract and each step exactly. +A daemon ends in one of two ways and the plan keeps them apart, because the +code does. **A daemon-initiated stop** is a sequence: refuse new connections +and new admissions, let admitted work drain within the composed cleanup grace, +then end what has not settled by stopping the runtime — which is +crash-equivalent by construction and therefore **claims no terminal outcome** +for that work, leaving `commit_unknown` fenced for the reconciliation that +already exists — then tell every client the reason on the wire, unlink the +socket, and stop the Store last, which is when its `terminate/2` releases the +marker. The daemon runs no cancellation of its own; cancellation is a +session's own durable command and a daemon-side path for it would be the +second loop this milestone forbids. + +**A store loss is not that sequence at all.** The local adapter answers an +append error by terminating itself, and its `terminate/2` releases the marker +on the way out, so by the time the daemon observes anything the store is gone +and the marker is already released. It is a fail-stop: refuse service, close +every connection with the reason, unlink the socket, exit non-zero. There is +no "stop the Store last" step to run when the Store is what died. The +technical companion fixes both paths, the fatal-class map and the reverse +cleanup a failed startup performs. At the closure candidate, every tracked file under `docs/operator/` and `docs/developer/` is read for consistency with M5, for relevance, links and From 5dc264791799733d9929a89d3154ef07a9321210 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:16:36 -0700 Subject: [PATCH 042/585] adr(0032): make residency a daemon fact, drop the coordinator-loss rule Fifth-review decision 3, reversing what the fourth round put in. `residency` now means exactly "this daemon activated this session in this lifetime" -- a daemon-owned fact, recorded when the daemon acted, true by construction and needing nothing from any other process to stay accurate. The previous definition, "the daemon holds a live coordinator", was a claim about core's state the daemon cannot keep current, and it was paid for with a rule that took the whole daemon down when a coordinator died. Both are withdrawn. Verified in code: a coordinator is a restart: :temporary child of core's DynamicSupervisor (control.ex:1115, session_coordinator.ex:134-142), and when one goes down Loopex.Runtime.Control consumes the DOWN, releases the dispatcher fence and returns without altering the session entry (control.ex:821). No notification leaves core and none is owed. So a dead coordinator surfaces as core's existing refusal on the next command for that session, which the daemon forwards unchanged, adding and interpreting nothing -- the client learns at the moment it matters, from the component that knows. Both alternatives are recorded as rejected because both are third core changes: a lifecycle notification would be a new core-to-host signal with its own delivery and ordering questions, added for a listing field; a monitorable coordinator handle would export core's supervision topology across the boundary. M5's core changes stay at two. The lease-owner fatal rule stays untouched, and the pair now says why the two cases differ: a lease owner is a daemon process holding daemon-only state nothing can reconstruct, while a coordinator is core's, supervised by core, and its loss is core's to report. --- ...tachment-residency-and-replay-technical.md | 77 +++++++++++-------- ...-daemon-attachment-residency-and-replay.md | 9 ++- docs/plans/M5-technical.md | 2 +- docs/plans/M5.md | 12 +-- 4 files changed, 58 insertions(+), 42 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 25f5b0d9a..7ac7137fb 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -168,41 +168,54 @@ the daemon itself owns or reads once: - `session_id` and the recorded placement identity, read from the directory entry at daemon start, or written when the daemon first activates a session the directory does not hold; -- `residency`, a daemon fact, set to `active` at activation and never set back - within a daemon's lifetime, because activation is one-way; +- `residency`, a daemon fact meaning *this daemon activated this session in + this lifetime*, set to `active` at activation and never set back, because + activation is one-way. It is not a claim about a live coordinator; - `controlled`, a daemon fact, updated on every lease grant, release and expiry by the same per-session owner ADR 0033 gives those transitions. -**Keeping `residency` honest costs a rule, and this pair pays it.** `active` -means the daemon holds a live coordinator. The index sets it once and never -back. Put those together and a coordinator that dies would leave the index -saying `active` about a session that has none — a field that is silently -false, which is worse than an absent one and is exactly what the four list -fields were narrowed to avoid. - -Core does not close that gap for us. `Loopex.Runtime.Control` monitors each -coordinator, and when an `:active` one goes down it releases the dispatcher -fence and returns without altering the session entry, which keeps the entry in -place with a dead coordinator pid. That is the right thing for core to do and -it is not a defect; it simply means no notification arrives that the daemon -could use to move the index. - -So **the loss of an activated session's coordinator is fatal to the daemon -instance**, by the same rule and the same supervision shape ADR 0033 gives a -lease owner's failure: `one_for_all` up to the listener, every connection -closed, the daemon exits and restarts with nothing activated, no lease, and an -index rebuilt from the directory in which every session is `dormant` and -`controlled` is false — which is exactly true of a daemon that has activated -nothing. The activation count starts again with it, since the ceiling counts -activations per daemon lifetime and a restart is a new lifetime. - -The alternative — a lifecycle notification from core, an index transition to -some third state, and a recovery route back to `active` — was rejected. A -transition out of `active` is a deactivation, and deciding when a session may -leave `active` is deciding when its coordinator may stop: that is the core -deactivation operation M5 does not have and cannot invent here, wearing a -different name. Taking the daemon down instead costs an outage and buys a -listing that is never wrong. +**`residency` says what the daemon knows, not what core is doing.** Its two +values mean exactly: + +- `active` — **this daemon activated this session during this lifetime**; +- `dormant` — it has not. + +That is a daemon-owned fact, recorded by the daemon at the moment it acted, +and it is **true by construction**: nothing else has to hold for it to stay +accurate, and no other process has to tell the daemon anything. + +An earlier draft defined `active` as "the daemon holds a live coordinator", +which is a claim about core's state that the daemon has no way to keep +current, and then paid for it with a rule that took the whole daemon down when +a coordinator died. Both are withdrawn. The reason the first was untenable is +in the code: a coordinator is a `restart: :temporary` child of core's +`DynamicSupervisor`, and when one goes down `Loopex.Runtime.Control` consumes +the `DOWN`, releases the dispatcher fence and returns without altering the +session entry. No notification leaves core, and none is owed — that is core +minding its own supervision. + +**So a dead coordinator is surfaced by core's own refusal, not by the index.** +A client that sends the next command for that session gets core's existing +refusal, and the daemon forwards it unchanged, adding nothing and interpreting +nothing. The client learns at the moment it matters, from the component that +knows, and the listing never claimed otherwise: `residency: active` said this +daemon activated the session, which remains true. The activation ceiling still +counts activations per daemon lifetime, for the same reason — it counts what +the daemon did. + +Two alternatives were rejected, and both are **third core changes** this +milestone does not make. A lifecycle notification from core to the daemon +would be a new core-to-host signal, with its own delivery and ordering +questions, added for a listing field. A monitorable coordinator handle handed +out to the daemon would export core's supervision topology across the boundary +and invite the daemon to reason about it. M5's core changes stay at two: +concurrent attachment, and the read-only existence query. + +The lease-owner fatal rule in ADR 0033 is untouched by this and stays. The +difference is ownership: a lease owner is a **daemon** process holding +daemon-only state that nothing can reconstruct, so losing it is the daemon's +failure to handle; a coordinator is core's, supervised by core, and its loss +is core's to report. Lineage, lifecycle state and last committed sequence are deliberately absent. A daemon index cannot keep them current without reading the Store on the diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index f46a98319..21ec036df 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -105,10 +105,11 @@ unresolved `commit_unknown` or an executing admission in flight, and because stopping one would need a core deactivation operation M5 does not add. The cost is stated rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th refuses, and the remedy is to restart the daemon. -Losing an activated session's coordinator is fatal to the daemon instance for -the same reason a lease owner's loss is — core signals no lifecycle transition -the daemon could use, so the only way to keep `active` from meaning something -false is to stop being a daemon that claims it. +`residency` therefore means *this daemon activated this session in this +lifetime* — a daemon-owned fact, true by construction — and never *a live +coordinator exists*, which the daemon has no way to know. A coordinator that +dies is core's to supervise and surfaces through core's own refusal on the +next command for that session, which the daemon forwards unchanged. Lazy recovery is what a daemon can honestly promise on a store whose session directory is not Store truth and whose every open replays a full log. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 52b674cc2..0ae491937 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -129,7 +129,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator takes the listener, every connection and the daemon down with it, after which the rebuilt index reports every session `dormant` and `controlled` false; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written at the next daemon start when the index is rebuilt; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written at the next daemon start when the index is rebuilt; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs on the Linux lane as `mix test --only cross_uid`, where the suite-summary judge makes a zero executed count red rather than a skip. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 888d1e4aa..b61f49da3 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -115,11 +115,13 @@ read-only existence query — neither of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation refuses with a stable reason, and the operator's remedy is to restart the -daemon. Losing an activated session's coordinator is fatal to the daemon -instance, the same rule a lease owner's loss carries: core signals no -lifecycle transition the daemon could act on, so the alternative is an index -that says `active` about a session with no coordinator, and a listing field -that is silently false is worse than an outage. Lifting it needs a core operation that can tell quiescent from idle, +daemon. And `residency` means what the daemon can actually know: *this daemon +activated this session in this lifetime*, true by construction, never *a live +coordinator exists*. A coordinator is core's `restart: :temporary` child and +its loss is core's to supervise; it reaches a client as core's existing +refusal on the next command for that session, which the daemon forwards +unchanged. Making the daemon track it would need a core notification or a +monitorable handle — a third core change M5 does not make. Lifting it needs a core operation that can tell quiescent from idle, which is its own decision and not M5's. `session.list` is a daemon convenience, not an enumeration of durable truth. From 84d5a8f2fae11a04e7b2a34d6125aa76e4aef47a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:18:00 -0700 Subject: [PATCH 043/585] plan(M5): complete the operator workflow end to end Fifth-review decision 4. The CLI contracts described starting and attaching but never said how a session gets created over the socket, what a daemon is composed from, or what happens when a lease renewal fails. (a) Composition inputs are now a table with default and refusal class each, taken from what LoopexAppServer.Host already documents at host.ex:23-31 -- state root, workspace, provider launch, policy (no default, deliberately: authority is the operator's to name), provider credential checked at start, cleanup grace, project resources, socket path. Each is refused before the marker is acquired where possible; the rest are covered by reverse cleanup. A --socket override is constrained by the same owner, mode and symlink rules as the default. (b) Sessions reach the socket through daemon forms of commands an operator already knows: loopex run --daemon creates and drives, loopex resume --daemon activates a dormant session through acquire, resume with a fresh command ID, attach. loopex attach joins an already-activated session and is restricted to observe or one-shot control with --take-over and --prompt/stdin. The restriction is stated as a decision, not an omission: a multi-turn interactive controller needs an input-framing, steering and interrupt contract this milestone does not have, and driving many turns is what the run and resume forms already do. (c) Initial cursor is --after , else 0 and a full replay -- a client that did not say where it left off has not established a position. (d) The controller CLI renews every ten seconds against the thirty-second term; a failed renewal stops mutations at once, reports on stderr and continues as an observer rather than racing the deadline. (e) Attaching as an observer to a session this daemon has not activated is refused with session_dormant. Attaching does not activate: activation starts a coordinator and counts against the ceiling, so it is a controller's act. (f) A reconnecting controller acquires again and takes a fresh epoch before any mutation, resuming first if the session went dormant -- the same acquire, resume with fresh command ID, attach, drive sequence ADR 0033 fixes, so the CLI contract and that ADR now say it the same way. The readiness line becomes one JSON object on one line, because a root or socket path may contain a space or newline and a phrase would be ambiguous. --- docs/plans/M5-technical.md | 142 +++++++++++++++++++++++++++++-------- docs/plans/M5.md | 21 ++++-- 2 files changed, 129 insertions(+), 34 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0ae491937..650c78aa8 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -133,7 +133,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs on the Linux lane as `mix test --only cross_uid`, where the suite-summary judge makes a zero executed count red rather than a skip. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach --observe` refused with `session_dormant` against a session this daemon has not activated and succeeding against one it has; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The three credential-bearing calls in the sender — the registry route call, the custody reply handling and the credential frame write — are excluded from tracing by match specification, as accepted ADR 0030 already requires of a key-bearing call, and the proof is an absence: under a real trace session at the `arguments` level no trace entry names any of the three, the tracer receives no raw trace message for them, and no credential bytes and no token appear in any captured entry. A placeholder entry for one of them fails the case as surely as the bytes would. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every @@ -441,16 +441,41 @@ or the daemon refuses the arguments. #### `loopex daemon`: starting, readiness, stopping -**Selection.** `loopex daemon [--state-root DIR] [--socket PATH]`. The root -resolves as every other command resolves it. The socket defaults to -`/daemon/daemon.sock` in the `0700` daemon-owned subdirectory; a -`--socket` beyond the platform's derived `sun_path` bound is refused at start -with `socket_path_too_long` before anything else happens. - -**Readiness.** Exactly one line on `stdout`, and nothing else on that stream: - -```text -loopex daemon ready root= socket= incarnation= +**Composition inputs.** A daemon is a host, so it takes the same inputs the +app-server host takes today, as flags with environment fallbacks, and refuses +the same way — `LoopexAppServer.Host` documents them and halts on standard +error when one is missing or unusable. The daemon's set, each with its default +and its refusal class: + +| Input | Flag / environment | Default | Missing or invalid | +| --- | --- | --- | --- | +| State root | `--state-root` / `LOOPEX_HOME` | none | `state_root_required`, or `state_root_unusable` when it cannot be created or read | +| Workspace | `--workspace` / `LOOPEX_WORKSPACE` | none | `workspace_required`, `workspace_unusable` | +| Provider launch | `--provider-launch` / `LOOPEX_PROVIDER_LAUNCH` | none | `provider_launch_required`, `provider_launch_invalid` | +| Policy | `--policy` / `LOOPEX_POLICY` | **none, deliberately** — authority is the operator's to name, as the app-server host already insists | `policy_required`, `policy_unknown` | +| Provider credential | `LOOPEX_PROVIDER_API_KEY` | none | `provider_credential_required`, checked at start so an unattended launch refuses in a second rather than at the first dispatch. The daemon reads it once, deletes it from its environment and holds it in custody under ADR 0034 | +| Cleanup grace | `--cleanup-grace-ms` | the composition default | `cleanup_grace_invalid` | +| Project resources | as the host already takes them | as today | as today | +| Socket path | `--socket` | `/daemon/daemon.sock` | `socket_path_too_long`, `socket_permission_unverified` | + +Every one of these is refused **before** the marker is acquired where that is +possible, so the common operator mistake costs nothing and leaves nothing +behind; the ones that can only fail later are covered by the reverse-cleanup +rule. + +A `--socket` override is constrained exactly as the default is: its parent +directory must be owned by the daemon's user and mode `0700`, no component +below the state root may be a symbolic link the daemon did not create, and the +socket is created `0600` and verified after bind. An override does not buy a +weaker rule; it only moves where the rule applies. + +**Readiness.** Exactly one line on `stdout`, and nothing else on that stream. +It is **one JSON object on one line**, not a space-separated phrase, because a +state root or socket path may contain a space or a newline and a phrase would +then be ambiguous to the process manager parsing it: + +```json +{"record":"daemon_ready","root":"…","socket":"…","incarnation":"…","version":"0.2.0"} ``` It is printed **only after** all of: the Store is open and its writer marker @@ -475,23 +500,78 @@ naming its class rather than a stack: `store_writer_active`, `socket_permission_unverified`, `session_index_too_large`, `store_lost`, and `supervision_fault` for the daemon-fatal rules ADR 0032 and ADR 0033 define. -#### `loopex attach`: driving and watching - -`loopex attach --daemon [--observe] [--take-over]`. - -- Default is **controller**: acquire control, then attach, then drive. If - another connection holds the lease the command refuses with `control_held`, - naming the epoch that holds it, rather than waiting. -- `--observe` attaches without acquiring and never sends a mutation. An - observer that tries is refused by the daemon, not by the client, which is - where the rule belongs. -- `--take-over` asks for control on a lease that is released or expired and - waits while an in-flight admission settles, as ADR 0033's linearization - requires. It never forces a live holder off. -- **Cursor and reconnect.** The client remembers the last event cursor it - emitted and, on transport loss, reconnects at it, deduplicating by session - ID, event sequence and event ID. Delivery is contiguous and at least once, - so a duplicate at the seam is expected and a gap is a defect. +#### How a session is created and driven over the socket + +`loopex attach` alone cannot start work, because a session has to exist and be +resumed before anything can be sent to it. The daemon forms of the two +released commands are what reach the socket: + +- **`loopex run --daemon --policy … ""`** — creates a session + and sends its first prompt. It performs the whole sequence: `session.create`, + then `session.acquire_control`, then the prompt under the granted writer + epoch, then attach, then stream. The offline `loopex run` is unchanged and + keeps composing its own runtime; `--daemon` is what redirects it. +- **`loopex resume --daemon `** — reaches an existing + session. It performs ADR 0033's sequence exactly: acquire control, then + `session.resume` with a **fresh resume command ID** and the granted epoch, + then attach, then stream. That is the sequence that activates a dormant + session, and it is the only one that does. +- **`loopex attach --daemon `** — joins a session that is + already activated. It does **not** resume, so it does not activate. + +**`loopex attach` is observe-or-one-shot-control, and that is a deliberate +restriction.** Its forms are: + +| Form | What it does | +| --- | --- | +| `--observe` (default when neither role flag is given) | Attaches without acquiring, streams events, sends nothing. Refused by the daemon, not the client, if it ever tries | +| `--take-over` | Acquires a released or expired lease, waiting while an in-flight admission settles as ADR 0033's linearization requires; never forces a live holder off. Then attaches and streams | +| `--take-over --prompt ""`, or `--take-over` with the prompt on stdin | The same, plus **one** command under the granted epoch, then streams to a terminal outcome | + +There is no interactive multi-turn controller in M5. A controller that could +accept turn after turn from a terminal would need a full interactive contract +— input framing, mid-run steering, interrupt handling, what a partial line +means — and none of that is in this milestone's scope. One-shot control is +what the two-process demonstration actually needs, and the restriction is +stated here so it is a decision rather than an omission. Multi-turn driving is +`loopex run --daemon` and `loopex resume --daemon`, which already own it. + +**Initial cursor.** `--after ` starts the stream strictly after that +event sequence. Without it the cursor is `0` and the client receives the +session's full replay, which is the honest default: a client that did not say +where it left off has not established a position, and silently starting at the +live tail would hide everything before it. + +**Lease renewal, and what a failed renewal does.** A controller CLI renews +every ten seconds against a thirty-second term, as ADR 0033's proposed terms +fix. A renewal that is refused or that cannot be sent is not retried silently: +the client stops sending mutations immediately, reports the loss on `stderr`, +and continues **as an observer** on the same attachment until the process +ends or the operator re-runs with `--take-over`. It does not race the +deadline, because a mutation sent after the term elapsed will be refused +anyway and a client that keeps trying only obscures when control was lost. + +**A dormant session refuses an observer.** `loopex attach --observe` against a +session this daemon has not activated is refused with `session_dormant`, +naming the remedy: `loopex resume --daemon`. Attaching does not activate. +Activation is a controller's act — acquire, then resume with a fresh command +ID — because it starts a coordinator and counts against the activation +ceiling, and letting a read-only observer trigger it would let a watcher +consume a resource a controller needs and start durable recovery nobody asked +for. + +**Cursor, reconnection and re-acquisition.** The client remembers the last +event cursor it emitted and, on transport loss, reconnects at it, +deduplicating by session ID, event sequence and event ID; delivery is +contiguous and at least once, so a duplicate at the seam is expected and a gap +is a defect. A reconnecting **controller** does not resume its old authority: +the lease it held is expiring or expired, and it must acquire again and +receive a **fresh writer epoch** before any further mutation. If the session +went dormant in between — because the daemon restarted — it must resume +first, with a fresh resume command ID under that new epoch. That is the same +acquire → resume → attach → drive sequence ADR 0033 fixes, reached from a +different starting point, and the CLI contract and that ADR say it the same +way on purpose. Exit status: `0` when the session reaches a terminal outcome or the operator detaches; non-zero on a refusal, or on a transport loss reconnection could not @@ -502,9 +582,11 @@ repair, with the reason class on `stderr`. | Contract | Operator page | | --- | --- | | `loopex sessions` offline, unchanged | `docs/operator/coding-sessions.md`, its existing command rows, reviewed unchanged | +| `loopex run` and `loopex resume` offline, unchanged | `docs/operator/coding-sessions.md`, reviewed unchanged | +| `loopex run --daemon`, `loopex resume --daemon` and the create-and-drive sequence | `docs/operator/daemon.md`, driving section | | `loopex sessions --daemon`, `--limit`, `--after`, `--status`, `index_full` | `docs/operator/daemon.md`, listing section | -| `loopex daemon` selection, readiness line, signals, exit classes | `docs/operator/daemon.md`, running section | -| `loopex attach` roles, takeover, reconnect, exit classes | `docs/operator/daemon.md`, attaching section | +| `loopex daemon` composition inputs, readiness record, signals, exit classes | `docs/operator/daemon.md`, running section | +| `loopex attach` roles, one-shot control, `--after`, renewal loss, `session_dormant`, reconnect and re-acquisition | `docs/operator/daemon.md`, attaching section | ### Daemon Lifecycle and Orderly Shutdown diff --git a/docs/plans/M5.md b/docs/plans/M5.md index b61f49da3..3776f2c2e 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -306,10 +306,23 @@ the socket is bound and permission-checked — sends everything else to standard error, stops on `SIGTERM` or `SIGINT`, and exits `0` for an operator stop or non-zero with a named reason class for a fatal one. There is no stop method on the wire, because ending every client's session residency is not authority a -connection carries. `loopex attach` drives or observes, takes over an expired -or released lease, and reconnects at its cursor. The released offline -`loopex sessions` is unchanged, and the live listing is a separate explicit -form of it. +connection carries. A daemon takes the same composition inputs the app-server host takes — state +root, workspace, provider launch, policy, provider credential, cleanup grace, +project resources — as flags with environment fallbacks, and refuses each +missing or invalid one with its own class. + +Reaching a session over the socket is the daemon form of a command an operator +already knows: `loopex run --daemon` creates a session and drives it, +`loopex resume --daemon` activates a dormant one through acquire, resume with +a fresh command ID and attach, and `loopex attach` joins one that is already +activated — as an observer, or as a one-shot controller with `--take-over`. +There is no interactive multi-turn controller in M5, which is a restriction +stated rather than an omission: driving many turns is what the `run` and +`resume` forms already do. Attaching never activates, so an observer meets +`session_dormant` and is told to resume. A reconnecting controller acquires +again and receives a fresh epoch before any further mutation. The released +offline `loopex sessions`, `run` and `resume` are unchanged, and each live +form is a separate explicit `--daemon` form of them. A daemon ends in one of two ways and the plan keeps them apart, because the code does. **A daemon-initiated stop** is a sequence: refuse new connections From ab85507b6e279a345f9f9bcbb09944666b20e8f3 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:26:27 -0700 Subject: [PATCH 044/585] adr(0032): live-daemon directory retry, add daemon.stopping Fifth-review decisions 5 and 6. Decision 5: the directory-entry retry is bound to the moments a live daemon still holds the session ID -- immediately after activation, on each later command for that session, and when any later client reaches it by ID or replays its create command -- stopping as soon as it succeeds. Two earlier answers are withdrawn with their reasons. "At the next activation" cannot happen because activation is one-way. "At the next daemon start" cannot happen for a sharper reason: a restarted daemon builds its index FROM the directory, so a session the directory does not hold is one the new daemon has never heard of and has no ID to retry with. Decision 6 adds generation 2's one notification record family, daemon.stopping, with reason in {operator_stop, store_lost, store_capacity_exceeded, fatal:}, a bounded non-secret message, and retry_after_ms present only for operator_stop -- a daemon that failed does not know when its cause will be fixed. Delivery is one write attempt into the connection's existing 4 MiB output buffer, then close regardless, so a backpressured or dead client may learn of the shutdown only by its socket closing, and the pair says that rather than implying the record always arrives. The bound is the buffer's rather than a millisecond deadline, recorded as a choice: a new timer would be a number this milestone introduces, and the minimalism budget requires every number to come from an accepted or proposed decision. One non-blocking attempt into an existing bound is the same guarantee with nothing new to justify. A new record family changes what schema_digest/0 is taken over, so the generation-2 digest statement now says the literal includes daemon.stopping and a generation 2 omitting it computes a different value and fails there. Generation 1's digest is untouched. --- ...tachment-residency-and-replay-technical.md | 61 ++++++++++++++++--- ...-daemon-attachment-residency-and-replay.md | 8 ++- docs/plans/M5-technical.md | 13 ++-- 3 files changed, 69 insertions(+), 13 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 7ac7137fb..df4be8907 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -151,6 +151,40 @@ enforced inside core. | `daemon.status` | none | Placement identity, daemon incarnation, socket path, attachment, active-session and index counts against their limits, uptime | | `session.acquire_control`, `session.release_control` | `session_id`, `request_id` and the lease fields ADR 0033 fixes | Lease result naming the writer epoch and the remaining lease term | +Generation 2 also adds **one notification record family**, `daemon.stopping`, +which no client requests and every client may receive: + +| Field | Value | +| --- | --- | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining fatal classes the plan's map names | +| `message` | A bounded non-secret sentence for an operator to read | +| `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | + +**Its delivery is bounded best-effort, and the bound is one the daemon already +has.** The daemon makes exactly **one** write attempt of the record into the +connection's existing 4 MiB output buffer and then closes the connection +regardless of what happened. If the buffer cannot accept it — a backpressured +client that has not been reading — the record is dropped and the connection is +closed anyway. A dead client receives nothing at all. **So a client may learn +of a shutdown only by its socket closing**, and this pair says so rather than +implying the record always arrives; a client that treats an unexplained close +as a defect would be wrong. + +The bound is the buffer's, not a new timer: a millisecond deadline would be a +number this milestone introduces, and the minimalism budget requires every +number to come from an accepted or proposed decision. One non-blocking attempt +into a bound that already exists is the same guarantee with nothing new to +justify. + +**This changes the generation-2 digest, and that is the point of saying it +here.** `Loopex.Protocol.Session.schema_digest/0` is taken over the +generation, the ordered methods, the ordered record families, the ordered +error codes and the limits. `daemon.stopping` is a new **record family**, so +generation 2's digest reflects it; the literal the conformance module pins for +generation 2 is the digest of the contract *including* this record, and a +generation 2 that omitted it would compute a different value and fail there. +Generation 1's digest is untouched, since generation 1 has no such record. + ### The session index, and what it may claim `session.list` reads a daemon-owned index, never the session directory or the @@ -324,13 +358,26 @@ durable record and no Store read by the daemon: as an explicit warning that this session will not appear in `session.list` — the reference CLI already reports exactly that failure today. The activation itself succeeds, the session is fully usable, and the daemon - retries the record at the next **daemon start**, when the index is rebuilt - from the directory and the missing entry is written then. It cannot be - "the next activation of that session", which an earlier draft said: - activation is one-way, so within a daemon's lifetime there is no next - activation to retry at. Until the restart, the session is reachable by ID - and absent from `session.list`, which is exactly what the client was - told. + **retries while it still holds the ID**, which is the only time it can: + + - immediately after activation, once; + - on each later command for that session, since the daemon has the ID in + hand at that moment anyway and the retry costs one file write it already + knows how to make; + - and when any later client reaches the session by ID, or replays its + create command, since both paths put the ID back in the daemon's hands. + + The retry stops as soon as it succeeds. Two earlier answers were wrong and + both are withdrawn. "At the next activation of that session" cannot happen: + activation is one-way, so within a lifetime there is no second one. "At the + next daemon start" cannot happen either, and for a sharper reason — a + restarted daemon builds its index *from the directory*, so a session the + directory does not hold is a session the new daemon has never heard of. It + has no ID to retry with. Only a live daemon that still holds the ID can + repair the gap, which is why the retry is bound to the moments it does. + + Until it succeeds, the session is reachable by ID and absent from + `session.list`, which is exactly what the client was told. 4. **A full index still activates.** If the index already holds 4,096 entries and a client reaches an unrecorded session by ID, the session is activated and is **not** recorded. Reachability never depends on the ceiling. What diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 21ec036df..6f48d7608 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -37,7 +37,13 @@ unchanged — and its request records with exactly one addition, the generation 2 a new schema digest rather than a rename. It serves exactly one generation, `loopex.experimental/2`, which adds `session.list`, `daemon.status`, the two -control methods and the writer-epoch field ADR 0033 names. It adds no durable +control methods, the writer-epoch field ADR 0033 names, and one notification +record family, `daemon.stopping`, carrying the reason a daemon is going away. +That record is a new record family, so it is part of what generation 2's +schema digest is taken over; its delivery is one bounded best-effort write +attempt into the connection's existing output buffer, after which the +connection closes whatever happened, so a client may learn of a shutdown only +by its socket closing. It adds no durable method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core has no durable stop command, and M5's core changes are concurrent attachment diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 650c78aa8..36f09a798 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,7 +130,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written at the next daemon start when the index is rebuilt; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs on the Linux lane as `mix test --only cross_uid`, where the suite-summary judge makes a zero executed count red rather than a skip. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason it carries, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs on the Linux lane as `mix test --only cross_uid`, where the suite-summary judge makes a zero executed count red rather than a skip. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach --observe` refused with `session_dormant` against a session this daemon has not activated and succeeding against one it has; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -647,10 +647,13 @@ from that instant: authority, at the moment it is least able to see them through. An unbounded natural drain — waiting for every effect to finish — would make `SIGTERM` unbounded, which is not a stop. -3. **Tell every client, then close.** Each connection receives one - `daemon.stopping` notification naming the reason, and the daemon then - closes it. Delivery is bounded best-effort; the record and its bound are - fixed in ADR 0032, and a backpressured or dead client may not receive it. +3. **Tell every client, then close.** Each connection gets one + `daemon.stopping` notification naming the reason — `operator_stop` here — + and the daemon then closes it. Delivery is bounded best-effort: one write + attempt into the connection's existing 4 MiB output buffer, then close + regardless. ADR 0032 fixes the record and that bound, and a backpressured + or dead client may receive nothing and learn of the stop only by its socket + closing. 4. **Unlink the socket.** The path is removed, so no later client connects to a dead endpoint and the next daemon binds cleanly rather than inheriting a stale file. From fa6f68a3d40cfa94a81eaddb0c17798c7692cd5a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:20:13 -0700 Subject: [PATCH 045/585] adr(0034): runtime-local registry handle, exclusion by named MFA Fifth-review decisions 7 and 8. Decision 7. The "runtime-scoped registered name" is withdrawn: a registered name on the BEAM is VM-global whatever it is called, so two runtimes in one VM would share one namespace with a convention holding them apart, and a convention is not isolation. The reference becomes a runtime-local capability handle of the class the runtime already takes -- verified: runtime.ex:941-970 validates an executor configuration carrying reference:, and loopex_composition.ex:290 fills it with the live pid start_edge/2 returned, composition data that is never durable and never public. The credential registry handle is written the same way, %Loopex.LLM.ReqLLM.CredentialRegistry.Handle{} wrapping that live reference, so it is self-describing in an options list. Lookup is route(handle, token) -> {:ok, custody_ref} | {:error, :unavailable}, a call to the registry process. Lifetime is the host supervisor's, and a registry restart leaves the handle invalid -- every resolution answers :unavailable until the host recomposes, with no retry, wait or rebuild, the same shape as losing custody. Two-runtime isolation is a required proof: two hosts, two registries, and neither token resolves in the other's runtime. Decision 8. A match specification needs a target, so the three credential-bearing calls are named private functions that must exist -- ProviderBridge.route_credential/2, receive_custody_reply/2 and write_credential_frame/2 -- and their identities are part of the contract. A second test asserts they exist with exactly those identities, so inlining or renaming one breaks the proof loudly instead of silently removing the match specification's target and widening what a trace session can capture. The Concept file now says "excluded by match specification" and spells out the difference: an excluded call produces no trace entry at all, where a redacted one would produce an entry with a placeholder. --- ...andoff-over-bootstrap-channel-technical.md | 81 +++++++++++++------ ...edential-handoff-over-bootstrap-channel.md | 9 ++- docs/plans/M5-technical.md | 2 +- 3 files changed, 63 insertions(+), 29 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 261f07e9c..b9ef073f6 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -97,26 +97,45 @@ separate: runtime, that every invocation needs. Composition puts the registry reference there, under its own key, beside the token the caller supplies per invocation. -- **It is plain data, and a name rather than a pid.** The reference is a - runtime-scoped registered name — bounded, serializable, meaningless in - another VM and in another runtime — never a pid, port or function. The - boundary rule that keeps PIDs out of durable and public data is not - negotiated here; a registered name satisfies it and a pid would not, and a - name also survives the registry process being restarted by its own - supervisor, which a pid does not. -- **No global state.** The name is scoped to the runtime, so two runtimes in - one VM have two registries and neither can reach the other's. Nothing is - read from application environment and nothing is looked up by a fixed - global name, which is the rule core already holds itself to. +- **It is a runtime-local capability handle, exactly the class the runtime + already takes.** The precedent is the executor: `Loopex.Runtime`'s executor + configuration carries `reference:`, and `LoopexComposition` fills it with + the live pid `start_edge/2` returned. That reference is composition data, + never durable and never public, and it is what the runtime hands the + adapter at dispatch. The credential registry handle is the same class and + is written the same way — `%Loopex.LLM.ReqLLM.CredentialRegistry.Handle{}` + wrapping that live reference, so the value is self-describing at a glance + and cannot be mistaken for anything else in an options list. + + An earlier draft made it a *runtime-scoped registered name*. That is + withdrawn: a registered name on the BEAM is VM-global whatever it is called, + so two runtimes in one VM would be one namespace with a convention holding + them apart, and a convention is not isolation. A handle carrying a live + reference is scoped by who holds it, which is the property actually wanted. +- **The boundary rule is respected because of where it lives, not because of + what it is.** The rule keeps PIDs out of durable and public data; a handle + in composition data is neither, exactly as the executor's `reference:` is + neither. It is never journaled, never in a public event or snapshot, never + on the wire, and never in a token. +- **Two runtimes are isolated by construction.** Each host composes its own + registry and holds its own handle; a token from one runtime presented in + the other reaches a registry that has no row for it and answers + `:unavailable`. That is a required proof, not an assertion: two hosts, two + registries, two tokens, and neither token resolves in the other's runtime. - **The lookup is one operation, and it is the host's.** - `route(registry_ref, token) -> {:ok, custody_ref} | {:error, :unavailable}`. - It returns *where to ask*, never bytes; `:unavailable` covers a registry - that is gone and a token with no row, because from the sender's side those - are the same fact and neither is recoverable by asking again. -- **Its lifetime is the host's.** The host starts the registry when it - composes the runtime and it dies with recomposition. The adapter neither - starts it, supervises it nor restarts it, and a sender that finds it absent - refuses rather than waiting for it to come back. + `route(handle, token) -> {:ok, custody_ref} | {:error, :unavailable}`, a + call to the registry process. It returns *where to ask*, never bytes; + `:unavailable` covers a token with no row, a registry that is gone, and a + registry that does not answer — from the sender's side those are one fact + and none is recoverable by asking again. +- **Its lifetime is the host supervisor's, and a restart invalidates the + handle.** The host starts the registry under its own supervisor when it + composes the runtime. If the registry dies, the handle a composed runtime + holds is invalid and every resolution through it answers `:unavailable` + **until the host recomposes** — the adapter does not re-look-up, does not + wait and does not rebuild, because it has nothing to rebuild from. That is + the same shape as losing custody, and it is deliberate: recomposition is the + one repair, and it is the host's to perform. **Custody is a separate process, and is where the bytes live.** Each reference implementation states and proves its own: the reference CLI, the app-server @@ -164,11 +183,21 @@ boundary, not an absolute: this pair does not invent one, it names which calls that covers. They are three, all in the sender: - | Excluded call | Why | + A match specification needs a target, so the three are **named private + functions that must exist**, and their identities are part of this contract + rather than an implementation detail: + + | Excluded function | Why | | --- | --- | - | The registry route call | Its arguments carry the token, and the token is the credential reference | - | The custody reply handling | Its argument is the resolved credential | - | The credential frame write | Its argument is the resolved credential | + | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | Its arguments carry the registry handle and the token, and the token is the credential reference | + | `Loopex.LLM.ReqLLM.ProviderBridge.receive_custody_reply/2` | Its argument is the resolved credential | + | `Loopex.LLM.ReqLLM.ProviderBridge.write_credential_frame/2` | Its argument is the resolved credential | + + The names are the contract; the arities are as written here. Inlining any of + the three into its caller, or renaming one, removes the match + specification's target and silently widens what a trace session can capture + — so a test asserts the three exist with exactly these identities, and a + rename breaks the proof loudly instead of quietly. Exclusion by match specification means the trace session never matches those functions, so the VM emits **no raw trace message** for them and the @@ -187,8 +216,10 @@ boundary, not an absolute: received no raw trace message for them, and that no credential bytes and no token appear anywhere in the captured entries. An entry bearing a placeholder for one of them fails the case exactly as an entry bearing the - bytes would, because it would prove the match specification did not - exclude what it was supposed to. + bytes would, because it would prove the match specification did not exclude + what it was supposed to. A second, smaller case asserts the three functions + exist with the identities above, so the first case cannot pass vacuously + against a build where they no longer do. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index a7108c02a..479ef4cec 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -84,9 +84,12 @@ transfer — bounded, unlogged, never forwarded, never retained after the frame is written — and it is the same class of act as writing the credential frame, protected the same way ADR 0019 already protects that sender. The registry lookup before it carries no credential, so routing adds no second place a -secret can be seen, and the credential-bearing call is excluded from tracing -by ADR 0030's existing redaction class, which the companion names and M5 -proves. +secret can be seen, and the three credential-bearing calls are **excluded by +match specification**, the mechanism accepted ADR 0030 already fixes for a +key-bearing call. Exclusion, not redaction: an excluded call produces no trace +entry at all, where a redacted one would produce an entry with a placeholder. +The companion names the three functions exactly, because a match specification +needs a target, and M5 proves the absence. **Everywhere else the boundary is where the adapter's claims stop.** Inside it — the token, the sender, the frame, the child — the adapter proves what it diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 36f09a798..5a52dc5ab 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -134,7 +134,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach --observe` refused with `session_dormant` against a session this daemon has not activated and succeeding against one it has; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The three credential-bearing calls in the sender — the registry route call, the custody reply handling and the credential frame write — are excluded from tracing by match specification, as accepted ADR 0030 already requires of a key-bearing call, and the proof is an absence: under a real trace session at the `arguments` level no trace entry names any of the three, the tracer receives no raw trace message for them, and no credential bytes and no token appear in any captured entry. A placeholder entry for one of them fails the case as surely as the bytes would. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The three credential-bearing calls in the sender — `ProviderBridge.route_credential/2`, `receive_custody_reply/2` and `write_credential_frame/2` — are excluded from tracing by match specification, as accepted ADR 0030 already requires of a key-bearing call, with a second case asserting those three functions exist with exactly those identities so a rename or an inlining breaks the proof loudly rather than widening what a trace can capture. The proof is an absence: under a real trace session at the `arguments` level no trace entry names any of the three, the tracer receives no raw trace message for them, and no credential bytes and no token appear in any captured entry. A placeholder entry for one of them fails the case as surely as the bytes would. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Two runtimes composed in one VM, each with its own registry and custody, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the From 3be8020915c23a2781f3edf667969576bf71c129 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:26:27 -0700 Subject: [PATCH 046/585] plan(M5): cross-UID non-vacuous, fix store_unavailable witness Fifth-review decisions 9 and 10. Decision 9. The suite-summary judge refuses a lane that executed nothing, but one executed test would satisfy it while the second silently excluded itself -- exactly the failure mode a cross-UID case has. The release script now asserts this lane reported exactly TWO executed tests; one and zero are both red, and a missing second user is a red check rather than a skipped case. Closure also requires the single release run to be on Linux, stated in the closure matrix and recorded on the evidence page beside the result, because a cross-UID witness needs a second unprivileged user and SO_PEERCRED and a macOS-only run would leave Outcome 2 unproved while reporting green. Decision 10, verified in code: Loopex.Store.Local answers ownership_head from state.store at local.ex:130-131 and :219-220 -- from memory -- so a root that has become unreadable on disk still answers and cannot produce store_unavailable. The witness now uses the controllable fault store the suite already has, Loopex.M1RuntimeTestStore, whose fail_reads/2 hook (m1_runtime_helper.exs:57,151-153) makes its reads refuse, with ownership_head at :78. Named in both the ADR and the evidence row, with the reason the obvious injection does not work stated so nobody re-derives it. --- ...tachment-residency-and-replay-technical.md | 5 ++- docs/plans/M5-technical.md | 32 ++++++++++++------- 2 files changed, 25 insertions(+), 12 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index df4be8907..22afa76e7 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -302,7 +302,10 @@ durable record and no Store read by the daemon: reads no Store internals. Each of the five results is a witness: `present` granting, `absent`, - `invalid_id`, `store_unavailable` injected by making the root unreadable, + `invalid_id`, `store_unavailable` injected through the suite's controllable + fault store rather than by making the root unreadable — `Loopex.Store.Local` + answers `ownership_head` from memory, so an unreadable root does not produce + that result — and `unexpected` injected by a stub that answers outside the set. All five assert the same absence afterwards — no attachment, no lease, no activation — and assert that the four refusals name distinct reasons. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 5a52dc5ab..1bfa4152f 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,9 +130,9 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written at the next daemon start when the index is rebuilt; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason it carries, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs on the Linux lane as `mix test --only cross_uid`, where the suite-summary judge makes a zero executed count red rather than a skip. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason it carries, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result — `store_unavailable` injected by making the root unreadable and `unexpected` by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach --observe` refused with `session_dormant` against a session this daemon has not activated and succeeding against one it has; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The three credential-bearing calls in the sender — `ProviderBridge.route_credential/2`, `receive_custody_reply/2` and `write_credential_frame/2` — are excluded from tracing by match specification, as accepted ADR 0030 already requires of a key-bearing call, with a second case asserting those three functions exist with exactly those identities so a rename or an inlining breaks the proof loudly rather than widening what a trace can capture. The proof is an absence: under a real trace session at the `arguments` level no trace entry names any of the three, the tracer receives no raw trace message for them, and no credential bytes and no token appear in any captured entry. A placeholder entry for one of them fails the case as surely as the bytes would. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Two runtimes composed in one VM, each with its own registry and custody, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -172,7 +172,7 @@ merge needs green in hosted CI, M5 selects exactly these, from the commit is the current-pair evidence; `bash scripts/check.sh` runs once under the floor pair, `mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh` with its own `MIX_BUILD_ROOT`; and -`bash scripts/check-release.sh` runs once on the current pair with the +`bash scripts/check-release.sh` runs once on the current pair **on Linux**, which closure requires because the cross-UID witness needs a second unprivileged user and `SO_PEERCRED`, neither of which a Darwin lane supplies; the evidence page records the platform beside the result. It runs with the provider credential and the pinned Node version in `scripts/fixtures/m4/client-toolchain.txt`. @@ -189,14 +189,24 @@ script runs, on the Linux lane only, for `loopex_daemon`: Two cases carry that tag and both must execute: a connection from a foreign uid refused before initialize, and one from the daemon's own uid accepted. -The script already pipes each lane through `scripts/suite-summary.sh` and -fails the check when a lane executed no test — "a run that executed nothing -is not a pass", as its own comment puts it — and that judge governs this lane -too: **a zero executed count is red**, not a skip. That matters more here than -elsewhere, because a cross-UID case is exactly the kind that quietly excludes -itself when the second user is missing, and a silent zero would turn the one -witness the fast check cannot supply into no witness at all. Closure is bound -to that lane's recorded result. + +**The suite judge's rule is not enough here, so the script asserts the exact +count.** `scripts/suite-summary.sh` fails a lane that executed no test — "a +run that executed nothing is not a pass", as the script's own comment puts it +— but one executed test would satisfy that while the second silently excluded +itself, which is exactly the failure mode a cross-UID case has. So the release +script asserts this lane reported **exactly two executed tests**, and anything +else, including one and including zero, is red. A missing second user is a red +check, not a skipped case. + +**And the single release run must be on Linux.** A cross-UID witness needs a +second unprivileged user and the `SO_PEERCRED` mechanism, neither of which the +Darwin lane supplies, so a release check run only on macOS would leave Outcome +2 unproved while reporting green. The closure matrix therefore states the +platform: `bash scripts/check-release.sh` runs once **on Linux**, and the +evidence page records the platform beside the result so a reviewer can see +which machine produced it. Closure is bound to that lane's recorded result and +to its platform. `loopex_daemon` joins the `release_apps` list in the change that adds its first release case, and only that list: every `release_apps` lane already runs From 3b79aede5c6758718ec9d1626354e58df8f6340f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:21:38 -0700 Subject: [PATCH 047/585] plan(M5): sweep the fifth round's material corrections Stale statements corrected: the marker is no longer said to be held "for its process's lifetime" -- the Store takes it and releases it in its own terminate/2, so the daemon owns the Store process and stops it last, and a store loss releases it before the daemon can act. The "next daemon start" retry is replaced everywhere by the live-daemon retry decision 5 fixes, in both plan files and the ADR's evidence line. The eager-activation cost formula was wrong: the local adapter replays the root's ONE log in full at every open, so activating everything at start does not cost a product of session count and history -- it costs that single replay, paid once, plus starting and holding a coordinator per recorded session. A root with 4,096 sessions would start 4,096 coordinators to serve the one a client wanted, which is the real reason lazy recovery wins. Aggregate reclamation now says it repeats until the aggregate is below the ceiling rather than applying each step once: releasing one window may not be enough, and a single pass could leave the daemon over its bound. The daemon's own log is bound to the rules that already exist -- ADR 0029's bounded non-secret discipline and ADR 0030's metadata rule -- with the fatal-class map as the whole vocabulary an exit may use, and no new diagnostic plane. ADR 0034's seven atoms are stated as internal diagnostic classes: the value complete/3 returns keeps the existing Loopex.Model refusal shape, since widening an accepted port's result is a change this decision does not make. --- ...n-attachment-residency-and-replay-technical.md | 15 ++++++++++----- ...0032-daemon-attachment-residency-and-replay.md | 11 +++++++---- ...al-handoff-over-bootstrap-channel-technical.md | 9 +++++++++ docs/plans/M5-technical.md | 12 +++++++++++- docs/plans/M5.md | 13 ++++++++----- 5 files changed, 45 insertions(+), 15 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 22afa76e7..218a518fe 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -533,9 +533,12 @@ delivered contiguously after the snapshot. The daemon adds: it is measured in bytes rather than in each session's own sequence numbers. A sequence-distance metric would not be comparable: sequence numbers are per-session and say nothing about how much memory an attachment is costing. - Ties break by session ID bytes ascending. Only after every window has been - released does the daemon detach the slowest attachment at its last emitted - cursor. Independently of pressure, a window whose session has had zero + Ties break by session ID bytes ascending. Each step is **repeated until the + aggregate is below the ceiling**, not applied once: releasing one window may + not be enough, so zero-attachment windows are released in that order until + either the aggregate fits or none is left. Only when none is left does the + daemon detach the slowest attachment at its last emitted cursor, and that + too repeats until the aggregate fits. Independently of pressure, a window whose session has had zero attachments for the idle interval is dropped. No reclamation stalls a journal transaction and none changes what any client is owed. @@ -600,8 +603,10 @@ recorded-entry bound refusing at start with its stable reason; at that bound a session reached by ID activated, not recorded, and the listing carrying `index_full`; a client that never saw a session ID recovering it through the create command's durable `command_id`; a directory write failing at activation -reported to that client, the session still usable, and the record retried at -the next activation; a +reported to that client, the session still usable, and the record written by +the retry the next time the live daemon holds that ID — right after +activation, on a later command for the session, or when a client reaches it by +ID; a recorded session the current composition cannot serve refused at activation by name while every other session in the root activates; progress coalescing under pressure with counted drops and no journal delay; peer-credential refusal; a diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 6f48d7608..748e70b37 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -156,10 +156,13 @@ session-creating transaction so it is crash-atomic with the commit, were both rejected on 2026-09-20: each is a change to the Store port or to the local adapter's transaction shape, and both are exactly what M5's selection of the unchanged adapter declines to buy. Activating every recorded session at -daemon start was rejected the same day: the local adapter replays a full log -at every open, so startup cost would grow with the product of session count -and history, and a root with one unservable session would fail a start that -need never have read it. The companion records each in full. +daemon start was rejected the same day. The local adapter replays the root's +**one** log in full at every open, so the cost is not a product of session +count and history — it is that single replay, paid once, plus the cost of +starting a coordinator for every recorded session and holding it. That is what +lazy recovery avoids: a root with 4,096 recorded sessions would start 4,096 +coordinators to serve the one a client wanted. And a root with one unservable +session would fail a start that need never have reached it. The companion records each in full. **Evidence its acceptance requires.** Two classes together. The transport and its generation are a protocol claim, so they need vectors and a compatibility diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index b9ef073f6..1fd5ed557 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -275,6 +275,15 @@ host-authored term is exactly where a secret could be smuggled into a reason. All seven atoms carry no content, so they are safe in a message, an exit reason and a bounded diagnostic. +**They are internal diagnostic classes, not a new public result shape.** The +seven live inside the adapter and in what the guardian records; the value +`complete/3` returns to the coordinator keeps the **existing `Loopex.Model` +refusal shape**, unchanged by this decision. A host that pattern-matches on +the adapter's result today matches the same shapes afterwards, and the atom is +what the bounded non-secret diagnostic says happened rather than a second +return contract to learn. Widening the callback's result would be a change to +an accepted port, which this decision explicitly does not make. + **What the sender reports.** `:ok` or `{:error, reason}` from that same closed set, never a bare `:error`. The guardian has to distinguish a custody process that refused from one that never answered — they are different operational diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 1bfa4152f..d20e98c96 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -39,7 +39,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | --- | --- | --- | | `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | -| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which the daemon holds for its process's lifetime | Any daemon fact, lease, index or residency state | +| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon` with its readiness line, signal handling and exit classes, `loopex attach` with its roles, takeover presentation and cursor reconnect, the live `loopex sessions --daemon` form beside the unchanged offline one, and the host-side credential custody and registry it composes | Normative lease or session semantics, and any change to the released offline `loopex sessions` | @@ -716,6 +716,16 @@ the next marker holder removes. | `store_capacity_exceeded` | Fail-stop: the Store terminated on the capacity refusal specifically | | `supervision_fault` | Fail-stop: a lease owner failed, under ADR 0033's daemon-fatal rule | +**The daemon's own log is bounded and redacted by the rules that already +exist.** Everything the daemon writes to `stderr` — refusals, warnings, the +fatal reason — is a bounded non-secret line under ADR 0029's discipline, and +carries no credential, no token, no model content, no tool argument or result, +and no artifact bytes, exactly as ADR 0030's metadata rule already forbids for +a trace or a telemetry span. Nothing here is a new logging plane: the daemon +has no diagnostic surface of its own beyond these lines and the records it +already sends on the wire, and the fatal-class map above is the whole +vocabulary of what an exit may say. + **Reverse cleanup.** Every startup failure *after* the marker is acquired unwinds what it has done, in reverse: an unlinked-and-bound socket is closed and its path unlinked, a created `daemon/` subdirectory it made is removed, diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 3776f2c2e..8b0519e79 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -14,8 +14,8 @@ server speaks, lets exactly one client drive while the others observe, survives the driver's crash with an explicit takeover, replays snapshot and cursor to a reconnecting client contiguously and at least once with no gap, cancels work across processes, and does all of it on the existing local store -adapter, which it holds for its process's lifetime within that adapter's -documented limits. +adapter, whose Store process it owns for its lifetime and stops last, within +that adapter's documented limits. Finish M5 as an operator-usable, source-only `0.2.0` release candidate. From a fresh extraction of the exact closure candidate an operator follows the @@ -161,9 +161,12 @@ writes that sequence out step by step, and its witness asserts a live coordinator and a prompt landing at the end of it, not merely an identity returned. If recording the directory entry fails during activation, that failure is reported to the client, the session is -fully usable anyway, and the record is retried at the next daemon start, when -the index is rebuilt from the directory — not at a next activation, because -activation is one-way and there is no second one within a lifetime. And if +fully usable anyway, and the daemon retries it while it still holds the ID: +right after activation, on each later command for that session, and when any +later client reaches the session by ID or replays its create command. It +cannot be "the next activation", since activation is one-way, nor "the next +daemon start", since a restarted daemon builds its index from the directory +and so has never heard of a session the directory does not hold. And if the index is already at its 4,096-entry ceiling, a session reached by ID is still activated, simply not recorded, with `session.list` carrying `index_full` so an operator is told the listing is incomplete rather than From d44f91c2fba38f321c2870a0304f9ea8af6624bc Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:23:04 -0700 Subject: [PATCH 048/585] plan(M5): add the ownership-and-failure boundary table Task A of the fifth round. Most of what went wrong across five reviews was not missing prose: it was a boundary where two documents each assumed the other side handled a failure, or where the daemon was given a job the code on the other side does not permit. The table is one row per boundary M5 touches -- Store/daemon at runtime and at startup, core/daemon for the existence query, attach, resume and commands, lease owner/connections for failure and for expiry, listener/connections, registry/sender/custody, CLI/socket, and daemon/OS for signals, kill, socket file and marker -- with owner, what fails, who observes it and how, what the client sees, and what is durable. Every observer cell rests on a code line that exists today or on a component this plan names as new. Two rows are called out for their reading, because they are the ones earlier drafts got wrong: the coordinator-death row has no observer entry available, which is what forced residency to be a daemon fact rather than a liveness claim, and the Store/daemon row shows the marker already released before the daemon can act, which is what forced the fail-stop split from the ordered shutdown. --- docs/plans/M5-technical.md | 38 ++++++++++++++++++++++++++++++++++++++ docs/plans/M5.md | 2 ++ 2 files changed, 40 insertions(+) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d20e98c96..afe169060 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -767,6 +767,44 @@ what lets an operator fix the cause and try again without a recovery step. held elsewhere, the socket permission check fails, or the index bound is exceeded, and each of those exits non-zero with its own class. + +### Ownership and Failure at Every Boundary + +Concept: [Scope](M5.md#concept-plan-scope). + +Most of what went wrong in this plan's reviews was not missing prose. It was a +boundary where two documents each assumed the other side handled a failure, or +where the daemon was given a job the code on the other side does not let it +do. This table is the answer to both: one row per boundary M5 touches, and +every cell resting on a code line that exists today or on a component this +plan names as new. It is the thing to check a change against. + +| Boundary | Owner | What fails | Who observes it, and how | What the client sees | Durable / not durable | +| --- | --- | --- | --- | --- | --- | +| **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the daemon owns the Store *process* | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:166`). The daemon observes the death two ways, because `LoopexComposition.start_edge/2` uses `start_link` (`loopex_composition.ex:302-307`): it traps the exit and also monitors the adapter | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | +| **Store ↔ daemon (startup)** | The adapter | Marker held, unverifiable, log too large | `WriterLock.acquire` refuses with `store_writer_active` / `store_writer_unverifiable`; `Log.open` refuses `store_log_too_large` (`log.ex:80-84`) | Nothing — no socket exists yet | **Not durable:** nothing was written. Reverse cleanup leaves no marker | +| **Core ↔ daemon: existence query** | `loopex` answers; the daemon asks | Root unreadable, malformed ID, unrecognised answer | The query's own closed result set — `present`, `absent`, `invalid_id`, `store_unavailable`, `unexpected` (this plan's new core operation) | The matching refusal, four of them distinct; nothing created, nothing attached, no lease | **Not durable:** the query writes nothing, proved by a byte-identical root | +| **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | +| **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | +| **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | +| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The daemon's own supervisor: `one_for_all` up to the listener | `daemon.stopping` with `supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | +| **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | +| **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled. The invocation's failure is | +| **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The daemon's signal handler begins the ordered shutdown | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | +| **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | +| **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | +| **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | `terminate/2` in an orderly stop; `terminate/2` early on store loss; nothing on a kill | Nothing directly; the next daemon's start succeeds, succeeds, or recovers | **Not durable in the journal sense:** the marker is exclusion, not truth | + +Two rows deserve their reading stated, because they are where earlier drafts +went wrong. The **coordinator death** row is the one that forced `residency` +to mean a daemon fact: there is no observer column entry available, so any +design that needed one was unimplementable. The **Store ↔ daemon** row is the +one that forced the fail-stop split: the marker is already released by the +time the daemon can act, so an ordered shutdown ending "stop the Store" had +nothing to stop. + ### Proportional Minimalism Budget diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 8b0519e79..2c2233740 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -378,6 +378,8 @@ Technical depth: [The daemon's operator contracts](M5-technical.md#technical-pla Technical depth: [Daemon lifecycle and orderly shutdown](M5-technical.md#technical-plan-lifecycle). +Technical depth: [Ownership and failure at every boundary](M5-technical.md#technical-plan-boundaries). + Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan-minimalism). From 814fd3582af333427ccde5498c6b18b99d9c7280 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:26:04 -0700 Subject: [PATCH 049/585] plan(M5): fix what my own adversarial pass found Task B. Seven findings, all of the class the fifth review named -- claims that contradict the code they build on, or that two sections state differently. 1. Evidence row 1 still said a tool effect is "terminated through the configured cancellation sequence with a truthful terminal" and that a store loss "runs the same sequence". Both contradict decisions 1 and 2, which I had applied only to the lifecycle prose. The row now asserts the negative that matters -- no cancelled, no outcome_unknown, no abort record -- and carries the fail-stop as a separate witness. 2. The same row still had the directory retry "at the next daemon start", which decision 5 withdrew. 3. loopex run --daemon was specified as create, acquire, prompt, attach. ADR 0033 admits an existing-session mutation only from a connection holding a controller-capable attachment, with exactly one exception -- session.resume on a verified dormant session -- and a prompt is not it. The sequence is now create, acquire, attach, prompt, with the reason stated. The attach --take-over --prompt row says the same. 4. The generation-2 digest statement covered methods and record families but not ERROR CODES, which schema_digest/0 is equally taken over. Generation 2 adds control_held, session_dormant, the four existence-query refusals and the activation and residency refusals; a reason invented at implementation time and not entered in the ordered list would make the served contract differ from the advertised digest. Now a four-row table of what changes. 5. "Bounded" for Runtime.stop was asserted rather than sourced. Supervisor.stop/3 takes an :infinity call timeout by default; the bound is each child's own shutdown value -- 5,000 ms for a coordinator, brutal kill after. Said that way, and noted that the daemon adds no timer. 6. "Stop the Store last" read as a daemon-side instruction. It is what the composition bracket already does: LoopexComposition starts the Store first and the runtime last, start_edge/2 prepends to the owned list, and RuntimeOwner's cleanup reduces over it in order -- runtime first, Store last. Cited, and step 2's explicit Runtime.stop is explained as ordering rather than duplication. 7. The fail-stop path implicitly depended on the bracket's teardown ordering. It must not and now says so: the marker is already gone when the signal arrives, so there is nothing left for an ordered teardown to protect. Also swept a non-goals line still saying core's only M5 change is concurrent attachment, and removed a sentence about store-child failure made redundant by the new fail-stop witness. --- ...tachment-residency-and-replay-technical.md | 29 ++++++--- docs/plans/M5-technical.md | 61 ++++++++++++++----- docs/plans/M5.md | 3 +- 3 files changed, 68 insertions(+), 25 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 218a518fe..937da78bb 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -176,14 +176,27 @@ number to come from an accepted or proposed decision. One non-blocking attempt into a bound that already exists is the same guarantee with nothing new to justify. -**This changes the generation-2 digest, and that is the point of saying it -here.** `Loopex.Protocol.Session.schema_digest/0` is taken over the -generation, the ordered methods, the ordered record families, the ordered -error codes and the limits. `daemon.stopping` is a new **record family**, so -generation 2's digest reflects it; the literal the conformance module pins for -generation 2 is the digest of the contract *including* this record, and a -generation 2 that omitted it would compute a different value and fail there. -Generation 1's digest is untouched, since generation 1 has no such record. +**This changes the generation-2 digest, and so do the error codes.** +`Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the +ordered methods, the ordered record families, the ordered error codes and the +limits — five inputs, and generation 2 changes four of them: + +| Digest input | Generation 2 | +| --- | --- | +| Generation | New string | +| Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | +| Record families | Adds `daemon.stopping` | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `session_dormant`, `index_full` where it is returned as a refusal rather than a field, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | +| Limits | Unchanged from ADR 0023's ceilings | + +Listing the error codes matters because it is the input most easily forgotten: +a refusal reason invented at implementation time and not entered in the +ordered list would make the served contract differ from the digest the server +advertises, which is exactly the drift the digest exists to catch. The +generation-2 literal the conformance module pins is the digest of the contract +*including* all four changes, and a build missing any of them computes a +different value and fails there. Generation 1's digest is untouched, since +generation 1 gains no method, no record family and no error code. ### The session index, and what it may claim diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index afe169060..cf1a5172e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -129,7 +129,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect terminated through the configured cancellation sequence with a truthful terminal, an ambiguous mutation left as `commit_unknown` rather than reported committed and resolved to exactly one outcome when the root is reopened, every client given a final frame naming the reason, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released. A fatal exit on store loss runs the same sequence, tells clients `store_lost` and exits non-zero with that class on `stderr`. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. Store-child failure closes the listener and every connection before exit. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written at the next daemon start when the index is rebuilt; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, every client given one bounded best-effort `daemon.stopping` naming `operator_stop`, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason it carries, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -517,10 +517,14 @@ resumed before anything can be sent to it. The daemon forms of the two released commands are what reach the socket: - **`loopex run --daemon --policy … ""`** — creates a session - and sends its first prompt. It performs the whole sequence: `session.create`, - then `session.acquire_control`, then the prompt under the granted writer - epoch, then attach, then stream. The offline `loopex run` is unchanged and - keeps composing its own runtime; `--daemon` is what redirects it. + and sends its first prompt. Its sequence is `session.create`, + `session.acquire_control`, **`session.attach`**, then the prompt under the + granted writer epoch, then stream. Attach comes *before* the prompt because + ADR 0033 admits an existing-session mutation only from a connection that + holds a controller-capable attachment, and grants exactly one exception — + `session.resume` on a verified dormant session — which a prompt is not. The + offline `loopex run` is unchanged and keeps composing its own runtime; + `--daemon` is what redirects it. - **`loopex resume --daemon `** — reaches an existing session. It performs ADR 0033's sequence exactly: acquire control, then `session.resume` with a **fresh resume command ID** and the granted epoch, @@ -536,7 +540,7 @@ restriction.** Its forms are: | --- | --- | | `--observe` (default when neither role flag is given) | Attaches without acquiring, streams events, sends nothing. Refused by the daemon, not the client, if it ever tries | | `--take-over` | Acquires a released or expired lease, waiting while an in-flight admission settles as ADR 0033's linearization requires; never forces a live holder off. Then attaches and streams | -| `--take-over --prompt ""`, or `--take-over` with the prompt on stdin | The same, plus **one** command under the granted epoch, then streams to a terminal outcome | +| `--take-over --prompt ""`, or `--take-over` with the prompt on stdin | The same — acquire, then attach — plus **one** command under the granted epoch, sent only after the attachment exists because ADR 0033 admits a mutation only from a controller-capable attachment, then streams to a terminal outcome | There is no interactive multi-turn controller in M5. A controller that could accept turn after turn from a terminal would need a full interactive contract @@ -639,10 +643,19 @@ from that instant: has not settled when the grace elapses is ended by stopping the runtime: `Loopex.Runtime.stop/1` is `Supervisor.stop(supervisor, :normal)`, and each session coordinator is a `restart: :temporary` child with `shutdown: 5_000` - that neither traps exits nor defines `terminate/2` — so it receives the - shutdown exit and dies, bounded, without running any terminal code. That is - **crash-equivalent by construction**, and it is the point: the daemon - claims no terminal mutation for work it ended. A mutation whose commit was + that neither traps exits in `init/1` nor defines `terminate/2` — so it + receives the shutdown exit and dies without running any terminal code. That + is **crash-equivalent by construction**, and it is the point: the daemon + claims no terminal mutation for work it ended. + + The bound is the supervision tree's, and the plan says whose rather than + asserting one. `Supervisor.stop/3` takes an `:infinity` call timeout by + default and the daemon adds none; what bounds the step is each child's own + `shutdown` value — 5,000 ms for a coordinator, after which the supervisor + kills it brutally — applied as the tree terminates. So the step is bounded + by values the tree already carries, not by a timer this milestone + introduces, and a coordinator cannot hold the shutdown open past its own + shutdown value. A mutation whose commit was ambiguous stays `commit_unknown` and fenced, and the reconciliation ADR 0006 and ADR 0018 already define settles it at the next activation — exactly as it would after an abrupt death. @@ -670,16 +683,32 @@ from that instant: 5. **Stop the Store, last.** The marker is released by the Store's own `terminate/2` at that moment — see the marker invariant in ADR 0031 — so stopping the Store last is exactly what makes the marker outlive every - session operation that might still have needed it. Only after it returns - does the daemon exit. + session operation that might still have needed it. + + This is the order the composition bracket already performs, which is worth + knowing before anyone writes a teardown of their own. + `LoopexComposition` starts the Store adapter first and the runtime last, + and `start_edge/2` **prepends** each started edge to its owned list, so + that list is runtime-first and Store-last; `RuntimeOwner`'s cleanup reduces + over it in order and therefore stops the runtime first and the Store last. + A daemon that composes through `with_runtime/2` gets this ordering by + returning from the bracket. Step 2 stops the runtime explicitly rather than + leaving it to that cleanup only because the daemon wants the sequence — end + work, *then* tell clients, *then* unlink — and the bracket's own teardown + would do it after the daemon had already closed everything. 6. **Exit `0`.** **Store loss, a fail-stop path.** The daemon composes its runtime through `LoopexComposition`, whose `start_edge/2` starts the adapter with -`start_link`, so the Store is **linked** to the composing process; the daemon -traps exits there and additionally monitors the adapter, so a store that -terminates itself is observed either way rather than taking the daemon down -as an untrapped exit. On that signal, and without the ordered sequence: +`start_link`, so the adapter is **linked** to the composing process. The +daemon arranges to observe its death rather than be killed by it: the process +holding that link traps exits, and the daemon additionally monitors the +adapter, so the signal arrives whichever way the link behaves and a store that +terminates itself cannot take the daemon down as an untrapped exit before the +daemon has told anyone. This path does **not** depend on the composition +bracket's own teardown ordering, and must not: the marker is already gone by +the time the signal arrives, so there is nothing left for an ordered teardown +to protect. On that signal, and without the ordered sequence: 1. Refuse service immediately — no further admission, no further attach, and the listener closed. diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 2c2233740..5000b9e32 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -386,7 +386,8 @@ Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan ### Non-Goals No controller lease, transport, socket or collaboration rule inside core. Its -only M5 change is independent concurrent attachment support. No daemon-grade +only M5 changes are independent concurrent attachment support and one +read-only session-existence query, neither of which is a durable command. No daemon-grade store adapter, journal format version, migration, backup tooling, compaction, retention cutoff or NIF dependency; no daemon-served generation 1; no durable lease record; no exactly-once delivery promise beyond the founding From 102271cf96f796c42b66a5b7ada8cfacbabd97a5 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:43:30 -0700 Subject: [PATCH 050/585] plan(M5): give the daemon its own supervision tree Review findings H1, H2, H3 and M1, each verified before the text changed. H1 holds and is worse than the previous round wrote. LoopexComposition. start_edge/2 runs inside a process RuntimeOwner SPAWNS -- own_started/5 and own_bracketed/6 are spawn_monitor bodies and initialize/1 sets trap_exit there -- so the start_link to the Store adapter links that owner process, not the daemon. The daemon is only the caller of start/1 or with_runtime/2, and %Loopex.Runtime{} is [:supervisor, :token] (runtime.ex:46): no composition function returns the adapter pid. A daemon on the bracket cannot observe the Store's death and has no pid to monitor. My previous "traps exits there and additionally monitors the adapter" was unimplementable. H2 holds. Runtime.stop/1 is Supervisor.stop(sup, :normal) (runtime.ex:115-121) and the runtime supervisor is one of the owner's linked edges, so its exit arrives as {:EXIT, _owned_pid, reason} (runtime_owner.ex:101) and the owner runs cleanup/1 (:166-180) immediately -- stopping the Store and releasing the marker before steps 3 to 5. So apps/loopex_daemon supervises its own children: Store adapter, runtime, lease owner supervisor, listener, in that start order, rest_for_one. The strategy is justified rather than asserted: each child depends on those started before it and none after, so the Store's failure must take the rest while the listener's need not take the Store; one_for_all would be safe but would claim something untrue. The daemon supervisor holds the Store's link, so the adapter's exit reason reaches a process the daemon controls, and reverse-start-order termination stops the Store last BY CONSTRUCTION rather than by a sequence someone must remember. Step 2's Runtime.stop targets a sibling and cannot reach the Store. The Store's spec is restart: :temporary, since rest_for_one would otherwise restart a store whose cause a restart cannot fix. Rejected option recorded: changing LoopexComposition to surface store death and the adapter pid -- a host convenience app the app server uses and the daemon does not need. The two hosts now compose differently on purpose, and the plan says why. H3 holds. Core's shutdown values do not bound the runtime's teardown: owner_group.ex:17 is shutdown: :infinity and its terminate/2 calls Supervisor.stop(workers, :shutdown, :infinity) at :87, and three of the runtime supervisor's children are supervisors defaulting to :infinity (supervisor.ex:73-81). "5,000 ms for a coordinator" is deleted as the bound. Step 2 now runs under the composed cleanup grace -- an existing number -- and on expiry kills the runtime supervisor pid the struct exposes, which is crash-equivalent by definition and so is the property itself rather than a compromise of it. M1: commit 4073538d on this branch edited two accepted product documents, docs/developer/verification.md and verification-technical.md, while M5 still says widening them is M5's work. Both files are restored to their main content; the plan's text is unchanged and the obligation stays M5's. The revert is exactly two rows -- the selection-table row and its companion row plus the sentence naming the boundary -- and the docs gate count is still 26. --- docs/developer/verification-technical.md | 7 +- docs/developer/verification.md | 2 +- docs/plans/M5-technical.md | 145 +++++++++++++++++------ 3 files changed, 110 insertions(+), 44 deletions(-) diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index 1f2d4fa2f..53edbf2fb 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -76,14 +76,13 @@ Concept: [Selection](verification.md#concept-verification-selection). | Observability | `apps/loopex/test/trace_session_test.exs`, `telemetry_boundary_test.exs`, `apps/loopex_telemetry/test/` | | Dependency direction | `mix loopex.deps_budget` and `apps/loopex/test/deps_budget_test.exs` | | Documentation chain | `mix loopex.status`, `mix loopex.docs_check` | -| An operating-system process boundary | The local executor's: `apps/loopex_executor_local/test/coding_tools_test.exs` launch-guard, cleanup and frame cases. The provider adapter's child: `apps/loopex_llm_reqllm/test/provider_launcher_test.exs`, `provider_startup_boundaries_test.exs`, `provider_deadline_test.exs`, `provider_retainer_boundaries_test.exs` and `credential_plane_test.exs`, which own the spawn, the control-pipe bootstrap handshake, the deadline and the cleanup grace. Either is reproduced under contention by the procedure below | +| The executor's OS boundary | `apps/loopex_executor_local/test/coding_tools_test.exs` launch-guard, cleanup and frame cases; reproduced under contention by the procedure below | **Reproducing an executor race under contention.** The launch guard, its wrapper subshell and the tool share one pipe, and the hosted runner's four loaded cores exposed a frame split that a twenty-core machine never showed. -The procedure that reproduced it on serenity, and that a change to any -operating-system process boundary is read against — the executor's, and the -provider child's, which has the same spawn, control-pipe and cleanup shape: pin the test VM and eight busy-loop +The procedure that reproduced it on serenity, and that a change to the +executor's OS boundary is read against: pin the test VM and eight busy-loop hogs to four cores with `taskset -c 0-3`, add one process writing 8 MiB with `dd oflag=dsync` in a loop, and run the case in a loop of thirty, counting any run past its 60 s run deadline as a hang. The frame split reproduced 2 in 34 diff --git a/docs/developer/verification.md b/docs/developer/verification.md index 3cd48b485..d06be0bb5 100644 --- a/docs/developer/verification.md +++ b/docs/developer/verification.md @@ -63,7 +63,7 @@ Technical depth: [The selection table](verification-technical.md#technical-verif | The wire protocol, its schema or vectors | The Node consumer workflows (`--only node_client`, part of the release check), and the compatibility surfaces page updated in the same change | | The CLI or operator-facing commands | The operator page that describes the behavior updated in the same change; a changed operator command also selects its workflow in the release check | | Provider or credential handling | `bash scripts/check-release.sh`, the real-provider cases | -| An operating-system process boundary (launch, control pipe, signals, cleanup) — the local executor's, or the provider adapter's child | `bash scripts/fixtures/pinned-load.sh` over the touched cases on a Linux host: thirty runs under four pinned cores and load, no failure and no hang | +| The executor's OS boundary (launch, signals, cleanup) | `bash scripts/fixtures/pinned-load.sh` over the touched cases on a Linux host: thirty runs under four pinned cores and load, no failure and no hang | | The toolchain floor or `.tool-versions` | The fast check under the floor pair once | | Documentation only | `bash scripts/check.sh --docs`, which `check.sh --select` chooses on its own for a prose-only diff | | Unknown | The release check, and the review names the boundaries it found | diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index cf1a5172e..dad084b22 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -621,15 +621,76 @@ non-zero with that step's reason class and touches nothing after it — in particular, a daemon that does not hold the marker never reads, unlinks or binds the socket path. +**The daemon composes its own supervision tree, and does not use +`LoopexComposition`'s bracket.** That is a decision this section has to make +before it can describe any shutdown, because the bracket makes the shutdown +this plan wants impossible. Two facts in the code say so: + +- `LoopexComposition.start_edge/2` runs inside a process `RuntimeOwner` + **spawns** — `own_started/5` and `own_bracketed/6` are `spawn_monitor` bodies + and `initialize/1` sets `trap_exit` there — so the `start_link` to the Store + adapter links that *owner* process, not the daemon. The daemon is only the + caller of `start/1` or `with_runtime/2`, and `%Loopex.Runtime{}` is + `[:supervisor, :token]`: no composition function hands back the adapter pid. + **A daemon using the bracket has no way to observe the Store's death and no + pid to monitor.** +- Worse, it inverts the ordering. `Runtime.stop/1` is + `Supervisor.stop(supervisor, :normal)`, and the runtime supervisor is one of + the owner's linked edges, so its exit arrives at the owner as + `{:EXIT, _owned_pid, reason}` and the owner runs `cleanup/1` **immediately** + — stopping every owned edge including the Store, and releasing the marker — + before the daemon has told a single client, unlinked the socket, or reached + anything this section calls step 3. + +So `apps/loopex_daemon` supervises its own children directly, in start order: + +| # | Child | Started how | +| --- | --- | --- | +| 1 | The Store adapter | `Loopex.Store.Local.start_link/1` with the root and `recover_stale_writer: true` — the same call `LoopexComposition` makes through `start_edge/2` | +| 2 | The runtime | `Loopex.Runtime.start_link/1` with the store, model, executor, policy and tool configuration the daemon composed | +| 3 | The lease owner supervisor | The daemon's own, under ADR 0033 | +| 4 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | + +The strategy is **`rest_for_one`**. It is the strategy that matches the +dependency direction already present: each child depends on the ones started +before it and on none started after, so the Store failing must take the +runtime, the lease owner and the listener with it, while the listener failing +need not take the Store. `one_for_all` would also be safe but says less — it +would claim the listener's failure must destroy the Store, which is not true +and would make the tree harder to reason about later. + +This buys exactly the two properties the bracket could not give: + +- **The daemon supervisor holds the Store's link**, so the adapter's exit + reason — the `{:stop, reason, …}` `Loopex.Store.Local` answers an append + error with — arrives at a process the daemon controls, carrying + `store_capacity_exceeded` or whatever the store's own reason was. +- **Reverse-start-order termination stops the Store last by construction.** A + supervisor terminates children in the reverse of their start order, so + listener, lease owner, runtime, Store — which is the ordered shutdown below, + obtained from the supervision strategy rather than from a sequence someone + has to remember to write. And step 2's explicit `Runtime.stop/1` targets + child 2, a *sibling*, so it cannot reach the Store. + +The rejected option is recorded: changing `LoopexComposition` to surface store +death and return the adapter pid. It is a host convenience application that +the app server uses and the daemon does not need — the daemon is a different +kind of host, one that must outlive its clients and own its own shutdown +ordering, and widening a shared helper to serve it would put daemon concerns +into an application whose other caller has none. **The two hosts therefore +compose differently, deliberately:** `LoopexAppServer.Host` keeps using +`with_runtime/2`, whose bracket is exactly right for a process that lives and +dies with one client's stdin, and the daemon supervises its own tree because +it does not. + There are **two** ways a daemon ends, and conflating them was a defect. A -daemon-initiated shutdown is the ordered sequence below and stops the Store -last. A **store loss is a fail-stop**, and it cannot be the ordered sequence, -for a reason that is in the code rather than in taste: `Loopex.Store.Local` -answers an append error with `{:stop, reason, commit_unknown, state}`, so it -terminates *itself*, and its `terminate/2` releases the writer marker on the -way out. By the time the daemon observes anything, the store is gone and the -marker is already released. A sequence that ends "then stop the Store" cannot -run when the Store is what died. +daemon-initiated shutdown is the ordered sequence below. A **store loss is a +fail-stop**, and it cannot be that sequence, for a reason in the code rather +than in taste: `Loopex.Store.Local` answers an append error with +`{:stop, reason, commit_unknown, state}`, so it terminates *itself*, and its +`terminate/2` releases the writer marker on the way out. By the time anything +observes it, the store is gone and the marker is already released. A sequence +that ends "then stop the Store" cannot run when the Store is what died. **Daemon-initiated shutdown, in order.** `SIGTERM` or `SIGINT` starts it, and from that instant: @@ -648,14 +709,25 @@ from that instant: is **crash-equivalent by construction**, and it is the point: the daemon claims no terminal mutation for work it ended. - The bound is the supervision tree's, and the plan says whose rather than - asserting one. `Supervisor.stop/3` takes an `:infinity` call timeout by - default and the daemon adds none; what bounds the step is each child's own - `shutdown` value — 5,000 ms for a coordinator, after which the supervisor - kills it brutally — applied as the tree terminates. So the step is bounded - by values the tree already carries, not by a timer this milestone - introduces, and a coordinator cannot hold the shutdown open past its own - shutdown value. A mutation whose commit was + **The daemon does not rely on the runtime's own teardown being bounded, + because it is not.** `Supervisor.stop/3` takes an `:infinity` call timeout + by default, and the runtime tree's own values do not close that: core + declares `shutdown: 5_000` for a session coordinator but `shutdown: + :infinity` for an owner group — whose `terminate/2` itself calls + `Supervisor.stop(workers, :shutdown, :infinity)` — and three of the runtime + supervisor's children are supervisors, which default to `:infinity`. The + runtime's teardown is bounded only transitively, by whatever leaf workers + happen to carry, and "5,000 ms for a coordinator" is not the bound of + anything. + + So the daemon supplies its own. Step 2 calls `Runtime.stop/1` under the + **composed cleanup grace** — the same value the session was composed with, + so no number is introduced — and if it has not returned when that elapses, + the daemon kills the runtime supervisor outright: + `Process.exit(runtime.supervisor, :kill)`, the pid `%Loopex.Runtime{}` + exposes. A brutal kill is crash-equivalent *by definition*, which is + precisely what this step claims to be, so the fallback is not a compromise + of the property — it is the property, reached directly. A mutation whose commit was ambiguous stays `commit_unknown` and fenced, and the reconciliation ADR 0006 and ADR 0018 already define settles it at the next activation — exactly as it would after an abrupt death. @@ -685,30 +757,21 @@ from that instant: stopping the Store last is exactly what makes the marker outlive every session operation that might still have needed it. - This is the order the composition bracket already performs, which is worth - knowing before anyone writes a teardown of their own. - `LoopexComposition` starts the Store adapter first and the runtime last, - and `start_edge/2` **prepends** each started edge to its owned list, so - that list is runtime-first and Store-last; `RuntimeOwner`'s cleanup reduces - over it in order and therefore stops the runtime first and the Store last. - A daemon that composes through `with_runtime/2` gets this ordering by - returning from the bracket. Step 2 stops the runtime explicitly rather than - leaving it to that cleanup only because the daemon wants the sequence — end - work, *then* tell clients, *then* unlink — and the bracket's own teardown - would do it after the daemon had already closed everything. + This is not a step someone has to remember to write: the daemon supervisor + starts the Store first, so reverse-start-order termination stops it last. + Stopping the daemon supervisor *is* steps 3 to 5 in order — listener, lease + owner, runtime, Store — and the marker comes back when the last of those + terminates. 6. **Exit `0`.** -**Store loss, a fail-stop path.** The daemon composes its runtime through -`LoopexComposition`, whose `start_edge/2` starts the adapter with -`start_link`, so the adapter is **linked** to the composing process. The -daemon arranges to observe its death rather than be killed by it: the process -holding that link traps exits, and the daemon additionally monitors the -adapter, so the signal arrives whichever way the link behaves and a store that -terminates itself cannot take the daemon down as an untrapped exit before the -daemon has told anyone. This path does **not** depend on the composition -bracket's own teardown ordering, and must not: the marker is already gone by -the time the signal arrives, so there is nothing left for an ordered teardown -to protect. On that signal, and without the ordered sequence: +**Store loss, a fail-stop path.** The daemon supervisor is the Store adapter's +parent, so the adapter's termination is reported to it with the adapter's own +exit reason — that is the whole observation mechanism, and it needs no link +the daemon does not already hold and no monitor it has to remember to set. +Under `rest_for_one` the Store is child 1, so its failure takes the runtime, +the lease owner and the listener with it, which is the refusal-of-service this +path wants. The daemon reads the reason to classify the exit and then, without +the ordered sequence: 1. Refuse service immediately — no further admission, no further attach, and the listener closed. @@ -719,7 +782,11 @@ to protect. On that signal, and without the ordered sequence: 4. Exit non-zero with that class on `stderr`. **There is no "stop the Store" step**, because the Store already stopped and the marker is already released; the next daemon finds no marker to recover rather than a stale - one. + one. The daemon does not restart the Store either: `rest_for_one` would + ordinarily restart child 1, so the Store's child specification is + `restart: :temporary` in this tree — a store that terminated on an append + error has a durable cause a restart cannot fix, and restarting it would + reacquire the marker only to fail again. Nothing durable is at risk in that ordering: whatever was ambiguous is `commit_unknown` in the journal and is reconciled at the next activation, and From 1002e1d743956b8313e1e0dd425c536a00191661 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:45:35 -0700 Subject: [PATCH 051/585] adr(0034): bind the token at composition, trace against what exists Review findings H4, H5 and H6. H4 holds: module.complete(request, options, progress) with options from state.model.options fixed at composition, and request the closed canonical projection -- there is no per-call seam a token could arrive through. The token is now bound at COMPOSITION, per runtime, in model options beside the registry handle, the same class as the executor reference: precedent, and "per-invocation" everywhere qualifies the RESOLUTION: the sender routes the token through the handle on every call and the bytes exist only in that sender for that one write. The obvious objection is answered directly rather than waved off: a per-runtime token is not the process-wide slot one level down, because the slot was one global location holding BYTES shared by every runtime, while two runtimes here carry different tokens routed through different handles to different custody processes, and options hold no bytes at any time. Confirmed and cited: the model span is built from a fixed identity map of session_id, run_id, attempt, model and provider, so nothing journals or spans model options. H5: the withdrawn live-coordinator definition survived as normative text in both 0032 files. Both now carry the daemon-lifetime fact, and a sweep finds no other residue. H6 holds, and the honest answer needed reading Loopex.Trace rather than ADR 0030. trace.ex:336 installs {module, :_, :_} per module -- no function or arity selectivity -- and excluded?/3 at :411 excludes only by pid, by role, inside core. There is no adapter-side exclusion API, so "excluded by match specification" describes nothing that exists. I did NOT declare a third core change, because none is needed. modules/1 expands a namespace through :application.get_key(application, :modules), and the code's own comment says why it is not a name prefix -- so Loopex.LLM.ReqLLM.ProviderBridge, in loopex_llm_reqllm, is in NO namespace wildcard and is untraced under every default configuration. Where a host names the module explicitly, the implemented redaction pass protects the bytes: Entry.render/2 calls redact/3, which placeholders a credential-keyed value and any binary longer than the identity bound -- a credential is 1..65,536 bytes, so it is redacted by size even as a bare positional argument. The three named functions stay with a precise role: the only functions that touch credential bytes, all in the sender. The proof is two tiers plus an existence case. ADR 0030's prose-implementation drift is flagged in M5's progress entry for the maintainer to disposition, and ADR 0030 is not edited. --- ...tachment-residency-and-replay-technical.md | 8 +- ...-daemon-attachment-residency-and-replay.md | 7 +- ...andoff-over-bootstrap-channel-technical.md | 171 ++++++++++++------ ...edential-handoff-over-bootstrap-channel.md | 27 ++- docs/plans/M5-technical.md | 4 +- docs/plans/M5.md | 25 ++- 6 files changed, 164 insertions(+), 78 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 937da78bb..9decdcf33 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -424,10 +424,10 @@ byte position. ### Session residency: active, dormant, and their bounds -A session is **active** when the daemon holds a live coordinator for it and -**dormant** when the index records it and the daemon has never activated it in -this process's lifetime. Nothing durable distinguishes the two; dormancy is a -daemon fact. +A session is **active** when this daemon activated it in this lifetime and +**dormant** when the index records it and this daemon has not. Nothing durable +distinguishes the two, and neither is a claim about a live coordinator: both +are daemon facts, recorded when the daemon acted. A dormant session costs less than an active one, but not nothing, and the plan should not pretend otherwise. It holds one index row against the diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 748e70b37..cd797f336 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -100,9 +100,10 @@ at the residency limit and reconnect at their retained cursor with no missing durable event. Transient progress is coalesced or dropped first and never delays a journal transaction. -A session is *active* when the daemon holds a live coordinator for it and -*dormant* when the root records it and the daemon has not activated it in this -process's lifetime. Recovery is lazy: a restarted daemon activates nothing, +A session is *active* when **this daemon activated it in this lifetime** and +*dormant* when the root records it and this daemon has not. Both are daemon +facts, true by construction; neither is a claim about a live coordinator, +which the daemon has no way to know. Recovery is lazy: a restarted daemon activates nothing, reads its index, and activates a session when a client reaches for it. Activation is one-way: dormancy applies to attachments, resident windows and output buffers, never to a coordinator, because a session with no attachment diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 1fd5ed557..7760f425a 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -54,15 +54,54 @@ the step-3 frame. ### The token, the routing registry, and the custody process -The per-invocation option is `:credential_token`, one member of the -configuration map the host already supplies to `complete/3`. Its value is an -**opaque token**: a binary of at most 256 bytes from ADR 0023's identifier +**Where the token is bound, and what "per-invocation" qualifies.** The token +is bound at **composition**, per runtime, and what happens per invocation is +its **resolution**. That distinction is the whole of this section, and getting +it wrong would have made the decision unimplementable. + +The seam admits nothing else. `complete/3` is called as +`module.complete(request, options, progress)`, with `options` taken from +`state.model.options` — the model configuration the runtime validated at +composition as `%{module:, model:, options:}` — and `request` is the closed +canonical projection a turn is staged into. There is no third place a caller +could put a value, and no per-call channel between the host and the adapter. +So a token "supplied with each call" has nowhere to arrive from. + +The token therefore sits in `options`, beside the registry handle, and is the +same class as the executor `reference:` the runtime already takes and +`LoopexComposition` already fills with a live process reference. Its value is +an **opaque token**: a binary of at most 256 bytes from ADR 0023's identifier alphabet, carrying no structure the adapter interprets and no authority of its own. It is not the credential, it does not name a module, and it cannot be -resolved by anyone who is not already holding the host's registry. Any other -shape, including a bare binary that could plausibly be the bytes themselves — -anything outside the alphabet or over the bound — is refused as an invalid -option before any child is spawned. +resolved by anyone not already holding the host's registry. Any other shape — +outside the alphabet, over the bound, or a bare binary that could plausibly be +bytes — is refused as an invalid option before any child is spawned. + +**Every later use of "per-invocation" in this pair qualifies the resolution.** +On each call the sender routes the token through the handle, receives the +custody process's reply, writes the frame and dies; the bytes exist in the +parent only in that process, only for that write. Two invocations resolve +independently and concurrently, and a rotation between them is visible to the +second. + +**Why a per-runtime token is not the process-wide slot one level down**, which +is the obvious objection and deserves a direct answer rather than a +reassurance. The slot this decision removes was the VM's environment: one +global location, shared by every runtime in the VM, holding the **bytes**, and +read inside each call so that whichever invocation wrote last determined what +every concurrent invocation sent. A token in `options` is none of those. It is +per runtime, so two runtimes in one VM carry **different tokens routed through +different handles to different custody processes** — the isolation proof this +pair requires. It is not global, because nothing looks it up by name. And it +holds **no bytes at any time**: it is an identifier whose resolution is a call +to a process the host owns. The property that made the environment variable +wrong — concurrent invocations in one VM unable to carry distinct credentials +— is exactly the property this arrangement restores. + +Nothing carries `options` into a durable or observable plane, which is worth +confirming rather than assuming: the model span is built from a fixed identity +map of `session_id`, `run_id`, `attempt`, `model` and `provider`, and no +journal record, public event or snapshot contains the model configuration. The token replaces the `{resolver_module, reference_term}` pair an earlier draft used. The maintainer decided that on 2026-09-20. A pair that named a @@ -177,49 +216,64 @@ boundary, not an absolute: already protects that process — the sender installs its own group-leader sink so no IO request can carry anything out of it, it is unregistered, and it reports only an atom or a `{:error, atom}` pair to the guardian. -- **The credential-bearing calls are excluded from tracing by match - specification, and are named exactly.** Accepted ADR 0030 already fixes the - mechanism — "the key-bearing call is excluded by match specification" — so - this pair does not invent one, it names which calls that covers. They are - three, all in the sender: - - A match specification needs a target, so the three are **named private - functions that must exist**, and their identities are part of this contract - rather than an implementation detail: - - | Excluded function | Why | +- **What actually keeps credential bytes out of a trace, verified against + `Loopex.Trace` rather than against prose.** ADR 0030's companion says "the + key-bearing call is excluded by match specification". No such mechanism + exists in the implementation, and this pair says so rather than promising + it: `Loopex.Trace` installs one pattern per **module**, + `:trace.function(session, {module, :_, :_}, match_spec(level), [:local])`, + with no function or arity selectivity, and its only exclusion is by **pid**, + decided inside core by role — the tracer itself and, on the diagnostics + sink, the dispatcher. There is no adapter-side API to exclude a pid and no + way to exclude one function of a traced module. **That prose-implementation + drift is a finding for the maintainer about an accepted ADR; M5 does not + edit ADR 0030 and its progress entry flags it.** + + What does hold is a two-tier property, and both tiers are real: + + 1. **The adapter is not in the default traced set.** A session's modules come + from `modules/1`, which expands the `:loopex` and `:loopex_protocol` + namespaces through `:application.get_key(application, :modules)` — the + application's own module list, and the code says why it is not a name + prefix: "reading the application's module list rather than matching a + name prefix keeps a module that merely starts with `Loopex` in some other + application out of the session." `Loopex.LLM.ReqLLM.ProviderBridge` lives + in `loopex_llm_reqllm`, so **no namespace wildcard reaches it**. Under + every default configuration the credential-bearing work is untraced, + which is the strong property and the one M5 proves first. + 2. **If a host explicitly names the adapter module**, its functions become + traceable — the sender inherits the trace flag, since `process_flags/2` + sets `:set_on_spawn` on every non-root traced process — and what protects + the bytes then is the redaction pass, which *is* implemented: + `Entry.render/2` calls `redact/3`, which replaces a credential-keyed + value with a `credential` placeholder and **any binary longer than the + identity bound with a `bytes` placeholder**. A credential is 1 to 65,536 + bytes, so it is redacted by size even as a bare positional argument. + + **The three functions stay, and their role is now precise.** They are not + match-specification targets, because those do not exist; they are **the only + functions that touch credential bytes, all executed in the sender process**: + + | Function | What it touches | | --- | --- | - | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | Its arguments carry the registry handle and the token, and the token is the credential reference | - | `Loopex.LLM.ReqLLM.ProviderBridge.receive_custody_reply/2` | Its argument is the resolved credential | - | `Loopex.LLM.ReqLLM.ProviderBridge.write_credential_frame/2` | Its argument is the resolved credential | - - The names are the contract; the arities are as written here. Inlining any of - the three into its caller, or renaming one, removes the match - specification's target and silently widens what a trace session can capture - — so a test asserts the three exist with exactly these identities, and a - rename breaks the proof loudly instead of quietly. - - Exclusion by match specification means the trace session never matches - those functions, so the VM emits **no raw trace message** for them and the - tracer never sees one. That is stronger than redaction and it is the - difference an earlier draft blurred: it said in one breath that the call was - excluded from tracing and in the next that M5 would prove placeholders - appear for it. Both cannot be true — a placeholder is a trace entry, and an - excluded call produces none — and the placeholder expectation is withdrawn - wherever it appeared, here and in the plan's evidence row. Redaction remains - the safety net for everything that *is* traced; it is not the mechanism for - these three. - - **The proof is an absence, and is stated as one.** Under a real trace - session at the `arguments` level over a real invocation, the case asserts - that no trace entry names any of the three functions, that the tracer - received no raw trace message for them, and that no credential bytes and no - token appear anywhere in the captured entries. An entry bearing a - placeholder for one of them fails the case exactly as an entry bearing the - bytes would, because it would prove the match specification did not exclude - what it was supposed to. A second, smaller case asserts the three functions - exist with the identities above, so the first case cannot pass vacuously - against a build where they no longer do. + | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | The registry handle and the token | + | `Loopex.LLM.ReqLLM.ProviderBridge.receive_custody_reply/2` | The resolved credential | + | `Loopex.LLM.ReqLLM.ProviderBridge.write_credential_frame/2` | The resolved credential | + + Naming them is what makes the witness precise and the redaction obligation + checkable: any credential byte in the parent passes through one of these + three and nowhere else. The names and arities are the contract, and a test + asserts they exist with these identities so an inlining or a rename breaks + the proof loudly rather than quietly moving bytes into an unnamed function. + + **The proof is two cases, matching the two tiers.** Under the **default** + configuration, a real trace session at the `arguments` level over a real + invocation produces no entry naming any of the three, no raw trace message + for them, and no credential bytes or token anywhere in the captured entries. + Under a configuration that **explicitly names** `ProviderBridge`, entries for + the three may exist and every one of them is asserted to carry placeholders + and no credential bytes and no token. Proving only the first would leave the + case a host can actually create unproved. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or @@ -481,14 +535,17 @@ Three proofs are new: exit reason and no crash report carries the resolved value. The two-resolutions-at-once case is a **success** case, not a refusal: both invocations complete with their own credentials. -- **The credential-bearing calls are not traced at all.** Under a trace - session at the `arguments` level over a real invocation, no trace entry - names the registry route call, the custody reply handling or the credential - frame write; the tracer received no raw trace message for any of them; and - no credential bytes and no token appear anywhere in the captured entries. A - placeholder entry for one of the three fails the case as surely as the bytes - would, because it would prove the match specification did not exclude what - it was supposed to. +- **Tracing, in two cases matching the two tiers above.** Under the + **default** trace configuration, a session at the `arguments` level over a + real invocation produces no entry naming `route_credential/2`, + `receive_custody_reply/2` or `write_credential_frame/2`, no raw trace + message for them, and no credential bytes or token anywhere — because the + adapter is in no namespace wildcard. Under a configuration that + **explicitly names** `Loopex.LLM.ReqLLM.ProviderBridge`, entries for those + three may exist, and every one is asserted to carry placeholders and no + credential bytes and no token, which is what the redaction pass promises. A + third case asserts the three functions exist with their exact identities, so + neither of the first two can pass vacuously. - **Host custody, proved at each host rather than in the adapter.** The adapter's test tree cannot prove a claim about the CLI's or the daemon's composition, and an earlier draft filed all three there. Each case lives diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 479ef4cec..ee8eb734e 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -40,9 +40,14 @@ test change shortens the check while the slot is shared. **Decide that the credential is a per-invocation input, named by an opaque token and resolved only inside the process that writes it to the child's -private channel.** The host supplies the adapter, with each call, a -*credential token*: an opaque identifier that carries no credential, no -routing and no authority of its own. Behind it the host owns two things the +private channel.** The host gives the adapter a *credential token* where it +composes the runtime: an opaque identifier that carries no credential, no +routing and no authority of its own. **"Per-invocation" qualifies the +resolution, not the token's arrival** — the token is bound once, per runtime, +and resolved afresh on every call. There is nowhere else it could arrive: +`complete/3` receives a request and the composition-time options and nothing +per-call from the host, so a token "supplied with each call" would have no +seam to arrive through. Behind it the host owns two things the adapter does not: a **routing registry** that maps a token to a custody process and holds routing only — never bytes, never anything a secret could be derived from — and the **custody process** that holds the bytes. The adapter @@ -84,12 +89,16 @@ transfer — bounded, unlogged, never forwarded, never retained after the frame is written — and it is the same class of act as writing the credential frame, protected the same way ADR 0019 already protects that sender. The registry lookup before it carries no credential, so routing adds no second place a -secret can be seen, and the three credential-bearing calls are **excluded by -match specification**, the mechanism accepted ADR 0030 already fixes for a -key-bearing call. Exclusion, not redaction: an excluded call produces no trace -entry at all, where a redacted one would produce an entry with a placeholder. -The companion names the three functions exactly, because a match specification -needs a target, and M5 proves the absence. +secret can be seen. What keeps those bytes out of a trace is stated against +the implementation rather than against ADR 0030's prose, which claims a +match-specification exclusion the tracer does not have: the adapter is in no +default trace namespace, so the credential work is untraced under every +default configuration, and a host that explicitly names the adapter module +gets entries whose credential values the implemented redaction pass replaces +with placeholders. The companion names the three functions that touch +credential bytes — they are the whole of the parent-side surface — and M5 +proves both tiers. The drift between ADR 0030's prose and its implementation +is flagged for the maintainer, not patched here. **Everywhere else the boundary is where the adapter's claims stop.** Inside it — the token, the sender, the frame, the child — the adapter proves what it diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index dad084b22..40878f3e1 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -20,7 +20,7 @@ decision named only in prose declares nothing. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or either core change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as a per-invocation input named by an opaque token, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; custody and registry ownership, rotation, the guardian-enforced deadline, `:unavailable` on lost custody or registry with no reconstruction, and every failure outcome; no credential environment read anywhere in the adapter's library tree, with `provider_bridge` reading none at all and the launcher's ADR 0019 scrubbing enumeration kept exactly where it is, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as an opaque token bound at composition beside the registry handle and **resolved per invocation**, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; custody and registry ownership, rotation, the guardian-enforced deadline, `:unavailable` on lost custody or registry with no reconstruction, and every failure outcome; no credential environment read anywhere in the adapter's library tree, with `provider_bridge` reading none at all and the launcher's ADR 0019 scrubbing enumeration kept exactly where it is, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | ADR 0031 decides one thing, the `0.2.0` local-adapter selection and its documented limits. It prescribes no successor engine, experiment or migration; @@ -134,7 +134,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach --observe` refused with `session_dormant` against a session this daemon has not activated and succeeding against one it has; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. The three credential-bearing calls in the sender — `ProviderBridge.route_credential/2`, `receive_custody_reply/2` and `write_credential_frame/2` — are excluded from tracing by match specification, as accepted ADR 0030 already requires of a key-bearing call, with a second case asserting those three functions exist with exactly those identities so a rename or an inlining breaks the proof loudly rather than widening what a trace can capture. The proof is an absence: under a real trace session at the `arguments` level no trace entry names any of the three, the tracer receives no raw trace message for them, and no credential bytes and no token appear in any captured entry. A placeholder entry for one of them fails the case as surely as the bytes would. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Two runtimes composed in one VM, each with its own registry and custody, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in two tiers, against `Loopex.Trace` as implemented rather than against ADR 0030's prose: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** the adapter module, entries for the three may exist and each is asserted to carry placeholders and no credential bytes and no token, which is what the implemented redaction pass gives. A third case asserts the three functions exist with exactly those identities, so neither tier can pass vacuously and an inlining or rename breaks the proof loudly. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Two runtimes composed in one VM, each with its own registry and custody, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 5000b9e32..6acfc180e 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -243,8 +243,14 @@ than failing a startup that never reads it. The credential handoff to a provider child moves from the process-wide environment variable the adapter reads inside each call to the per-invocation private channel the launcher already opens for the nonce and the build -manifest. The host passes an opaque credential token with each call and owns -both the registry that routes it and the custody process the bytes live in; the reference hosts — the CLI, the app-server +manifest. The host binds an opaque credential token where it composes the +runtime — `complete/3` takes a request and composition-time options and +nothing per-call, so that is the only seam there is — and what happens per +invocation is the **resolution**: the sender routes the token through a +host-owned registry to a host-owned custody process, and the bytes exist in +the parent only in that sender, only for that one write. Two runtimes in one +VM carry different tokens and different handles, so this is not the +process-wide slot one level down; the reference hosts — the CLI, the app-server host and the daemon — read the operator's variable once where they compose and delete it there, so the claim about the parent VM's environment is stated from the completion of composition onward rather than for all time. The claim is @@ -435,7 +441,7 @@ implementation that depends on it, not before unrelated work. | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence and the operator root-retirement procedure documented; a daemon-grade adapter and any migration are left open for a separate decision and prescribed nowhere | 1, 5 | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is a per-invocation input named by an opaque token, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is named by an opaque token bound at composition and **resolved per invocation**, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | Three accepted decisions remain load-bearing, are not reopened, and are left **Accepted and unchanged** by everything M5 does: M4's ADR 0023 fixes the @@ -732,6 +738,19 @@ remains Proposed and wholly deferred; decision 4 neither accepts nor partially implements it. ADRs 0019 and 0030 remain Accepted and unchanged, and nothing in this pair asks for an amendment to either. +**One drift flagged, not patched.** Accepted +[ADR 0030](../adr/0030-observability-tracing-and-telemetry-technical.md#technical-depth) +says "the key-bearing call is excluded by match specification". `Loopex.Trace` +has no such mechanism: it installs one pattern per module, `{module, :_, :_}`, +with no function or arity selectivity, and its only exclusion is by pid, +decided inside core by role. The sentence describes something the +implementation does not do. M5 does **not** edit ADR 0030 — an accepted ADR +changes through its own amendment path — and does not rely on the claim: ADR +0034 states the two properties that do hold, that the adapter is in no default +trace namespace and that the implemented redaction pass replaces credential +values with placeholders where a host names the module explicitly. The drift +is recorded here for the maintainer to disposition. + ## Governance Records | Decision | Authority | Authority evidence | Bound bytes | From 0e325b33d06269db1bfc7fdf30543115d28b8eac Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:48:05 -0700 Subject: [PATCH 052/585] plan(M5): apply the review's medium and low findings M2: supervision_fault is expressed on the wire as fatal:supervision_fault, so it lies inside ADR 0032's reason set; daemon.stopping vectors are bound to the reasons a client can receive, with startup-phase classes explicitly carrying none because no socket exists when they occur. M3: index_full is a listing field everywhere else, so it leaves the generation-2 error-code list and the digest-input statement. M4: Loopex.Protocol.Session becomes LoopexProtocol.Session (session.ex:1) in both places. M5: apps/loopex_daemon/test/test_helper.exs ends ExUnit.start(exclude: [:cross_uid]) on the app-server precedent, which excludes :node_client and :real_provider for the same reason, so the fast check never runs the two. M6: verified that nothing makes a Darwin release run red -- check-release.sh has uname only in its banner and pipes each suite summary to /dev/null, discarding the line that would carry a count. The script now reads that line and branches on platform for this lane: Linux runs it and asserts exactly two executed; any other platform prints cross_uid: not run () and the final line becomes PASS (closure-incomplete: cross_uid not run). Closure requires the evidence page to cite a Linux run whose final line is a plain PASS. M7: 69,632 is attributed to ADR 0034, where the frame's shape is written -- it appears in no ADR 0019 file. The req_llm pin joins the ceiling table sourced to maintainer decision 4B of 2026-09-20, with the note that a dependency pin is a plan decision rather than a contract number, and ADR 0035 now says M5 makes the pin independently. M8: attach --take-over against a dormant session would have acquired, then been refused at attach, leaving the client holding a thirty-second lease on the session whose remedy begins by acquiring that same lease -- the refusal advising a step it had just blocked. Two rules close it: the existence query that precedes acquisition carries residency, so the refusal happens BEFORE any lease is granted, and every CLI exit path that holds a lease releases it explicitly, since ADR 0033 binds early release to that call alone. L1: the generation-2 schema and vectors files each carry their own pinned file digest beside the two generation 1 already pins. L2: restructuring LoopexProtocol.Session per generation -- schema_digest/0 is arity-zero over module attributes and negotiate/2 matches one @generation -- is named as loopex_protocol work owned by workstream 3. L3: joining release_apps is stated as separate from the cross_uid lane, which is its own invocation. The boundary table is updated for the daemon's own tree: observer cells are now parent-child relationships the daemon establishes or mechanisms inside core with line numbers, and the closing note says why -- an earlier draft filled that column with a link and a monitor the daemon could not hold. --- ...tachment-residency-and-replay-technical.md | 13 ++- ...controller-lease-and-takeover-technical.md | 6 +- ...ision-models-as-policy-inputs-technical.md | 8 +- docs/plans/M5-technical.md | 110 +++++++++++++----- docs/plans/M5.md | 9 +- 5 files changed, 106 insertions(+), 40 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 9decdcf33..16b1ec6af 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -156,7 +156,7 @@ which no client requests and every client may receive: | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining fatal classes the plan's map names | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining fatal classes the plan's map names — `fatal:supervision_fault` being the one a running daemon can reach | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | @@ -177,7 +177,7 @@ into a bound that already exists is the same guarantee with nothing new to justify. **This changes the generation-2 digest, and so do the error codes.** -`Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the +`LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits — five inputs, and generation 2 changes four of them: @@ -186,7 +186,7 @@ limits — five inputs, and generation 2 changes four of them: | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `session_dormant`, `index_full` where it is returned as a refusal rather than a field, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | | Limits | Unchanged from ADR 0023's ceilings | Listing the error codes matters because it is the input most easily forgotten: @@ -507,7 +507,12 @@ existing clients agreed to. The generation-2 schema and its vectors are new files beside generation 1's, as `apps/loopex_protocol/priv/schema/loopex-experimental-2.json` and `apps/loopex_protocol/priv/vectors/loopex-experimental-2.json`, reviewed with -the change that adds them; generation 1's bytes are untouched. A +the change that adds them, and **each carries its own pinned file digest** +written into the conformance module beside the two generation 1 already pins — +so an independent client can fetch either file and verify its bytes, and an +edit to a generation-2 file fails the same way an edit to a generation-1 file +does. The digests are computed and pinned when the files are written; +generation 1's bytes and its two pinned digests are untouched. A negotiation vector proves selection from a list that also names generation 1 and refusal of a generation-1-only list. The M4 foreground server keeps serving generation 1 only, with its one-attachment-per-process rule. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index e521cc0aa..2ad4e9f2c 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -98,7 +98,11 @@ the local store's writer marker, unchanged. session ID before attach. The daemon validates durable session existence first, and it does so with core's read-only session-existence query — the one that asks only whether the root holds that ID, with no attach, no - resume and no side effect. That matters here more than anywhere: acquire + resume and no side effect. That answer also carries residency, so a daemon + whose client is asking to drive a session it has not activated refuses + `session_dormant` **here, before any lease is granted** — granting first and + refusing later would leave the client holding a lease that blocks the resume + it is being told to perform. That matters here more than anywhere: acquire must be safe to call on an ID that turns out to be unknown, and an earlier draft that learned existence by calling `attach` or `resume` would have taken a durable or attaching side effect to answer a question. The diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 6b3fef18d..194b3f7c5 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -133,9 +133,11 @@ complete set, whatever the call does. So the first real call, and with it the first latency and price measurement, belongs to the milestone that accepts this decision. M5's move to `req_llm` -`~> 1.24.0` is explicit M5 scope for its own dependency reasons, separate from -this decision and not conditional on it, and adds no call path: nothing in M5 -calls anything `1.24.0` makes newly reachable. +`~> 1.24.0` is a pin **M5 makes independently**, on the maintainer's plan +decision of 2026-09-20 and for its own dependency reasons. It is not this +decision's number and does not become one if this decision is never accepted; +it adds no call path, since nothing in M5 calls anything `1.24.0` makes newly +reachable. ### Evidence diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 40878f3e1..4f04c53ee 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,10 +130,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, every client given one bounded best-effort `daemon.stopping` naming `operator_stop`, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `Loopex.Protocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason it carries, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded` and `fatal:supervision_fault` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach --observe` refused with `session_dormant` against a session this daemon has not activated and succeeding against one it has; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` against a session this daemon has not activated — in both roles, and for `--take-over` asserted to refuse **before any lease is granted**, so the `loopex resume --daemon` the refusal recommends is not blocked by a lease the refusal itself created — and succeeding against a session it has activated; a CLI holding a lease releasing it explicitly on every exit path, proved by a second client acquiring immediately rather than waiting out the term; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in two tiers, against `Loopex.Trace` as implemented rather than against ADR 0030's prose: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** the adapter module, entries for the three may exist and each is asserted to carry placeholders and no credential bytes and no token, which is what the implemented redaction pass gives. A third case asserts the three functions exist with exactly those identities, so neither tier can pass vacuously and an inlining or rename breaks the proof loudly. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Two runtimes composed in one VM, each with its own registry and custody, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every @@ -190,6 +190,14 @@ script runs, on the Linux lane only, for `loopex_daemon`: Two cases carry that tag and both must execute: a connection from a foreign uid refused before initialize, and one from the daemon's own uid accepted. +They are excluded from an ordinary run at the source, on the app-server's +precedent: `apps/loopex_daemon/test/test_helper.exs` ends +`ExUnit.start(exclude: [:cross_uid])`, exactly as +`apps/loopex_app_server/test/test_helper.exs` excludes `:node_client` and +`:real_provider` so an ordinary `mix test` needs neither Node nor a +credential. The fast check therefore never runs these two, and they run only +when the release check asks for them by name. + **The suite judge's rule is not enough here, so the script asserts the exact count.** `scripts/suite-summary.sh` fails a lane that executed no test — "a run that executed nothing is not a pass", as the script's own comment puts it @@ -199,17 +207,29 @@ script asserts this lane reported **exactly two executed tests**, and anything else, including one and including zero, is red. A missing second user is a red check, not a skipped case. -**And the single release run must be on Linux.** A cross-UID witness needs a -second unprivileged user and the `SO_PEERCRED` mechanism, neither of which the -Darwin lane supplies, so a release check run only on macOS would leave Outcome -2 unproved while reporting green. The closure matrix therefore states the -platform: `bash scripts/check-release.sh` runs once **on Linux**, and the -evidence page records the platform beside the result so a reviewer can see -which machine produced it. Closure is bound to that lane's recorded result and -to its platform. +**And the script has to make a Darwin run visibly incomplete, because today +nothing does.** `scripts/check-release.sh` has no platform branch — `uname` +appears only in its opening banner — and it pipes each lane's suite summary to +`/dev/null`, discarding the very line that would carry an executed count. So +M5 changes the script in two ways: + +- it reads `scripts/suite-summary.sh`'s result line instead of discarding it, + which is what lets any lane assert a count at all; and +- it branches on platform for this one lane. On Linux it runs + `mix test --only cross_uid` and asserts **exactly two** executed. On any + other platform it runs nothing for that lane, prints + `cross_uid: not run ()`, and the run's final line is + `PASS (closure-incomplete: cross_uid not run)` rather than a plain `PASS`. + +A Darwin release run is then still useful — it proves everything else — but it +cannot be mistaken for the run closure needs. **Closure requires the evidence +page to cite a Linux run whose final line is a plain `PASS`**, and a +`closure-incomplete` line is not that. `loopex_daemon` joins the `release_apps` list in the change that adds its -first release case, and only that list: every `release_apps` lane already runs +first release case. Joining that list is separate from the cross-UID lane, +which is its own invocation described above and not a `release_apps` run: +every `release_apps` lane already runs `--include long_bound`, so the daemon's long-duration bound tests are carried there and the application does not also join `long_bound_apps`, which exists for applications with no other release test. Each run's revision, platform, @@ -539,7 +559,7 @@ restriction.** Its forms are: | Form | What it does | | --- | --- | | `--observe` (default when neither role flag is given) | Attaches without acquiring, streams events, sends nothing. Refused by the daemon, not the client, if it ever tries | -| `--take-over` | Acquires a released or expired lease, waiting while an in-flight admission settles as ADR 0033's linearization requires; never forces a live holder off. Then attaches and streams | +| `--take-over` | Validates existence first, refusing `session_dormant` before any lease is taken if the session is dormant; otherwise acquires a released or expired lease, waiting while an in-flight admission settles as ADR 0033's linearization requires and never forcing a live holder off. Then attaches, streams, and releases the lease explicitly on exit | | `--take-over --prompt ""`, or `--take-over` with the prompt on stdin | The same — acquire, then attach — plus **one** command under the granted epoch, sent only after the attachment exists because ADR 0033 admits a mutation only from a controller-capable attachment, then streams to a terminal outcome | There is no interactive multi-turn controller in M5. A controller that could @@ -565,14 +585,36 @@ ends or the operator re-runs with `--take-over`. It does not race the deadline, because a mutation sent after the term elapsed will be refused anyway and a client that keeps trying only obscures when control was lost. -**A dormant session refuses an observer.** `loopex attach --observe` against a -session this daemon has not activated is refused with `session_dormant`, -naming the remedy: `loopex resume --daemon`. Attaching does not activate. -Activation is a controller's act — acquire, then resume with a fresh command -ID — because it starts a coordinator and counts against the activation -ceiling, and letting a read-only observer trigger it would let a watcher -consume a resource a controller needs and start durable recovery nobody asked -for. +**A dormant session refuses `attach` in either role, and refuses it before any +lease is taken.** `loopex attach` against a session this daemon has not +activated is refused with `session_dormant`, naming the remedy: +`loopex resume --daemon`. Attaching does not activate. Activation is a +controller's act — acquire, then resume with a fresh command ID — because it +starts a coordinator and counts against the activation ceiling, and letting a +read-only observer trigger it would let a watcher consume a resource a +controller needs and start durable recovery nobody asked for. + +**Where the refusal happens matters as much as that it happens.** ADR 0033's +acquisition already validates durable existence through core's read-only +existence query, and that query's answer carries residency, so the daemon +knows the session is dormant *before* it has anything to grant. The refusal is +therefore issued at that point: `attach --take-over` against a dormant session +refuses `session_dormant` **with no lease taken**. + +The alternative would strand the operator, which is how this was found. If +acquisition succeeded and only the attach refused, the client would exit +holding a thirty-second lease on the very session whose remedy — +`loopex resume --daemon` — begins by acquiring that same lease, so the command +the refusal recommends would itself refuse `control_held` until the term +elapsed. The refusal would be advising a step it had just blocked. + +Two rules close it together. The first is above: refuse before granting. The +second is general and applies to every exit path, not only this one — **a CLI +that holds a lease releases it explicitly before exiting**, by sending +`session.release_control`, because ADR 0033 binds early release to that call +alone and treats every transport loss, including a clean client exit, as a +wait for expiry. A client that simply closed its socket would leave the lease +held for its full term whatever the reason it stopped. **Cursor, reconnection and re-acquisition.** The client remembers the last event cursor it emitted and, on transport loss, reconnects at it, @@ -600,7 +642,7 @@ repair, with the reason class on `stderr`. | `loopex run --daemon`, `loopex resume --daemon` and the create-and-drive sequence | `docs/operator/daemon.md`, driving section | | `loopex sessions --daemon`, `--limit`, `--after`, `--status`, `index_full` | `docs/operator/daemon.md`, listing section | | `loopex daemon` composition inputs, readiness record, signals, exit classes | `docs/operator/daemon.md`, running section | -| `loopex attach` roles, one-shot control, `--after`, renewal loss, `session_dormant`, reconnect and re-acquisition | `docs/operator/daemon.md`, attaching section | +| `loopex attach` roles, one-shot control, `--after`, renewal loss, `session_dormant` before any lease, explicit release on exit, reconnect and re-acquisition | `docs/operator/daemon.md`, attaching section | ### Daemon Lifecycle and Orderly Shutdown @@ -810,7 +852,7 @@ the next marker holder removes. | `socket_permission_unverified` | Startup: subdirectory or socket ownership/mode could not be verified | | `store_lost` | Fail-stop: the Store terminated under a live listener | | `store_capacity_exceeded` | Fail-stop: the Store terminated on the capacity refusal specifically | -| `supervision_fault` | Fail-stop: a lease owner failed, under ADR 0033's daemon-fatal rule | +| `supervision_fault` | Fail-stop: a lease owner failed, under ADR 0033's daemon-fatal rule. On the wire this is `fatal:supervision_fault`, since ADR 0032's `reason` set admits the fatal classes only under that prefix | **The daemon's own log is bounded and redacted by the rules that already exist.** Everything the daemon writes to `stderr` — refusals, warnings, the @@ -877,29 +919,34 @@ plan names as new. It is the thing to check a change against. | Boundary | Owner | What fails | Who observes it, and how | What the client sees | Durable / not durable | | --- | --- | --- | --- | --- | --- | -| **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the daemon owns the Store *process* | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:166`). The daemon observes the death two ways, because `LoopexComposition.start_edge/2` uses `start_link` (`loopex_composition.ex:302-307`): it traps the exit and also monitors the adapter | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | +| **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the **daemon supervisor** owns the Store process as child 1 | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:166`). Its parent is the daemon supervisor, so the exit reason is reported there — no link the daemon must arrange and no monitor it must remember. Under `rest_for_one` the failure also takes children 2 to 4 | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | | **Store ↔ daemon (startup)** | The adapter | Marker held, unverifiable, log too large | `WriterLock.acquire` refuses with `store_writer_active` / `store_writer_unverifiable`; `Log.open` refuses `store_log_too_large` (`log.ex:80-84`) | Nothing — no socket exists yet | **Not durable:** nothing was written. Reverse cleanup leaves no marker | | **Core ↔ daemon: existence query** | `loopex` answers; the daemon asks | Root unreadable, malformed ID, unrecognised answer | The query's own closed result set — `present`, `absent`, `invalid_id`, `store_unavailable`, `unexpected` (this plan's new core operation) | The matching refusal, four of them distinct; nothing created, nothing attached, no lease | **Not durable:** the query writes nothing, proved by a byte-identical root | | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | -| **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The daemon's own supervisor: `one_for_all` up to the listener | `daemon.stopping` with `supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | +| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The daemon supervisor, where the lease owner is child 3: under `rest_for_one` its failure takes child 4, the listener, with it, and ADR 0033 makes it fatal to the instance | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | -| **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled. The invocation's failure is | +| **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The daemon's signal handler begins the ordered shutdown | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The daemon's signal handler begins the ordered shutdown; the tree's reverse-start-order termination supplies steps 3 to 5, and step 2's `Runtime.stop/1` targets child 2 under the daemon's own grace, killing `runtime.supervisor` on expiry | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | `terminate/2` in an orderly stop; `terminate/2` early on store loss; nothing on a kill | Nothing directly; the next daemon's start succeeds, succeeds, or recovers | **Not durable in the journal sense:** the marker is exclusion, not truth | -Two rows deserve their reading stated, because they are where earlier drafts +Three rows deserve their reading stated, because they are where earlier drafts went wrong. The **coordinator death** row is the one that forced `residency` to mean a daemon fact: there is no observer column entry available, so any design that needed one was unimplementable. The **Store ↔ daemon** row is the one that forced the fail-stop split: the marker is already released by the -time the daemon can act, so an ordered shutdown ending "stop the Store" had -nothing to stop. +time anything can act, so an ordered shutdown ending "stop the Store" had +nothing to stop. And that same row is why the daemon supervises its own tree: +an earlier draft filled its observer column with a link and a monitor the +daemon could not actually hold, because `LoopexComposition` takes the link in +a process it spawns and returns no adapter pid. Every observer cell in this +table is now a parent-child relationship the daemon itself establishes, or a +mechanism inside core with a line number, and nothing in between. ### Proportional Minimalism Budget @@ -966,7 +1013,8 @@ decision named above; M5 introduces none of its own. | Takeover grace beyond expiry | none; takeover is eligible at expiry and granted once the session's in-flight admission set is empty | ADR 0033 | | Writer epoch | opaque, at most 64 bytes, at least 128 bits of fresh randomness, minted per grant | ADR 0033 | | Credential size | 1 to 65,536 bytes | ADR 0019, unchanged by ADR 0034 | -| Credential frame cap | 69,632 bytes | ADR 0019, unchanged by ADR 0034 | +| Credential frame cap | 69,632 bytes | ADR 0034, which is where the frame's shape is written; no ADR 0019 file states it | +| `req_llm` version pin | `~> 1.24.0` | Maintainer decision 4B of 2026-09-20, a **plan** decision. A dependency pin is not a contract number: it binds what this milestone builds against and is changed by an ordinary reviewed dependency change, not by an ADR amendment | Count and byte ceilings apply together: an event that would exceed either triggers the stated detachment, eviction or refusal before the ceiling is diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 6acfc180e..b9379664e 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -579,7 +579,14 @@ lease — and the companion's rejoin order says where each part goes. activation refusal for a session this composition cannot serve, shutdown on store loss, capacity as one such loss, and reopening under the foreground server after an orderly stop. -3. **The socket transport and the daemon's operator contracts.** The +3. **The socket transport and the daemon's operator contracts.** This + workstream carries `loopex_protocol` work as well as daemon work, and the + protocol part is not small: `LoopexProtocol.Session` today holds one + generation in module attributes, with `schema_digest/0` taking no argument + and `negotiate/2` matching a single `@generation`. Serving two generations + from one module — and pinning both digests side by side in the conformance + module — means restructuring it per generation, which is where that + restructuring is owned. Then the daemon's side: the listener, its owner-only peer check and path bound, the startup ordering and its readiness line, signal handling and the orderly-shutdown sequence, the exit-status classes, `loopex daemon`, `loopex attach` and the live form From a21e415608404761dc041ae0a5f30aed967bbb9d Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 21:51:14 -0700 Subject: [PATCH 053/585] plan(M5): fix what my adversarial pass found in this round's diff Six findings against my own edits, four of them contradictions of the kind this review round exists to catch. AF1: ADR 0031 still carried the withdrawn, unimplementable claim that the daemon "composes the adapter through LoopexComposition.start_edge/2 ... and the daemon both traps exits there and monitors the adapter" -- exactly H1, surviving in the ADR after I fixed the plan. Replaced with the daemon supervising the adapter directly. AF2: the shared-surfaces row still said hosts "pass a token with the call", contradicting H4's composition binding. AF3/AF4: I first wrote that the daemon does not depend on loopex_composition. That was an overcorrection -- that application assembles the executor with its workspace lease and coding tools, the artifact store, the resolved policy, the runtime identity and the tool definitions, all of which the daemon needs, and duplicating them would be a second wiring layer. Reverted. The real difficulty is named instead and handed to the maintainer: both public entry points bundle wiring with ownership through RuntimeOwner, so either loopex_composition gains a narrow compose-without-owning entry point (the preferred shape, and a different change from the rejected one -- it exposes wiring, not store death or adapter identity) or the daemon assembles the pieces itself. Marked as the open decision the daemon workstream opens with. AF6: ADR 0033 still said one_for_all up to the listener while the plan said rest_for_one, and under rest_for_one a lease-owner failure would not have been daemon-fatal at all. Worse, plain rest_for_one would RESTART a failed Store or lease owner -- the two things that must never be restarted. The daemon supervisor now carries max_restarts: 0, so any child's failure exceeds intensity at once and the tree terminates in reverse start order. The Store's fail-stop and the lease owner's daemon-fatal rule become the same mechanism seen twice rather than two special cases, and ADR 0033 is aligned. AF8, the one that forced a restructure: with max_restarts: 0, step 2's explicit kill of the runtime supervisor would itself have exceeded intensity and torn the tree down from under steps 3 to 5. The shutdown is now the tree terminating -- listener, lease owner, runtime, Store -- with the runtime child's shutdown value set to the composed cleanup grace, which bounds the drain and ends in a kill, so decision 2's crash-equivalent ending comes from the child spec instead of from a manual timer that contradicted the supervision setting. One consequence is stated because it reverses an earlier draft: clients are told BEFORE work is drained, which is better for the one party that cannot see inside the daemon. --- ...store-selection-and-migration-technical.md | 17 +- ...controller-lease-and-takeover-technical.md | 9 +- docs/plans/M5-technical.md | 210 +++++++++++------- 3 files changed, 141 insertions(+), 95 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 10ae4aae5..8c6799b6b 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -29,13 +29,16 @@ control.** This adapter answers an append error with `terminate/2` releases the marker as it goes. So on a store loss the marker is released **before** the daemon can react, and any sequence ending "then stop the Store" is unrunnable, because the Store is what died. The daemon's only -correct response is a fail-stop: observe the termination — it composes the -adapter through `LoopexComposition.start_edge/2`, which uses `start_link`, so -the adapter is linked to the composing process, and the daemon both traps -exits there and monitors the adapter so the signal cannot be missed — then -refuse service, close every connection with `store_lost`, or -`store_capacity_exceeded` where that was the store's own reason, unlink the -socket and exit non-zero. The next daemon finds no marker to recover, because +correct response is a fail-stop, and it arranges to be able to make it: the +daemon supervises the adapter **directly**, as the first child of its own +supervisor, so the adapter's termination and its exit reason are reported to +a process the daemon controls. It does not compose through +`LoopexComposition`, whose `start_edge/2` takes the `start_link` inside a +process `RuntimeOwner` spawns and which returns no adapter pid — a daemon on +that bracket could not observe this failure at all. On the reported exit it +refuses service, closes every connection with `store_lost`, or +`store_capacity_exceeded` where that was the store's own reason, unlinks the +socket and exits non-zero. The next daemon finds no marker to recover, because the dying store already gave it back. An abrupt kill of the daemon runs no `terminate/2` at all, which is why *that* diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 2ad4e9f2c..0ee3de7d0 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -53,9 +53,12 @@ sockets intact; that was withdrawn on 2026-09-20, on an independent review's finding, because a successor acquire could then be granted while a forgotten admission was still able to settle. -So the session-owner tree is supervised `one_for_all` up to the listener: an -owner's failure closes the listener and every connection, the daemon exits, -and the daemon restarts with no lease anywhere, no connection, and no +So a lease owner's failure is fatal to the daemon instance, and the daemon's +supervision supplies that without special-case code: the lease owner is a +child of the daemon's own supervisor, which carries `max_restarts: 0`, so the +failure exceeds the restart intensity at once, the supervisor terminates its +remaining children in reverse start order and exits. Every connection closes +with it, and the daemon restarts with no lease anywhere, no connection and no session activated. No successor acquire exists to be granted wrongly, because no connection survives to make one. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 4f04c53ee..2e6ea3b9f 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -75,7 +75,7 @@ to the integrator, who resolves them rather than either writer: | Shared surface | Why both reach it | | --- | --- | -| Host composition — `apps/loopex_composition`, `apps/loopex_app_server/lib/loopex_app_server/host.ex`, `apps/loopex_cli` | The credential item makes every host compose a routing registry and a custody process, pass a token with the call and delete the operator's variable; the daemon *is* a new host composed the same way, and `host.ex:221` is where the variable is read today | +| Host composition — `apps/loopex_composition`, `apps/loopex_app_server/lib/loopex_app_server/host.ex`, `apps/loopex_cli` | The credential item makes every host compose a routing registry, a custody process and the token bound in its model options, and delete the operator's variable; the daemon *is* a new host composed the same way, and `host.ex:221` is where the variable is read today | | The integration scripts — `scripts/check-release.sh` and its fixtures | Workstream 5 selects the real-provider lane; the daemon workstreams add `loopex_daemon` to `release_apps` and the Linux cross-uid case | | Provider and credential documentation under `docs/operator/` and `docs/developer/` | Workstream 5 adds the operator credential sentence and the host-composition note; workstream 6 rewrites the same pages for the daemon | | Closure evidence — `docs/evidence/M5-closure-runs.md` and `docs/evidence/README.md` | Every workstream's runs, the security review and the demonstration are retained on one page | @@ -682,7 +682,7 @@ this plan wants impossible. Two facts in the code say so: `{:EXIT, _owned_pid, reason}` and the owner runs `cleanup/1` **immediately** — stopping every owned edge including the Store, and releasing the marker — before the daemon has told a single client, unlinked the socket, or reached - anything this section calls step 3. + told a single client or unlinked the socket. So `apps/loopex_daemon` supervises its own children directly, in start order: @@ -693,13 +693,31 @@ So `apps/loopex_daemon` supervises its own children directly, in start order: | 3 | The lease owner supervisor | The daemon's own, under ADR 0033 | | 4 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | -The strategy is **`rest_for_one`**. It is the strategy that matches the -dependency direction already present: each child depends on the ones started -before it and on none started after, so the Store failing must take the -runtime, the lease owner and the listener with it, while the listener failing -need not take the Store. `one_for_all` would also be safe but says less — it -would claim the listener's failure must destroy the Store, which is not true -and would make the tree harder to reason about later. +**The strategy is `rest_for_one` with `max_restarts: 0`**, and the second half +is what makes the failure rules in ADR 0032 and ADR 0033 true rather than +aspirational. + +`rest_for_one` expresses the dependency direction that is actually there: each +child depends on those started before it and on none started after. But by +itself it would *restart* — and every restart here is wrong. A Store that +terminated on an append error has a durable cause a restart cannot fix, and +restarting it would reacquire the marker only to fail again. A lease owner +that died lost the in-flight admission set, which is precisely what ADR 0033 +says must not be silently reconstructed. So the daemon supervisor carries +`max_restarts: 0`: **any child's failure exceeds the intensity immediately**, +the supervisor terminates its remaining children in reverse start order and +exits, and the daemon is fail-stop for every child uniformly. + +That one setting is what gives this section its shape. The Store's fail-stop +and the lease owner's daemon-fatal rule are the same mechanism seen twice, +not two special cases anyone has to implement separately. And reverse-start- +order termination — a property of every strategy, not only this one — is what +stops the Store last without a written sequence. + +`one_for_all` would also have been safe but says less: it would claim the +listener's failure must destroy the Store, which is not the dependency that +exists, and would make the tree harder to reason about when something is +added to it later. This buys exactly the two properties the bracket could not give: @@ -711,8 +729,35 @@ This buys exactly the two properties the bracket could not give: supervisor terminates children in the reverse of their start order, so listener, lease owner, runtime, Store — which is the ordered shutdown below, obtained from the supervision strategy rather than from a sequence someone - has to remember to write. And step 2's explicit `Runtime.stop/1` targets - child 2, a *sibling*, so it cannot reach the Store. + has to remember to write. The runtime is terminated before it, as a sibling + in that order, so nothing the daemon does to end work can reach the Store + early. + +**What the daemon still takes from `loopex_composition`, and one seam that +needs a decision.** Owning the tree is about *lifetime*, not about wiring. +The daemon still needs everything that application assembles — the executor +with its workspace lease and coding tools, the artifact store, the resolved +policy, the runtime identity, the tool definitions — and duplicating that +would be a second copy of a wiring layer, which the minimalism budget forbids +on its face. + +The difficulty is that both public entry points, `start/1` and +`with_runtime/2`, bundle the wiring with the ownership: each goes through +`RuntimeOwner`, which is the bracket the daemon must not use. So one of two +things happens, and the maintainer should choose rather than have it decided +by whoever writes the code first: + +- **`loopex_composition` gains a narrow compose-without-owning entry point** + — the wiring it already performs, returning the started pieces to a caller + that supervises them — and the daemon calls that. This is a small addition + to a shared application, and it is a *different* change from the one + rejected below: it exposes wiring, not store death or adapter identity. +- **Or the daemon assembles those pieces itself** from the same public + building blocks the composition uses, accepting a second assembly site. + +This pair states the first as the preferred shape, because it keeps one +wiring layer, and marks it as the open implementation decision the daemon +workstream opens with. The rejected option is recorded: changing `LoopexComposition` to surface store death and return the adapter pid. It is a host convenience application that @@ -734,77 +779,74 @@ than in taste: `Loopex.Store.Local` answers an append error with observes it, the store is gone and the marker is already released. A sequence that ends "then stop the Store" cannot run when the Store is what died. -**Daemon-initiated shutdown, in order.** `SIGTERM` or `SIGINT` starts it, and -from that instant: - -1. **Refuse new work.** The listener stops accepting, so a new connection is - refused rather than queued, and the daemon admits no new mutation on any - existing connection. Queries and attach-state reads still answer, because - they change nothing and a client deserves to learn what is happening. -2. **Drain, then end what has not settled — without claiming an outcome.** - Admitted work gets the composed cleanup grace to finish on its own. What - has not settled when the grace elapses is ended by stopping the runtime: - `Loopex.Runtime.stop/1` is `Supervisor.stop(supervisor, :normal)`, and each - session coordinator is a `restart: :temporary` child with `shutdown: 5_000` - that neither traps exits in `init/1` nor defines `terminate/2` — so it - receives the shutdown exit and dies without running any terminal code. That - is **crash-equivalent by construction**, and it is the point: the daemon - claims no terminal mutation for work it ended. - - **The daemon does not rely on the runtime's own teardown being bounded, - because it is not.** `Supervisor.stop/3` takes an `:infinity` call timeout - by default, and the runtime tree's own values do not close that: core - declares `shutdown: 5_000` for a session coordinator but `shutdown: - :infinity` for an owner group — whose `terminate/2` itself calls +**Daemon-initiated shutdown is the tree terminating, in reverse start order.** +`SIGTERM` or `SIGINT` asks the daemon supervisor to terminate. It is not a +sequence anyone writes: a supervisor terminates children in the reverse of +their start order, so listener, lease owner, runtime, Store falls out of the +tree above, and each child's own `shutdown` value bounds its part. An ordered +termination is also not a child failure, so it does not trip `max_restarts: +0` — that setting governs a child dying on its own, which is the fail-stop +path below. + +1. **The listener terminates first.** It stops accepting, so a new connection + is refused rather than queued; it sends each open connection one + `daemon.stopping` naming `operator_stop`, bounded best-effort as ADR 0032 + fixes — one write attempt into the existing 4 MiB output buffer — and + closes it. Clients therefore learn *first*, before anything else is torn + down, which is the right order for the one party that cannot see inside the + daemon. +2. **The lease owner terminates.** Every lease vanishes with it. Nothing + durable is involved, and no client is left holding one, because no + connection survived step 1. +3. **The runtime terminates, and this is where admitted work ends.** The + daemon gives the runtime child a `shutdown` value of the **composed cleanup + grace** — the same value the sessions were composed with, so no number is + introduced. Work that settles within it settles normally. Work that does + not is ended when the supervisor's shutdown timeout elapses and it kills + the child, which is **crash-equivalent by definition**: no terminal + mutation is claimed, no `cancelled`, no `outcome_unknown`, no abort record. + A mutation whose commit was ambiguous stays `commit_unknown` and fenced, + and the reconciliation ADR 0006 and ADR 0018 already define settles it at + the next activation — exactly as after an abrupt death. + + **This is why the daemon sets that value rather than trusting the + runtime's own.** The runtime's internal teardown is bounded only + transitively: core declares `shutdown: 5_000` for a session coordinator but + `shutdown: :infinity` for an owner group — whose `terminate/2` itself calls `Supervisor.stop(workers, :shutdown, :infinity)` — and three of the runtime - supervisor's children are supervisors, which default to `:infinity`. The - runtime's teardown is bounded only transitively, by whatever leaf workers - happen to carry, and "5,000 ms for a coordinator" is not the bound of - anything. - - So the daemon supplies its own. Step 2 calls `Runtime.stop/1` under the - **composed cleanup grace** — the same value the session was composed with, - so no number is introduced — and if it has not returned when that elapses, - the daemon kills the runtime supervisor outright: - `Process.exit(runtime.supervisor, :kill)`, the pid `%Loopex.Runtime{}` - exposes. A brutal kill is crash-equivalent *by definition*, which is - precisely what this step claims to be, so the fallback is not a compromise - of the property — it is the property, reached directly. A mutation whose commit was - ambiguous stays `commit_unknown` and fenced, and the reconciliation - ADR 0006 and ADR 0018 already define settles it at the next activation — - exactly as it would after an abrupt death. - - An earlier draft said running effects enter the configured cancellation - sequence. That is withdrawn: cancellation is the coordinator's to run as - part of a session's own durable command, not something a daemon may drive - from outside, and a daemon-side cancellation path is precisely the second - loop this milestone forbids. Two alternatives were rejected with it. + supervisor's children are supervisors, which default to `:infinity`. "5,000 + ms for a coordinator" is not the bound of anything. A `shutdown` value on + the daemon's own child spec is a bound the daemon owns, and it ends in a + kill, which is the property this step wants rather than a compromise of it. + + An earlier draft had the daemon call `Runtime.stop/1` explicitly and then + kill the supervisor pid on a timer. That is withdrawn: with + `max_restarts: 0` an explicit kill of a supervised child would itself + exceed the intensity and tear the tree down from under the remaining + steps. Expressing the same bound as the child's `shutdown` value obtains + it without that contradiction. + + Also withdrawn, from an earlier draft: that running effects enter the + configured cancellation sequence. Cancellation is the coordinator's to run + as part of a session's own durable command, not something a daemon may + drive from outside, and a daemon-side cancellation path is precisely the + second loop this milestone forbids. Two alternatives were rejected with it. Host-authorized durable aborts — the daemon admitting an abort per session on the way down — would have the daemon issuing mutations on nobody's authority, at the moment it is least able to see them through. An unbounded - natural drain — waiting for every effect to finish — would make `SIGTERM` - unbounded, which is not a stop. -3. **Tell every client, then close.** Each connection gets one - `daemon.stopping` notification naming the reason — `operator_stop` here — - and the daemon then closes it. Delivery is bounded best-effort: one write - attempt into the connection's existing 4 MiB output buffer, then close - regardless. ADR 0032 fixes the record and that bound, and a backpressured - or dead client may receive nothing and learn of the stop only by its socket - closing. -4. **Unlink the socket.** The path is removed, so no later client connects to - a dead endpoint and the next daemon binds cleanly rather than inheriting a - stale file. -5. **Stop the Store, last.** The marker is released by the Store's own - `terminate/2` at that moment — see the marker invariant in ADR 0031 — so - stopping the Store last is exactly what makes the marker outlive every - session operation that might still have needed it. - - This is not a step someone has to remember to write: the daemon supervisor - starts the Store first, so reverse-start-order termination stops it last. - Stopping the daemon supervisor *is* steps 3 to 5 in order — listener, lease - owner, runtime, Store — and the marker comes back when the last of those - terminates. -6. **Exit `0`.** + natural drain would make `SIGTERM` unbounded, which is not a stop. +4. **The Store terminates last**, and its `terminate/2` releases the writer + marker — see the marker invariant in ADR 0031. Stopping it last is what + makes the marker outlive every session operation that might still have + needed it, and it is obtained from the start order rather than from a step + someone has to remember. +5. **The socket path is unlinked** and the daemon **exits `0`**. + +One ordering consequence is worth stating because it reverses an earlier +draft: clients are told *before* work is drained, not after. That is +deliberate. The drain does not need connections to exist, and a client that +must reconnect elsewhere is better served by learning immediately than by +waiting out a cleanup grace it cannot see. **Store loss, a fail-stop path.** The daemon supervisor is the Store adapter's parent, so the adapter's termination is reported to it with the adapter's own @@ -824,11 +866,9 @@ the ordered sequence: 4. Exit non-zero with that class on `stderr`. **There is no "stop the Store" step**, because the Store already stopped and the marker is already released; the next daemon finds no marker to recover rather than a stale - one. The daemon does not restart the Store either: `rest_for_one` would - ordinarily restart child 1, so the Store's child specification is - `restart: :temporary` in this tree — a store that terminated on an append - error has a durable cause a restart cannot fix, and restarting it would - reacquire the marker only to fail again. + one. Nothing restarts the Store: the daemon supervisor's `max_restarts: 0` + makes this failure fatal to the tree rather than a restart, which is why + this path exists at all. Nothing durable is at risk in that ordering: whatever was ambiguous is `commit_unknown` in the journal and is reconciled at the next activation, and @@ -925,12 +965,12 @@ plan names as new. It is the thing to check a change against. | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The daemon supervisor, where the lease owner is child 3: under `rest_for_one` its failure takes child 4, the listener, with it, and ADR 0033 makes it fatal to the instance | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The daemon supervisor, where the lease owner is child 3: `max_restarts: 0` makes the failure exceed intensity at once, so the supervisor terminates the tree in reverse start order and exits — ADR 0033's daemon-fatal rule, obtained from the supervision setting rather than from special-case code | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The daemon's signal handler begins the ordered shutdown; the tree's reverse-start-order termination supplies steps 3 to 5, and step 2's `Runtime.stop/1` targets child 2 under the daemon's own grace, killing `runtime.supervisor` on expiry | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The daemon supervisor terminates; reverse start order gives listener, lease owner, runtime, Store, and the runtime child's `shutdown` value — the composed cleanup grace — bounds the drain and ends in a kill | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | `terminate/2` in an orderly stop; `terminate/2` early on store loss; nothing on a kill | Nothing directly; the next daemon's start succeeds, succeeds, or recovers | **Not durable in the journal sense:** the marker is exclusion, not truth | From 343ed3185271d55a90b439ec4883d0f278bb3c13 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:06:08 -0700 Subject: [PATCH 054/585] plan(M5): replace the daemon supervisor with an owner process Review findings N1 through N10, each verified before the text changed and two re-proved by running the code. N1. I re-ran Entry.render/2 rather than trusting my own reading, and the finding holds exactly: @identity_bytes is 64 (trace/entry.ex:28), redact/3 placeholders a binary only when byte_size > 64 (:148-149), and bare list and tuple elements are walked with key = nil (:151, :153-159, :206-213) falling through to redact(term, _, _) -> term (:181). Measured: a credential of 1, 40, 51 and 64 bytes renders VERBATIM in a bare argument list and inside {:ok, cred}; only the credential-keyed map is placeholdered, and that works at every size. ADR 0019 admits credentials from 1 byte, so the leaking range is real. "Redacted by size even as a bare positional argument" is withdrawn with the probe table recorded. The shape is now bound: the three named functions carry credential bytes only as a value under a credential-named key, in every argument and every return -- receive_custody_reply/2 returns {:ok, %{credential: bytes}}, write_credential_frame/2 takes the keyed map -- so @credential_pattern placeholders them at any size. The witness calls each with a ONE-BYTE credential under a session naming the module explicitly, which is the size at which a size-based redaction fails and a shape-based one does not. N2, N3, N7, N10. The Supervisor design does not work, and N3 alone settles it: Loopex.Runtime.start_link/1 returns {:ok, %Loopex.Runtime{}} (runtime.ex:90-99) -- a struct, not {:ok, pid} -- so the runtime is not a startable child at all. A supervisor also offers no callback that can read a terminating child's exit reason, so store_lost, store_capacity_exceeded and supervision_fault would be indistinguishable at the one moment the daemon must name a class; with intensity zero the supervisor exits :shutdown and the child's reason is logged and discarded; and its own termination would leave the socket unlinked and no client told, needing a fifth component. The top-level component is now Loopex.Daemon.Owner, a GenServer that traps exits and start_links the Store adapter (keeping the pid), the runtime (keeping the struct), the lease owner and the listener -- the pattern RuntimeOwner already uses. Its {:EXIT, pid, reason} clause is the whole failure rule AND the fatal-class map's reader. There is no restart strategy, so rest_for_one, one_for_all and max_restarts are gone; the Store's inherited restart: :permanent (local.ex:55, use GenServer) is no longer load-bearing. The rejected supervisor option is recorded with all three reasons. That also restores the original H3 mechanism: the owner calls Runtime.stop/1 under the composed cleanup grace and kills runtime.supervisor on expiry, with no intensity left to trip. N4. The composition seam is decided rather than left open -- one branch was already non-compliant, since duplicating the wiring is what the minimalism budget forbids. loopex_composition gains one narrow public function that runs its edge-assembly sequence in the CALLER's process and returns the edges, so the daemon owner's links land on the owner and RuntimeOwner keeps using the same function. Decided in M5.md's design decisions, explained in the companion, with a loopex_composition ownership row and a minimalism entry naming what it unifies. N5, N6. Siting session_dormant in acquisition was wrong twice: ADR 0033's concept drives a dormant session by acquiring, resuming and attaching, and ADR 0032's recovery acquires a dormant session at step 7, so the refusal would break the path it recommends -- and session.acquire_control carries only session_id and request_id, so telling the two intentions apart would need a new field and a new digest input. The refusal moves to the daemon's ATTACH handler, which consults its own residency index. attach --take-over therefore acquires, is refused at attach, and releases the lease explicitly on that exit path. "The existence query's answer carries residency" is deleted from both files: the query's result set is closed at five and core carries no daemon fact. N8 was resolved by the rewrite. N9: the within-one-runtime concurrency witness is meaningless once the token is composition-bound -- two invocations of one runtime carry the same token -- so it is folded into the two-runtime isolation case as a stated corollary. --- ...controller-lease-and-takeover-technical.md | 27 +- ...andoff-over-bootstrap-channel-technical.md | 56 ++- ...edential-handoff-over-bootstrap-channel.md | 5 +- docs/plans/M5-technical.md | 370 +++++++++--------- docs/plans/M5.md | 28 ++ 5 files changed, 268 insertions(+), 218 deletions(-) diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 0ee3de7d0..98f7d766e 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -54,13 +54,15 @@ finding, because a successor acquire could then be granted while a forgotten admission was still able to settle. So a lease owner's failure is fatal to the daemon instance, and the daemon's -supervision supplies that without special-case code: the lease owner is a -child of the daemon's own supervisor, which carries `max_restarts: 0`, so the -failure exceeds the restart intensity at once, the supervisor terminates its -remaining children in reverse start order and exits. Every connection closes -with it, and the daemon restarts with no lease anywhere, no connection and no -session activated. No successor acquire exists to be granted wrongly, because -no connection survives to make one. +own structure supplies that without special-case code: the lease owner is one +of four processes the daemon's owner process `start_link`s, the owner traps +exits, and its `{:EXIT, pid, reason}` clause treats **any** linked exit as +fatal. There are no restarts to configure and no strategy to get wrong. The +owner classifies the exit as `fatal:supervision_fault`, has the listener tell +every client, closes them, unlinks the socket and exits non-zero; the daemon +comes back with no lease anywhere, no connection and no session activated. No +successor acquire exists to be granted wrongly, because no connection +survives to make one. That rule stands on its own, and this pair does not lean on core to help it. An earlier draft said core would fence the forgotten admission by epoch @@ -101,11 +103,12 @@ the local store's writer marker, unchanged. session ID before attach. The daemon validates durable session existence first, and it does so with core's read-only session-existence query — the one that asks only whether the root holds that ID, with no attach, no - resume and no side effect. That answer also carries residency, so a daemon - whose client is asking to drive a session it has not activated refuses - `session_dormant` **here, before any lease is granted** — granting first and - refusing later would leave the client holding a lease that blocks the resume - it is being told to perform. That matters here more than anywhere: acquire + resume and no side effect. Its answer is one of the five in + ADR 0032's closed set and nothing more — it says whether the root holds the + session, not whether this daemon has activated it, which is a daemon fact + core does not carry. Acquisition therefore does **not** refuse a dormant + session: a dormant session is acquired here precisely so it can be resumed, + which is the sequence this ADR's concept sets out. That matters here more than anywhere: acquire must be safe to call on an ID that turns out to be unknown, and an earlier draft that learned existence by calling `attach` or `resume` would have taken a durable or attaching side effect to answer a question. The diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 7760f425a..3660d11f3 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -242,17 +242,49 @@ boundary, not an absolute: every default configuration the credential-bearing work is untraced, which is the strong property and the one M5 proves first. 2. **If a host explicitly names the adapter module**, its functions become - traceable — the sender inherits the trace flag, since `process_flags/2` + traceable — a host may name any module through the explicit-module route, + `supervised/1` recurses so the sender is in scope, and `process_flags/2` sets `:set_on_spawn` on every non-root traced process — and what protects - the bytes then is the redaction pass, which *is* implemented: - `Entry.render/2` calls `redact/3`, which replaces a credential-keyed - value with a `credential` placeholder and **any binary longer than the - identity bound with a `bytes` placeholder**. A credential is 1 to 65,536 - bytes, so it is redacted by size even as a bare positional argument. + the bytes then is the redaction pass, which *is* implemented. But it + protects them **only in one shape**, and that shape is therefore part of + this contract rather than an implementation detail. + + `Entry.render/2` calls `redact/3`, which placeholders a value whose + **key** matches `@credential_pattern` — `credential|secret|token|api[_-]? + key|password|authorization` — at any size, and otherwise placeholders a + binary only when it is **longer than `@identity_bytes`, which is 64**. + Bare list and tuple elements are walked with `key = nil` and a short + binary falls through to `redact(term, _, _) -> term`, returned verbatim. + + An earlier draft of this pair concluded from that code that a credential + is "redacted by size even as a bare positional argument". **That is + false**, and running `Entry.render/2` says so: + + | Credential size | Bare arg `[cred]` | Tuple `{:ok, cred}` | Keyed `%{credential: cred}` | + | --- | --- | --- | --- | + | 1 byte | **leaks** | **leaks** | placeholdered | + | 40 bytes | **leaks** | **leaks** | placeholdered | + | 51 bytes | **leaks** | **leaks** | placeholdered | + | 64 bytes | **leaks** | **leaks** | placeholdered | + | 65 bytes | placeholdered | placeholdered | placeholdered | + + ADR 0019 admits a credential of 1 to 65,536 bytes, so the leaking range + is real, not hypothetical. The size reading is withdrawn with those + numbers recorded. + + **So the shape is bound, and that is what makes the second tier true.** The + three functions below carry credential bytes **only as a value under a + credential-named key**, in every argument and every return value: + `receive_custody_reply/2` returns `{:ok, %{credential: bytes}}` and never + `{:ok, bytes}`; `write_credential_frame/2` takes that keyed map, not a bare + binary. Under `@credential_pattern` the key `credential` matches, so the + value is placeholdered at **any** size, including one byte. Nothing relies + on how long a credential happens to be. **The three functions stay, and their role is now precise.** They are not match-specification targets, because those do not exist; they are **the only - functions that touch credential bytes, all executed in the sender process**: + functions that touch credential bytes, all executed in the sender process, + and all carrying them keyed**: | Function | What it touches | | --- | --- | @@ -262,9 +294,13 @@ boundary, not an absolute: Naming them is what makes the witness precise and the redaction obligation checkable: any credential byte in the parent passes through one of these - three and nowhere else. The names and arities are the contract, and a test - asserts they exist with these identities so an inlining or a rename breaks - the proof loudly rather than quietly moving bytes into an unnamed function. + three and nowhere else. The names, the arities **and the keyed shape** are + the contract, and one case asserts all three: that the functions exist with + these identities, and that calling each with a **one-byte** credential under + a trace session naming the module explicitly produces no entry containing + that byte. One byte is the point — it is the size at which a size-based + redaction would fail and a shape-based one does not — so an inlining, a + rename, or a change that passes bytes bare breaks the proof loudly. **The proof is two cases, matching the two tiers.** Under the **default** configuration, a real trace session at the `arguments` level over a real diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index ee8eb734e..a1475efa7 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -95,7 +95,10 @@ match-specification exclusion the tracer does not have: the adapter is in no default trace namespace, so the credential work is untraced under every default configuration, and a host that explicitly names the adapter module gets entries whose credential values the implemented redaction pass replaces -with placeholders. The companion names the three functions that touch +with placeholders — which holds because the companion binds the *shape*, so +those bytes always travel under a credential-named key and are placeholdered +at any size. It would not hold by size alone: the pass leaves a short binary +verbatim, and a credential may be one byte. The companion names the three functions that touch credential bytes — they are the whole of the parent-side surface — and M5 proves both tiers. The drift between ADR 0030's prose and its implementation is flagged for the maintainer, not patched here. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 2e6ea3b9f..92ea717c3 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -41,7 +41,8 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | -| `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses | Daemon lifetime or residency | +| `loopex_composition` | The edge-assembly sequence, and the one new public function that runs it in the caller's process and returns the edges — used by `RuntimeOwner` and by the daemon's owner | Daemon lifetime, ownership of what it assembles, or any knowledge of a daemon | +| `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses, and its use of `with_runtime/2`, which M5 does not change | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon` with its readiness line, signal handling and exit classes, `loopex attach` with its roles, takeover presentation and cursor reconnect, the live `loopex sessions --daemon` form beside the unchanged offline one, and the host-side credential custody and registry it composes | Normative lease or session semantics, and any change to the released offline `loopex sessions` | | `loopex_llm_reqllm` | The credential handoff, its sender, the token it accepts, the launcher's unchanged ADR 0019 scrubbing enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | @@ -133,8 +134,8 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded` and `fatal:supervision_fault` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` against a session this daemon has not activated — in both roles, and for `--take-over` asserted to refuse **before any lease is granted**, so the `loopex resume --daemon` the refusal recommends is not blocked by a lease the refusal itself created — and succeeding against a session it has activated; a CLI holding a lease releasing it explicitly on every exit path, proved by a second client acquiring immediately rather than waiting out the term; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in two tiers, against `Loopex.Trace` as implemented rather than against ADR 0030's prose: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** the adapter module, entries for the three may exist and each is asserted to carry placeholders and no credential bytes and no token, which is what the implemented redaction pass gives. A third case asserts the three functions exist with exactly those identities, so neither tier can pass vacuously and an inlining or rename breaks the proof loudly. The registry lookup is proved to carry no credential. Two invocations with distinct credentials run at once and neither child, nor either child's diagnostics, observes the other's. Two runtimes composed in one VM, each with its own registry and custody, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease releasing it explicitly on every exit path; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in two tiers, against `Loopex.Trace` as implemented rather than against ADR 0030's prose: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** the adapter module, entries for the three may exist and each is asserted to carry placeholders and no credential bytes and no token. That second tier holds because ADR 0034 binds the **shape**: the three carry credential bytes only under a credential-named key, which `@credential_pattern` placeholders at any size. It does not hold by size — running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim, and only a credential-keyed value placeholdered at every size — so the witness calls each of the three with a **one-byte** credential under a session naming the module, and asserts no entry contains that byte. A third case asserts the three identities, so neither tier can pass vacuously. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -559,7 +560,7 @@ restriction.** Its forms are: | Form | What it does | | --- | --- | | `--observe` (default when neither role flag is given) | Attaches without acquiring, streams events, sends nothing. Refused by the daemon, not the client, if it ever tries | -| `--take-over` | Validates existence first, refusing `session_dormant` before any lease is taken if the session is dormant; otherwise acquires a released or expired lease, waiting while an in-flight admission settles as ADR 0033's linearization requires and never forcing a live holder off. Then attaches, streams, and releases the lease explicitly on exit | +| `--take-over` | Acquires a released or expired lease, waiting while an in-flight admission settles as ADR 0033's linearization requires and never forcing a live holder off, then attaches. Against a session this daemon has not activated the attach refuses `session_dormant`, and the client **releases the lease explicitly** before exiting non-zero with `loopex resume --daemon` as the remedy. On every other exit path it also releases explicitly | | `--take-over --prompt ""`, or `--take-over` with the prompt on stdin | The same — acquire, then attach — plus **one** command under the granted epoch, sent only after the attachment exists because ADR 0033 admits a mutation only from a controller-capable attachment, then streams to a terminal outcome | There is no interactive multi-turn controller in M5. A controller that could @@ -585,36 +586,44 @@ ends or the operator re-runs with `--take-over`. It does not race the deadline, because a mutation sent after the term elapsed will be refused anyway and a client that keeps trying only obscures when control was lost. -**A dormant session refuses `attach` in either role, and refuses it before any -lease is taken.** `loopex attach` against a session this daemon has not -activated is refused with `session_dormant`, naming the remedy: -`loopex resume --daemon`. Attaching does not activate. Activation is a +**A dormant session refuses `attach` in either role.** `loopex attach` against +a session this daemon has not activated is refused with `session_dormant`, +naming the remedy: `loopex resume --daemon`. Attaching does not activate. Activation is a controller's act — acquire, then resume with a fresh command ID — because it starts a coordinator and counts against the activation ceiling, and letting a read-only observer trigger it would let a watcher consume a resource a controller needs and start durable recovery nobody asked for. -**Where the refusal happens matters as much as that it happens.** ADR 0033's -acquisition already validates durable existence through core's read-only -existence query, and that query's answer carries residency, so the daemon -knows the session is dormant *before* it has anything to grant. The refusal is -therefore issued at that point: `attach --take-over` against a dormant session -refuses `session_dormant` **with no lease taken**. - -The alternative would strand the operator, which is how this was found. If -acquisition succeeded and only the attach refused, the client would exit -holding a thirty-second lease on the very session whose remedy — -`loopex resume --daemon` — begins by acquiring that same lease, so the command -the refusal recommends would itself refuse `control_held` until the term -elapsed. The refusal would be advising a step it had just blocked. - -Two rules close it together. The first is above: refuse before granting. The -second is general and applies to every exit path, not only this one — **a CLI -that holds a lease releases it explicitly before exiting**, by sending -`session.release_control`, because ADR 0033 binds early release to that call -alone and treats every transport loss, including a clean client exit, as a -wait for expiry. A client that simply closed its socket would leave the lease -held for its full term whatever the reason it stopped. +**The refusal sits at attach, not at acquisition, and that placement took +correcting.** An earlier draft refused inside `session.acquire_control` — "no +lease taken" — which reads well and is wrong twice over. ADR 0033's own +concept says a known dormant session is driven by *acquiring by ID, resuming +with the granted epoch and attaching*, and ADR 0032's recovery sequence +acquires a dormant session at step 7 before resuming at step 8. Refusing +acquisition for dormancy would break the one path that is supposed to bring a +dormant session back. And acquisition could not tell the two intentions apart +anyway: `session.acquire_control` carries `session_id` and `request_id` and +nothing about what the caller means to do next, so distinguishing "acquiring +to resume" from "acquiring to attach" would need a new field — a new input to +the generation-2 schema digest, added to make a client-side convenience +expressible. + +So the daemon's **attach** handler is where it belongs. That handler consults +the daemon's own residency index — a daemon fact the daemon owns, needing +nothing from core — and refuses `session_dormant` for a session this lifetime +has not activated. `loopex resume --daemon` is unaffected: it acquires, +resumes, and only then attaches, by which time the session is active. + +`loopex attach --take-over` against a dormant session therefore acquires +successfully and is refused at attach, holding a lease it no longer wants. +That is exactly why the general rule matters: **a CLI that holds a lease +releases it explicitly before exiting**, by sending `session.release_control`, +because ADR 0033 binds early release to that call alone and treats every +transport loss — including a clean client exit — as a wait for expiry. On this +path the client releases, exits non-zero, and names `loopex resume --daemon` +as the remedy. Without that release it would strand the operator: the command +the refusal recommends begins by acquiring the same lease, and would refuse +`control_held` for the rest of the term. **Cursor, reconnection and re-acquisition.** The client remembers the last event cursor it emitted and, on transport loss, reconnects at it, @@ -642,7 +651,7 @@ repair, with the reason class on `stderr`. | `loopex run --daemon`, `loopex resume --daemon` and the create-and-drive sequence | `docs/operator/daemon.md`, driving section | | `loopex sessions --daemon`, `--limit`, `--after`, `--status`, `index_full` | `docs/operator/daemon.md`, listing section | | `loopex daemon` composition inputs, readiness record, signals, exit classes | `docs/operator/daemon.md`, running section | -| `loopex attach` roles, one-shot control, `--after`, renewal loss, `session_dormant` before any lease, explicit release on exit, reconnect and re-acquisition | `docs/operator/daemon.md`, attaching section | +| `loopex attach` roles, one-shot control, `--after`, renewal loss, `session_dormant` at attach, explicit release on every exit path, reconnect and re-acquisition | `docs/operator/daemon.md`, attaching section | ### Daemon Lifecycle and Orderly Shutdown @@ -663,10 +672,9 @@ non-zero with that step's reason class and touches nothing after it — in particular, a daemon that does not hold the marker never reads, unlinks or binds the socket path. -**The daemon composes its own supervision tree, and does not use -`LoopexComposition`'s bracket.** That is a decision this section has to make -before it can describe any shutdown, because the bracket makes the shutdown -this plan wants impossible. Two facts in the code say so: +**The daemon's top-level component is an owner process, not a supervisor.** +That is a decision this section has to make before it can describe any +shutdown, and three facts in the code force it. - `LoopexComposition.start_edge/2` runs inside a process `RuntimeOwner` **spawns** — `own_started/5` and `own_bracketed/6` are `spawn_monitor` bodies @@ -676,99 +684,74 @@ this plan wants impossible. Two facts in the code say so: `[:supervisor, :token]`: no composition function hands back the adapter pid. **A daemon using the bracket has no way to observe the Store's death and no pid to monitor.** -- Worse, it inverts the ordering. `Runtime.stop/1` is +- The bracket also inverts the ordering. `Runtime.stop/1` is `Supervisor.stop(supervisor, :normal)`, and the runtime supervisor is one of the owner's linked edges, so its exit arrives at the owner as `{:EXIT, _owned_pid, reason}` and the owner runs `cleanup/1` **immediately** — stopping every owned edge including the Store, and releasing the marker — - before the daemon has told a single client, unlinked the socket, or reached - told a single client or unlinked the socket. - -So `apps/loopex_daemon` supervises its own children directly, in start order: - -| # | Child | Started how | -| --- | --- | --- | -| 1 | The Store adapter | `Loopex.Store.Local.start_link/1` with the root and `recover_stale_writer: true` — the same call `LoopexComposition` makes through `start_edge/2` | -| 2 | The runtime | `Loopex.Runtime.start_link/1` with the store, model, executor, policy and tool configuration the daemon composed | -| 3 | The lease owner supervisor | The daemon's own, under ADR 0033 | -| 4 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | - -**The strategy is `rest_for_one` with `max_restarts: 0`**, and the second half -is what makes the failure rules in ADR 0032 and ADR 0033 true rather than -aspirational. - -`rest_for_one` expresses the dependency direction that is actually there: each -child depends on those started before it and on none started after. But by -itself it would *restart* — and every restart here is wrong. A Store that -terminated on an append error has a durable cause a restart cannot fix, and -restarting it would reacquire the marker only to fail again. A lease owner -that died lost the in-flight admission set, which is precisely what ADR 0033 -says must not be silently reconstructed. So the daemon supervisor carries -`max_restarts: 0`: **any child's failure exceeds the intensity immediately**, -the supervisor terminates its remaining children in reverse start order and -exits, and the daemon is fail-stop for every child uniformly. - -That one setting is what gives this section its shape. The Store's fail-stop -and the lease owner's daemon-fatal rule are the same mechanism seen twice, -not two special cases anyone has to implement separately. And reverse-start- -order termination — a property of every strategy, not only this one — is what -stops the Store last without a written sequence. - -`one_for_all` would also have been safe but says less: it would claim the -listener's failure must destroy the Store, which is not the dependency that -exists, and would make the tree harder to reason about when something is -added to it later. - -This buys exactly the two properties the bracket could not give: - -- **The daemon supervisor holds the Store's link**, so the adapter's exit - reason — the `{:stop, reason, …}` `Loopex.Store.Local` answers an append - error with — arrives at a process the daemon controls, carrying - `store_capacity_exceeded` or whatever the store's own reason was. -- **Reverse-start-order termination stops the Store last by construction.** A - supervisor terminates children in the reverse of their start order, so - listener, lease owner, runtime, Store — which is the ordered shutdown below, - obtained from the supervision strategy rather than from a sequence someone - has to remember to write. The runtime is terminated before it, as a sibling - in that order, so nothing the daemon does to end work can reach the Store - early. - -**What the daemon still takes from `loopex_composition`, and one seam that -needs a decision.** Owning the tree is about *lifetime*, not about wiring. -The daemon still needs everything that application assembles — the executor -with its workspace lease and coding tools, the artifact store, the resolved -policy, the runtime identity, the tool definitions — and duplicating that -would be a second copy of a wiring layer, which the minimalism budget forbids -on its face. - -The difficulty is that both public entry points, `start/1` and -`with_runtime/2`, bundle the wiring with the ownership: each goes through -`RuntimeOwner`, which is the bracket the daemon must not use. So one of two -things happens, and the maintainer should choose rather than have it decided -by whoever writes the code first: - -- **`loopex_composition` gains a narrow compose-without-owning entry point** - — the wiring it already performs, returning the started pieces to a caller - that supervises them — and the daemon calls that. This is a small addition - to a shared application, and it is a *different* change from the one - rejected below: it exposes wiring, not store death or adapter identity. -- **Or the daemon assembles those pieces itself** from the same public - building blocks the composition uses, accepting a second assembly site. - -This pair states the first as the preferred shape, because it keeps one -wiring layer, and marks it as the open implementation decision the daemon -workstream opens with. - -The rejected option is recorded: changing `LoopexComposition` to surface store -death and return the adapter pid. It is a host convenience application that -the app server uses and the daemon does not need — the daemon is a different -kind of host, one that must outlive its clients and own its own shutdown -ordering, and widening a shared helper to serve it would put daemon concerns -into an application whose other caller has none. **The two hosts therefore -compose differently, deliberately:** `LoopexAppServer.Host` keeps using -`with_runtime/2`, whose bracket is exactly right for a process that lives and -dies with one client's stdin, and the daemon supervises its own tree because -it does not. + before the daemon has told a single client or unlinked the socket. +- And an OTP `Supervisor` cannot serve here either, which an earlier draft of + this section got wrong. `Loopex.Runtime.start_link/1` returns + `{:ok, %Loopex.Runtime{}}` — a **struct**, not `{:ok, pid}` — so the runtime + is not a startable child at all; a supervisor rejects that return. Beyond + that, a supervisor offers no callback that can read a terminating child's + exit reason, so `store_lost`, `store_capacity_exceeded` and + `supervision_fault` would be indistinguishable at exactly the moment the + daemon must name one. + +So `apps/loopex_daemon` has one top-level process, `Loopex.Daemon.Owner`, a +`GenServer` that traps exits and holds the links itself — the same pattern +`RuntimeOwner` already uses, for the same reason. It starts and links four +things, in this order: + +| # | Child | Started how | What the owner keeps | +| --- | --- | --- | --- | +| 1 | The Store adapter | `Loopex.Store.Local.start_link/1` with the root and `recover_stale_writer: true` — the same call composition makes | The **pid**, so `{:EXIT, store_pid, reason}` identifies it and carries the store's own reason | +| 2 | The runtime | `Loopex.Runtime.start_link/1` | The `%Loopex.Runtime{}` **struct** — which is why this cannot be a supervisor child, and is fine for a process that simply holds it | +| 3 | The lease owner | The daemon's own, under ADR 0033 | Its pid | +| 4 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | Its pid | + +**There is no restart strategy, because there are no restarts.** Every child is +`start_link`ed by the owner, and the owner's `handle_info({:EXIT, pid, reason}, state)` +clause is the whole failure rule: any linked exit, whatever the reason, is +fatal to the daemon instance. That clause is also the **reader** the +fatal-class map needs — it matches the pid against the four it holds, +classifies `reason`, and has the class in hand before anything else happens. +Nothing here is `rest_for_one`, `one_for_all` or `max_restarts`; those words +belonged to the withdrawn design and are gone. + +The rejected option is recorded with its reasons, because it was tried in an +earlier draft of this pair and looked plausible: **a `Supervisor` with +`max_restarts: 0`**. It fails three ways. With intensity zero the restart +accounting runs before the strategy clause and the supervisor terminates with +reason `:shutdown`, so the child's real reason is logged and discarded — +exactly the information the daemon exists to report. It cannot host the +runtime at all, because of the struct return above. And its own termination +would leave the socket unlinked and no client told, so a fifth component +would have been needed to do the work steps 3 and 4 describe — which is the +owner, arrived at by a longer road. + +The second rejected option is the one this section opened with: changing +`LoopexComposition` to surface store death and return the adapter pid. It is +a host convenience application the app server uses and the daemon does not +need for *lifetime*; widening it for daemon concerns would put them into an +application whose other caller has none. **The two hosts compose differently, +deliberately**: `LoopexAppServer.Host` keeps `with_runtime/2`, whose bracket +suits a process that lives and dies with one client's stdin, and the daemon +owns its own because it does not. + +**Wiring is a separate question from lifetime, and M5 answers it.** The daemon +still needs everything `loopex_composition` assembles — the executor with its +workspace lease and coding tools, the artifact store, the resolved policy, the +runtime identity, the tool definitions. Duplicating that is not an option the +minimalism budget leaves open. So `loopex_composition` gains **one narrow +public function** that runs its existing edge-assembly sequence **in the +caller's process** and returns the started edges — the adapter pid, the +`%Loopex.Runtime{}` struct and the rest — instead of owning them. The daemon +owner calls it from inside its own trap-exit process, so every link lands on +the owner; `RuntimeOwner` calls the same function from its spawned process, so +`start/1` and `with_runtime/2` behave exactly as they do today. The Concept +file records this as a design decision; this file explains it. There are **two** ways a daemon ends, and conflating them was a defect. A daemon-initiated shutdown is the ordered sequence below. A **store loss is a @@ -779,68 +762,53 @@ than in taste: `Loopex.Store.Local` answers an append error with observes it, the store is gone and the marker is already released. A sequence that ends "then stop the Store" cannot run when the Store is what died. -**Daemon-initiated shutdown is the tree terminating, in reverse start order.** -`SIGTERM` or `SIGINT` asks the daemon supervisor to terminate. It is not a -sequence anyone writes: a supervisor terminates children in the reverse of -their start order, so listener, lease owner, runtime, Store falls out of the -tree above, and each child's own `shutdown` value bounds its part. An ordered -termination is also not a child failure, so it does not trip `max_restarts: -0` — that setting governs a child dying on its own, which is the fail-stop -path below. - -1. **The listener terminates first.** It stops accepting, so a new connection - is refused rather than queued; it sends each open connection one +**Daemon-initiated shutdown is the owner stopping its children, in reverse +order.** `SIGTERM` or `SIGINT` reaches the owner, which performs these four +steps itself. They are the owner's code, not a supervisor's behaviour, which +is what lets each one carry a reason and lets step 3 use a bound the owner +chooses. + +1. **The listener stops first.** It stops accepting, so a new connection is + refused rather than queued; it writes each open connection one `daemon.stopping` naming `operator_stop`, bounded best-effort as ADR 0032 fixes — one write attempt into the existing 4 MiB output buffer — and closes it. Clients therefore learn *first*, before anything else is torn down, which is the right order for the one party that cannot see inside the daemon. -2. **The lease owner terminates.** Every lease vanishes with it. Nothing - durable is involved, and no client is left holding one, because no - connection survived step 1. -3. **The runtime terminates, and this is where admitted work ends.** The - daemon gives the runtime child a `shutdown` value of the **composed cleanup - grace** — the same value the sessions were composed with, so no number is - introduced. Work that settles within it settles normally. Work that does - not is ended when the supervisor's shutdown timeout elapses and it kills - the child, which is **crash-equivalent by definition**: no terminal - mutation is claimed, no `cancelled`, no `outcome_unknown`, no abort record. - A mutation whose commit was ambiguous stays `commit_unknown` and fenced, - and the reconciliation ADR 0006 and ADR 0018 already define settles it at - the next activation — exactly as after an abrupt death. - - **This is why the daemon sets that value rather than trusting the - runtime's own.** The runtime's internal teardown is bounded only - transitively: core declares `shutdown: 5_000` for a session coordinator but - `shutdown: :infinity` for an owner group — whose `terminate/2` itself calls - `Supervisor.stop(workers, :shutdown, :infinity)` — and three of the runtime - supervisor's children are supervisors, which default to `:infinity`. "5,000 - ms for a coordinator" is not the bound of anything. A `shutdown` value on - the daemon's own child spec is a bound the daemon owns, and it ends in a - kill, which is the property this step wants rather than a compromise of it. - - An earlier draft had the daemon call `Runtime.stop/1` explicitly and then - kill the supervisor pid on a timer. That is withdrawn: with - `max_restarts: 0` an explicit kill of a supervised child would itself - exceed the intensity and tear the tree down from under the remaining - steps. Expressing the same bound as the child's `shutdown` value obtains - it without that contradiction. - - Also withdrawn, from an earlier draft: that running effects enter the - configured cancellation sequence. Cancellation is the coordinator's to run - as part of a session's own durable command, not something a daemon may - drive from outside, and a daemon-side cancellation path is precisely the - second loop this milestone forbids. Two alternatives were rejected with it. - Host-authorized durable aborts — the daemon admitting an abort per session - on the way down — would have the daemon issuing mutations on nobody's - authority, at the moment it is least able to see them through. An unbounded - natural drain would make `SIGTERM` unbounded, which is not a stop. -4. **The Store terminates last**, and its `terminate/2` releases the writer - marker — see the marker invariant in ADR 0031. Stopping it last is what - makes the marker outlive every session operation that might still have - needed it, and it is obtained from the start order rather than from a step - someone has to remember. -5. **The socket path is unlinked** and the daemon **exits `0`**. +2. **The lease owner stops.** Every lease vanishes with it. Nothing durable is + involved, and no client is left holding one, because no connection survived + step 1. +3. **The runtime stops, and this is where admitted work ends.** The owner + calls `Loopex.Runtime.stop/1` on the struct it kept, under its own bound: + the **composed cleanup grace**, the same value the sessions were composed + with, so no number is introduced. Work that settles within it settles + normally. If the call has not returned when the grace elapses, the owner + kills the runtime supervisor outright — `Process.exit(runtime.supervisor, + :kill)`, the pid the struct exposes — which is **crash-equivalent by + definition**: no terminal mutation is claimed, no `cancelled`, no + `outcome_unknown`, no abort record. A mutation whose commit was ambiguous + stays `commit_unknown` and fenced, and the reconciliation ADR 0006 and + ADR 0018 already define settles it at the next activation — exactly as + after an abrupt death. + + The owner can do this precisely *because* it is not a supervisor: there is + no restart intensity for a deliberate kill to trip, and the exit it causes + arrives at its own `{:EXIT, …}` clause, which knows this teardown is in + progress and does not re-enter the fail-stop path. + + **The daemon supplies that bound rather than trusting the runtime's own, + which is not one.** Core declares `shutdown: 5_000` for a session + coordinator but `shutdown: :infinity` for an owner group — whose + `terminate/2` itself calls `Supervisor.stop(workers, :shutdown, + :infinity)` — and three of the runtime supervisor's children are + supervisors, which default to `:infinity`. `Supervisor.stop/3` takes an + `:infinity` call timeout by default. "5,000 ms for a coordinator" is not + the bound of anything, and an earlier draft that claimed it was is + withdrawn. +4. **The Store stops last**, and its `terminate/2` releases the writer marker + — see the marker invariant in ADR 0031. Stopping it last is what makes the + marker outlive every session operation that might still have needed it. + Then the socket path is unlinked and the owner **exits `0`**. One ordering consequence is worth stating because it reverses an earlier draft: clients are told *before* work is drained, not after. That is @@ -848,14 +816,23 @@ deliberate. The drain does not need connections to exist, and a client that must reconnect elsewhere is better served by learning immediately than by waiting out a cleanup grace it cannot see. -**Store loss, a fail-stop path.** The daemon supervisor is the Store adapter's -parent, so the adapter's termination is reported to it with the adapter's own -exit reason — that is the whole observation mechanism, and it needs no link -the daemon does not already hold and no monitor it has to remember to set. -Under `rest_for_one` the Store is child 1, so its failure takes the runtime, -the lease owner and the listener with it, which is the refusal-of-service this -path wants. The daemon reads the reason to classify the exit and then, without -the ordered sequence: +**Cancellation is not the daemon's to run**, which an earlier draft claimed. +It is the coordinator's, as part of a session's own durable command, and a +daemon-side cancellation path is precisely the second loop this milestone +forbids. Two alternatives were rejected with it. Host-authorized durable +aborts — the daemon admitting an abort per session on the way down — would +have the daemon issuing mutations on nobody's authority, at the moment it is +least able to see them through. An unbounded natural drain would make +`SIGTERM` unbounded, which is not a stop. + +**Store loss, a fail-stop path.** The owner holds the Store's link and its +pid, so the adapter's termination arrives as `{:EXIT, store_pid, reason}` at +the owner's own clause, carrying the store's real reason. That clause is the +fatal-class map's reader: it matches the pid, classifies `reason` as +`store_capacity_exceeded` where that was the store's own refusal and +`store_lost` otherwise, and has the class in hand before it does anything +else. No link the owner does not already hold, no monitor to remember, and no +information lost on the way. Then, without the ordered sequence: 1. Refuse service immediately — no further admission, no further attach, and the listener closed. @@ -866,9 +843,9 @@ the ordered sequence: 4. Exit non-zero with that class on `stderr`. **There is no "stop the Store" step**, because the Store already stopped and the marker is already released; the next daemon finds no marker to recover rather than a stale - one. Nothing restarts the Store: the daemon supervisor's `max_restarts: 0` - makes this failure fatal to the tree rather than a restart, which is why - this path exists at all. + one. Nothing restarts the Store: the owner start_links its children and + restarts none of them, so any linked exit is fatal by its own clause — + which is why this path exists at all rather than being a restart. Nothing durable is at risk in that ordering: whatever was ambiguous is `commit_unknown` in the journal and is reconciled at the next activation, and @@ -959,18 +936,18 @@ plan names as new. It is the thing to check a change against. | Boundary | Owner | What fails | Who observes it, and how | What the client sees | Durable / not durable | | --- | --- | --- | --- | --- | --- | -| **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the **daemon supervisor** owns the Store process as child 1 | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:166`). Its parent is the daemon supervisor, so the exit reason is reported there — no link the daemon must arrange and no monitor it must remember. Under `rest_for_one` the failure also takes children 2 to 4 | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | +| **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the **daemon owner process** holds the Store's link and pid | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:166`). The owner's `{:EXIT, store_pid, reason}` clause receives it **with the store's real reason**, which is what distinguishes `store_capacity_exceeded` from `store_lost` | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | | **Store ↔ daemon (startup)** | The adapter | Marker held, unverifiable, log too large | `WriterLock.acquire` refuses with `store_writer_active` / `store_writer_unverifiable`; `Log.open` refuses `store_log_too_large` (`log.ex:80-84`) | Nothing — no socket exists yet | **Not durable:** nothing was written. Reverse cleanup leaves no marker | | **Core ↔ daemon: existence query** | `loopex` answers; the daemon asks | Root unreadable, malformed ID, unrecognised answer | The query's own closed result set — `present`, `absent`, `invalid_id`, `store_unavailable`, `unexpected` (this plan's new core operation) | The matching refusal, four of them distinct; nothing created, nothing attached, no lease | **Not durable:** the query writes nothing, proved by a byte-identical root | | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The daemon supervisor, where the lease owner is child 3: `max_restarts: 0` makes the failure exceed intensity at once, so the supervisor terminates the tree in reverse start order and exits — ADR 0033's daemon-fatal rule, obtained from the supervision setting rather than from special-case code | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause, which treats any linked exit as fatal — ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The daemon supervisor terminates; reverse start order gives listener, lease owner, runtime, Store, and the runtime child's `shutdown` value — the composed cleanup grace — bounds the drain and ends in a kill | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The owner stops its children in reverse order itself — listener, lease owner, runtime, Store — calling `Runtime.stop/1` under the composed cleanup grace and killing `runtime.supervisor` on expiry | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | `terminate/2` in an orderly stop; `terminate/2` early on store loss; nothing on a kill | Nothing directly; the next daemon's start succeeds, succeeds, or recovers | **Not durable in the journal sense:** the marker is exclusion, not truth | @@ -995,7 +972,10 @@ Concept: [Scope](M5.md#concept-plan-scope). The smallest sufficient system wins, and each addition below names what it unifies and why direct code is insufficient. One application, because a -daemon is a host and a host is an application. One socket listener, one narrow +daemon is a host and a host is an application. One daemon owner process, one new public composition function — which unifies +the two callers that need the edges assembled, `RuntimeOwner` and the daemon's +owner, and which direct code cannot replace because the alternative is a +second copy of the whole wiring layer. One socket listener, one narrow core concurrent-attachment change, one read-only core existence query — which unifies the three daemon paths that must know whether an ID exists before doing anything with it (acquire, activation of a session the index does not diff --git a/docs/plans/M5.md b/docs/plans/M5.md index b9379664e..e2937a2ca 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -443,6 +443,34 @@ implementation that depends on it, not before unrelated work. | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is named by an opaque token bound at composition and **resolved per invocation**, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | +**Two design decisions are settled here rather than in an ADR**, because both +are internal structure that no public or durable contract depends on. They are +recorded because getting either wrong would be expensive to discover later. + +**The daemon owns its own lifetime, through an owner process rather than a +supervisor.** Its top-level component is one `GenServer` that traps exits and +`start_link`s four things — the Store adapter, the runtime, the lease owner, +the listener — keeping the Store's pid and the runtime's struct. Any linked +exit is fatal, by that process's own clause, and that clause is what reads a +dying Store's reason and turns it into the class the daemon reports. It is not +an OTP `Supervisor`: a supervisor offers no callback that can read a child's +exit reason, so `store_lost` and `store_capacity_exceeded` would be +indistinguishable, and `Loopex.Runtime.start_link/1` returns a struct rather +than `{:ok, pid}`, so the runtime is not a startable child at all. The +rejected alternative — a supervisor with zero restart intensity — is recorded +in the companion with all three reasons it fails. + +**`loopex_composition` gains one narrow public function**, which assembles the +edges it already assembles but **in the caller's process**, returning them +instead of owning them. The daemon's owner calls it from inside its own +trap-exit process, so every link lands where the daemon can act on it, and +`RuntimeOwner` calls the same function from its spawned process so `start/1` +and `with_runtime/2` are unchanged. The rejected alternative is the daemon +assembling the executor, artifact store, policy, runtime identity and tools +for itself: a second copy of a wiring layer, which the minimalism budget +rules out on its face. One function is the smaller change, and it unifies two +callers rather than adding a layer for one. + Three accepted decisions remain load-bearing, are not reopened, and are left **Accepted and unchanged** by everything M5 does: M4's ADR 0023 fixes the protocol M5's generation 2 extends; M4's ADR 0030 fixes the closed telemetry From eb06768aabd90301b6239c52a98650ced9f85aa0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:07:44 -0700 Subject: [PATCH 055/585] plan(M5): fix what my adversarial pass found in the owner rewrite Five findings against this round's own diff. AP2/AP6: the permitted credential-bearing transfer still carried {:ok, bytes} while N1's shape binding requires {:ok, %{credential: bytes}} -- the one place the keyed shape had to hold was still bare. Fixed, and both malformed-reply rows now refuse a bare binary explicitly, with the reason: accepting it would carry bytes in the shape the redaction pass leaves verbatim below 65 bytes. AP4: ADR 0031 still said the daemon supervises the adapter "as the first child of its own supervisor". Replaced with the owner start_linking it and keeping the pid, and the sentence now says why a supervisor would not do -- it reports no child's exit reason to any callback. AP7: the fatal-class map had no stated reader. It now names the owner's {:EXIT, pid, reason} clause as the single place a class is decided. AP3: reverse cleanup was written as if a supervisor performed it. The owner does it in its own start path, and the text says why that matters: a crashing owner would drop the links without unlinking the socket file, which no exit signal removes. AP9, the one that was a real gap rather than residue: lazy recovery listed attach and acquire as activating a session but never said what session.create does. Creation starts a coordinator, so it counts as an activation against the ceiling -- a ceiling counting resumes but not creations would bound the wrong thing. Acquire and attach are stated as not activating, which is what makes the CLI's resume form necessary. The boundary table's closing note now states the standard the table holds itself to, since its Store row has been written wrong twice for the same reason: every observer cell names a process the daemon itself links, with the clause that receives the exit, or a mechanism inside core with a line number. --- ...store-selection-and-migration-technical.md | 9 +++-- ...tachment-residency-and-replay-technical.md | 13 +++++++- ...andoff-over-bootstrap-channel-technical.md | 7 ++-- docs/plans/M5-technical.md | 33 ++++++++++++------- 4 files changed, 43 insertions(+), 19 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 8c6799b6b..8f1bfc652 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -30,9 +30,12 @@ control.** This adapter answers an append error with released **before** the daemon can react, and any sequence ending "then stop the Store" is unrunnable, because the Store is what died. The daemon's only correct response is a fail-stop, and it arranges to be able to make it: the -daemon supervises the adapter **directly**, as the first child of its own -supervisor, so the adapter's termination and its exit reason are reported to -a process the daemon controls. It does not compose through +daemon **start_links the adapter itself**, from an owner process that traps +exits and keeps the adapter's pid, so the termination arrives as +`{:EXIT, store_pid, reason}` at a clause the daemon wrote — carrying the +store's own reason, which is what separates `store_capacity_exceeded` from +`store_lost`. An OTP supervisor would not do: it reports no child's exit +reason to any callback. It does not compose through `LoopexComposition`, whose `start_edge/2` takes the `start_link` inside a process `RuntimeOwner` spawns and which returns no adapter pid — a daemon on that bracket could not observe this failure at all. On the reported exit it diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 16b1ec6af..6cb71cf19 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -462,7 +462,18 @@ be a second core change this milestone does not make. is unaffected. - **Lazy recovery.** A restarted daemon activates no session. It acquires the writer marker, reads the index, binds the socket, and activates a session - the first time a client attaches to, acquires control of or resumes it. + when a client first reaches it — by `session.resume`, or by `session.create`, + which starts a coordinator for a session that did not exist before. + **Creation counts as an activation** against the ceiling below, because it + costs exactly what any other activation costs: a live coordinator the daemon + holds for its lifetime. A ceiling that counted resumes but not creations + would be a ceiling on the wrong thing. + + `session.acquire_control` and `session.attach` do **not** activate. Acquire + is a lease over a session that durably exists, validated by the existence + query, and attach is refused with `session_dormant` against a session this + lifetime has not activated — which is exactly why the CLI's `resume` form + exists and why `attach` alone cannot start work. - **Activation ceiling.** At most 64 sessions are activated **per daemon lifetime**, not at once, because nothing gives a slot back. The 65th activation refuses with a stable reason naming the ceiling and the remedy, diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 3660d11f3..953361bf8 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -206,7 +206,8 @@ boundary, not an absolute: - The **only** permitted credential-bearing transfer in the parent is the custody process's reply to the sender's `resolve` call, carrying - `{:ok, bytes}` to the one sender process that asked. It is bounded by the + `{:ok, %{credential: bytes}}` — **keyed**, for the redaction reason below — + to the one sender process that asked. It is bounded by the same 1..65,536-byte rule as the frame, it is never logged, never forwarded, and never held after the frame is written. The registry lookup that precedes it carries no credential, so the token's journey through the registry adds @@ -355,7 +356,7 @@ produced, and nothing else is accepted. | `:missing` | A custody process | It has no credential for this token | | `:expired` | A custody process | It has one and considers it no longer valid | | `:oversized` | The sender | A successful reply whose bytes fall outside 1 to 65,536 | -| `:unavailable` | The registry or a custody process | A missing registry row, a gone registry, a dead custody process, a custody process that answers `:unavailable`, or **a successful reply that is malformed** — not a binary, or a shape the sender does not recognise — because a reply it cannot read is not a credential it can send | +| `:unavailable` | The registry or a custody process | A missing registry row, a gone registry, a dead custody process, a custody process that answers `:unavailable`, or **a successful reply that is malformed** — not `{:ok, %{credential: binary}}`, including a bare binary where the keyed map is required — because a reply the sender cannot read, or reads in a shape the redaction pass does not protect, is not a credential it can send | | `:timeout` | The guardian | Resolution had not completed when the invocation deadline was reached | An earlier draft left the first two unnamed and folded a malformed successful @@ -389,7 +390,7 @@ leaves no retained copy of anything the resolver may have produced: | --- | --- | | No `:credential_token` in the configuration | `:no_token`, refused before the namespace is created and before any child is spawned | | Malformed token — outside the identifier alphabet or over 256 bytes | `:invalid_token`, refused before any lookup and before any child is spawned | -| A successful custody reply that is malformed — not a binary, or a shape the sender does not recognise | `:unavailable`; a reply the sender cannot read is not a credential it can send | +| A successful custody reply that is malformed — not `{:ok, %{credential: binary}}`, a bare binary included | `:unavailable`; a bare binary is refused rather than accepted, because accepting it would carry bytes in a shape the redaction pass leaves verbatim below 65 bytes | | The registry holds no row for the token, the registry is gone, or the custody process is dead | `:unavailable`. The host recomposes; nothing is reconstructed, because the registry holds no bytes to reconstruct from | | Custody answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | | Custody answers `{:error, :unavailable}`, or anything outside the closed set | The same path, reported as `:unavailable` | diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 92ea717c3..c04fee6f9 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -857,7 +857,7 @@ not hold was ever promised, the marker left behind is reclaimed by the next daemon's verified stale-writer recovery, and the socket file is a stale path the next marker holder removes. -**The fatal-class map.** Every non-zero exit names one class on `stderr`: +**The fatal-class map.** Every non-zero exit names one class on `stderr`. Its **reader is the owner's `{:EXIT, pid, reason}` clause**, which matches the pid against the four it holds and classifies the reason; there is one place in the daemon where a class is decided, and this is it: | Class | When | | --- | --- | @@ -881,10 +881,13 @@ has no diagnostic surface of its own beyond these lines and the records it already sends on the wire, and the fatal-class map above is the whole vocabulary of what an exit may say. -**Reverse cleanup.** Every startup failure *after* the marker is acquired -unwinds what it has done, in reverse: an unlinked-and-bound socket is closed -and its path unlinked, a created `daemon/` subdirectory it made is removed, -and the Store is stopped so its `terminate/2` releases the marker. A daemon +**Reverse cleanup.** Startup happens inside the owner, so a failure at any +step unwinds what that step and its predecessors did, in reverse: a bound +socket is closed and its path unlinked, a `daemon/` subdirectory the owner +created is removed, and the Store is stopped so its `terminate/2` releases the +marker. The owner does this in its own start path rather than leaving it to a +crash, because a crashing owner would take the links down without unlinking +the socket file, which no exit signal removes. A daemon that refuses to start leaves no marker and no socket file behind, which is what lets an operator fix the cause and try again without a recovery step. @@ -956,14 +959,20 @@ Three rows deserve their reading stated, because they are where earlier drafts went wrong. The **coordinator death** row is the one that forced `residency` to mean a daemon fact: there is no observer column entry available, so any design that needed one was unimplementable. The **Store ↔ daemon** row is the -one that forced the fail-stop split: the marker is already released by the +one that forced the fail-stop split — the marker is already released by the time anything can act, so an ordered shutdown ending "stop the Store" had -nothing to stop. And that same row is why the daemon supervises its own tree: -an earlier draft filled its observer column with a link and a monitor the -daemon could not actually hold, because `LoopexComposition` takes the link in -a process it spawns and returns no adapter pid. Every observer cell in this -table is now a parent-child relationship the daemon itself establishes, or a -mechanism inside core with a line number, and nothing in between. +nothing to stop — and it is also the row that has now been written wrong +twice. The first draft filled its observer column with a link and a monitor +the daemon could not hold, because `LoopexComposition` takes the link in a +process it spawns and returns no adapter pid. The second put a `Supervisor` +there, which cannot report a child's exit reason at all and cannot host the +runtime's struct return. Both failures were the same mistake: naming an +observer without checking that something could observe. + +So the standard this table holds itself to is now explicit. **Every observer +cell names either a process the daemon itself links, with the clause that +receives the exit, or a mechanism inside core with a line number.** A cell +that can name neither is a boundary the plan has not finished. ### Proportional Minimalism Budget From fa80a1a1e1cece8df1595aca8e553035f1a7a00f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:19:46 -0700 Subject: [PATCH 056/585] plan(M5): bound the runtime stop truthfully and link all seven Review findings R1 through R8, with the OTP semantics read from the installed stdlib rather than assumed. R1. Runtime.stop/1 is arity one and uses the default :infinity (runtime.ex:115-121), so it cannot carry the owner's bound. The owner calls Supervisor.stop(runtime_supervisor, :normal, grace) instead. What a timeout does, read at the floor toolchain: Supervisor.stop/3 reaches gen:stop/3, which is proc_lib:stop/3 (gen.erl:560-563); that function monitors the target, calls sys:terminate/3, and on expiry -- from sys:terminate raising exit:{timeout, {sys, terminate, _}} or from its own after RemainingTimeout -- demonitors and calls exit(timeout) (proc_lib.erl:1575-1604). Two consequences are now stated: the target is NOT killed, so the owner's kill is the only thing that ends the tree; and the exit lands on the CALLER, so the call runs under try/catch :exit or the owner dies of timeout and never reaches step 4. try/catch is the simpler form precisely because the caller is what exits. The owner traps exits, so signals arriving while it is blocked queue rather than being lost -- deferred, not dropped. One correction to the finding: runtime.ex:46 declares the struct @opaque, so the daemon reaching into runtime.supervisor would violate opacity across applications. The composition function returns the runtime supervisor pid alongside the struct instead; composition already holds it. R2. "Crash-equivalent by definition" was true of coordinators and false of the owner-group subtree: OwnerGroup traps (owner_group.ex:50), carries shutdown: :infinity (:17) and a terminate/2 calling Supervisor.stop(workers, :shutdown, :infinity) (:87), and three of the root's seven children are supervisors. Stated honestly now: the bound is on the call RETURNING; non-trapping descendants die at once while trapping ones unwind on their own clock and the daemon does not wait; the surviving claim is about the JOURNAL, not about every process being gone. The marker claim is weakened to "every operation the owner can end", with an orphan meeting a stopped Store getting the refusal it would get after a VM death -- never a write. Enumerate-and-kill is recorded as rejected: no API walks a subtree without racing its teardown. The Store traps exits (local.ex:150), so an owner crash still runs its terminate/2 and returns the marker; the plan says it relies on that. R3. The composition function runs the start_edge chain in the caller's process, so the owner links seven, not four: Store.Local (:171), Loopex root (:177), Transfers (:260, optional), WorkspaceLease (:283), executor Local (:289), plus lease owner and listener. The function returns every pid it linked; the table lists all seven; the EXIT clause maps pid to component; and the fatal-class map gains one class per component -- runtime_lost, transfers_lost, workspace_lease_lost, executor_lost, listener_lost beside the store and lease-owner classes -- each a fatal: on the wire, with ADR 0032's reason set and the vector list updated. The executor traps exits (executor.ex:2603), stated as contract. R4. Attach consulted "the residency index", which at the 4,096 ceiling would refuse session_dormant for a session that is demonstrably active, making the recorded-entry bound a bound on reachability. Attach now consults the per-lifetime ACTIVATION SET -- the structure the 64-activation counter already needs -- and both files say which structure answers which question. R5. "Creation counts as an activation" reaches ADR 0032's Concept and M5.md's limitation text, with the witness: a fresh create raises the count by one, and at the ceiling a create is refused activation_ceiling_reached. R6. ADR 0034's concurrency witness and its matching prose are re-pointed at the two-runtime case, with within-one-runtime independence as a corollary. R7. Both Concept files said a session activates "when a client reaches for it", contradicting the rule that acquire and attach do not activate. R8. ADR 0034 now says the contract rests on the shape rather than on @identity_bytes or @credential_pattern, which live in apps/loopex and nothing here pins -- and that the one-byte witness is what pins the property. --- ...store-selection-and-migration-technical.md | 24 +- ...tachment-residency-and-replay-technical.md | 2 +- ...-daemon-attachment-residency-and-replay.md | 7 +- ...andoff-over-bootstrap-channel-technical.md | 17 +- docs/plans/M5-technical.md | 230 +++++++++++++----- docs/plans/M5.md | 16 +- 6 files changed, 216 insertions(+), 80 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 8f1bfc652..35a1873b2 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -18,10 +18,26 @@ hold the marker itself and cannot release it itself: `Loopex.Store.Local` takes it at start and releases it in its own `terminate/2`. What the daemon owns is the Store *process*. It starts it before the socket is bound and, in a **daemon-initiated** shutdown, stops it last — after the listener is closed, -every connection is closed and the socket is unlinked — so the marker is held -for as long as any session operation could still need it and is released by -that `terminate/2` at the moment the daemon stops the Store. That ordering is -the whole mechanism; it is fixed in the M5 plan's lifecycle section. +every connection is closed and the runtime is stopped — so the marker is held +for as long as any operation **the daemon can end** could still need it, and +is released by that `terminate/2` at the moment the daemon stops the Store. +That ordering is the whole mechanism; it is fixed in the M5 plan's lifecycle +section. + +The qualification is deliberate and is the strongest true form. Where the +runtime does not stop within its grace the daemon kills its supervisor, and a +*trapping* descendant — an owner group, or a trapping worker beneath one — +may still be unwinding when the Store goes. Such an orphan meets a stopped +Store and gets the same refusal it would get after a VM death: it cannot +write, because there is nothing left to write to. So the marker is never held +open by a straggler, and no straggler appends behind the daemon's back; what +the daemon does not promise is that every process has finished before it +exits. + +The adapter also **traps exits**, which this arrangement relies on: an owner +that crashes rather than stopping still runs the Store's `terminate/2`, so the +marker comes back. Only a kill or a power loss leaves it, which is what the +next daemon's verified stale-writer recovery is for. **Store loss inverts it, and the daemon cannot order what it does not control.** This adapter answers an append error with diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 6cb71cf19..0200dff4c 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -156,7 +156,7 @@ which no client requests and every client may receive: | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining fatal classes the plan's map names — `fatal:supervision_fault` being the one a running daemon can reach | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:supervision_fault`, `fatal:listener_lost`. The startup classes carry no reason, because no socket exists when they occur | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index cd797f336..f14a23bc8 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -104,7 +104,12 @@ A session is *active* when **this daemon activated it in this lifetime** and *dormant* when the root records it and this daemon has not. Both are daemon facts, true by construction; neither is a claim about a live coordinator, which the daemon has no way to know. Recovery is lazy: a restarted daemon activates nothing, -reads its index, and activates a session when a client reaches for it. +reads its index, and activates a session when a client creates or resumes it. +Creating a session activates it, so `session.create` spends one of the +activations the ceiling counts — a created session has a coordinator like any +other, and a ceiling that counted resumes but not creations would bound the +wrong thing. Acquiring control and attaching do not activate. + Activation is one-way: dormancy applies to attachments, resident windows and output buffers, never to a coordinator, because a session with no attachment may still have a model request, a tool effect, an interaction, a recovery, an diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 953361bf8..5dac45537 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -95,8 +95,10 @@ different handles to different custody processes** — the isolation proof this pair requires. It is not global, because nothing looks it up by name. And it holds **no bytes at any time**: it is an identifier whose resolution is a call to a process the host owns. The property that made the environment variable -wrong — concurrent invocations in one VM unable to carry distinct credentials -— is exactly the property this arrangement restores. +wrong — concurrent work in one VM unable to carry distinct credentials — is +exactly the property this arrangement restores, now at the granularity that +matters: two *runtimes* in one VM carry different credentials, where the +environment variable gave them one slot between them. Nothing carries `options` into a durable or observable plane, which is worth confirming rather than assuming: the model span is built from a fixed identity @@ -517,9 +519,14 @@ Three proofs are new: "During" is observed from inside the call, at the point the child reports readiness. The case composes the runtime the way a reference host does, with the variable set, and asserts that composition returns having deleted it. -- **Concurrent independence.** Two invocations with distinct credentials run - at once and each child records only its own; neither child, nor either - child's diagnostics, ever sees the other's. +- **Independence across runtimes.** Two runtimes composed in one VM, each + with its own registry, custody and token, run invocations at once; each + child records only its own credential, and neither child — nor either + child's diagnostics — ever sees the other's. It is stated across *runtimes* + rather than across invocations because a composition-bound token makes the + within-one-runtime form vacuous: two invocations of one runtime necessarily + carry the same token. Their independence is a corollary of this case, not a + separate witness. - **No credential environment read in the adapter's lib tree.** The existing drift-protection case in `apps/loopex_llm_reqllm/test/adapter_test.exs` — `the adapter reads exactly one credential environment variable` — pins the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index c04fee6f9..441785656 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,8 +130,8 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, every client given one bounded best-effort `daemon.stopping` naming `operator_stop`, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with its stable reason and the restart remedy, and the count starts again after a restart because it counts per lifetime; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded` and `fatal:supervision_fault` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, every client given one bounded best-effort `daemon.stopping` naming `operator_stop`, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `supervision_fault`, `listener_lost`) — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease releasing it explicitly on every exit path; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -608,10 +608,22 @@ to resume" from "acquiring to attach" would need a new field — a new input to the generation-2 schema digest, added to make a client-side convenience expressible. -So the daemon's **attach** handler is where it belongs. That handler consults -the daemon's own residency index — a daemon fact the daemon owns, needing -nothing from core — and refuses `session_dormant` for a session this lifetime -has not activated. `loopex resume --daemon` is unaffected: it acquires, +So the daemon's **attach** handler is where it belongs — and it consults the +right structure, which is not the listing index. Two daemon-owned structures +answer two different questions, and conflating them would make the index +ceiling bound reachability: + +| Structure | Question it answers | Bounded? | +| --- | --- | --- | +| The **activation set** | Has this daemon activated this session ID in this lifetime? | By the 64-activation ceiling it already counts — it *is* that counter's backing set | +| The **listing index** | What sessions does this root record, for `session.list`? | By the 4,096 recorded-entry ceiling | + +Attach consults the **activation set**. That matters because at the index +ceiling a session reached by ID is activated and deliberately *not* recorded: +consulting the index would refuse `session_dormant` for a session that is +demonstrably active, and the recorded-entry bound — which this plan says is +never a bound on reachability — would become exactly that. The activation set +has no such gap, because a session cannot be activated without entering it. `loopex resume --daemon` is unaffected: it acquires, resumes, and only then attaches, by which time the session is active. `loopex attach --take-over` against a dormant session therefore acquires @@ -701,24 +713,50 @@ shutdown, and three facts in the code force it. So `apps/loopex_daemon` has one top-level process, `Loopex.Daemon.Owner`, a `GenServer` that traps exits and holds the links itself — the same pattern -`RuntimeOwner` already uses, for the same reason. It starts and links four -things, in this order: +`RuntimeOwner` already uses, for the same reason. + +**It links seven processes, not four.** An earlier draft of this section said +four, having counted the components the daemon *thinks* about rather than the +processes composition actually starts. Because the new composition function +runs the edge-assembly chain in the caller's process, every `start_edge/2` in +that chain links the owner — five of them — and the daemon adds two of its +own: -| # | Child | Started how | What the owner keeps | +| # | Linked process | Where it comes from | Optional? | | --- | --- | --- | --- | -| 1 | The Store adapter | `Loopex.Store.Local.start_link/1` with the root and `recover_stale_writer: true` — the same call composition makes | The **pid**, so `{:EXIT, store_pid, reason}` identifies it and carries the store's own reason | -| 2 | The runtime | `Loopex.Runtime.start_link/1` | The `%Loopex.Runtime{}` **struct** — which is why this cannot be a supervisor child, and is fine for a process that simply holds it | -| 3 | The lease owner | The daemon's own, under ADR 0033 | Its pid | -| 4 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | Its pid | - -**There is no restart strategy, because there are no restarts.** Every child is -`start_link`ed by the owner, and the owner's `handle_info({:EXIT, pid, reason}, state)` -clause is the whole failure rule: any linked exit, whatever the reason, is -fatal to the daemon instance. That clause is also the **reader** the -fatal-class map needs — it matches the pid against the four it holds, -classifies `reason`, and has the class in hand before anything else happens. -Nothing here is `rest_for_one`, `one_for_all` or `max_restarts`; those words -belonged to the withdrawn design and are gone. +| 1 | The Store adapter | `start_edge(Store.Local, …)` | no | +| 2 | The runtime root | `start_edge(Loopex, …)` | no | +| 3 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | +| 4 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | +| 5 | The local executor | `start_edge(Local, …)` | no | +| 6 | The lease owner | The daemon's own, under ADR 0033 | no | +| 7 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | + +The composition function therefore returns **every pid it linked**, not only +the ones the daemon names in prose: a map carrying `store`, `runtime` (the +`%Loopex.Runtime{}` struct), `runtime_supervisor`, `transfers` (absent when +disabled), `workspace_lease` and `executor`. Returning the runtime supervisor +pid separately matters: `%Loopex.Runtime{}`'s type is declared `@opaque`, so +the daemon reaching into its `supervisor` field would be an opacity violation +across applications. Composition already holds that pid, so handing it over +costs nothing and keeps the daemon out of another application's internals. + +**There is no restart strategy, because there are no restarts.** Every one of +the seven is `start_link`ed by the owner, and the owner's +`handle_info({:EXIT, pid, reason}, state)` clause is the whole failure rule: +any linked exit, whatever the reason, is fatal to the daemon instance. That +clause is also the **reader** the fatal-class map needs — it matches the pid +against the seven it holds, maps it to a component, classifies `reason`, and +has the class in hand before anything else happens. Nothing here is +`rest_for_one`, `one_for_all` or `max_restarts`; those words belonged to the +withdrawn design and are gone. + +Two of the seven trap exits, and the plan states that as contract rather than +relying on it as luck: the **Store adapter** traps, so an owner that crashes +still runs its `terminate/2` and returns the marker; the **local executor** +traps, so an owner exit lets it complete its own cleanup rather than leaving +OS effects behind. Neither is a property M5 adds; both are properties M5 +depends on, and a change to either is a change to this plan. The rejected option is recorded with its reasons, because it was tried in an earlier draft of this pair and looked plausible: **a `Supervisor` with @@ -779,36 +817,84 @@ chooses. involved, and no client is left holding one, because no connection survived step 1. 3. **The runtime stops, and this is where admitted work ends.** The owner - calls `Loopex.Runtime.stop/1` on the struct it kept, under its own bound: - the **composed cleanup grace**, the same value the sessions were composed - with, so no number is introduced. Work that settles within it settles - normally. If the call has not returned when the grace elapses, the owner - kills the runtime supervisor outright — `Process.exit(runtime.supervisor, - :kill)`, the pid the struct exposes — which is **crash-equivalent by - definition**: no terminal mutation is claimed, no `cancelled`, no - `outcome_unknown`, no abort record. A mutation whose commit was ambiguous - stays `commit_unknown` and fenced, and the reconciliation ADR 0006 and - ADR 0018 already define settles it at the next activation — exactly as - after an abrupt death. - - The owner can do this precisely *because* it is not a supervisor: there is - no restart intensity for a deliberate kill to trip, and the exit it causes - arrives at its own `{:EXIT, …}` clause, which knows this teardown is in - progress and does not re-enter the fail-stop path. - - **The daemon supplies that bound rather than trusting the runtime's own, - which is not one.** Core declares `shutdown: 5_000` for a session - coordinator but `shutdown: :infinity` for an owner group — whose - `terminate/2` itself calls `Supervisor.stop(workers, :shutdown, - :infinity)` — and three of the runtime supervisor's children are - supervisors, which default to `:infinity`. `Supervisor.stop/3` takes an - `:infinity` call timeout by default. "5,000 ms for a coordinator" is not - the bound of anything, and an earlier draft that claimed it was is - withdrawn. + calls `Supervisor.stop(runtime_supervisor, :normal, grace)` on the pid the + composition function handed it, with `grace` the **composed cleanup + grace** — the same value the sessions were composed with, so no number is + introduced. It does **not** call `Loopex.Runtime.stop/1`: that is arity one + and uses the default `:infinity` timeout, which is exactly the bound this + step exists to supply. + + **What a timeout does, read from the installed stdlib rather than + assumed.** `Supervisor.stop/3` reaches `gen:stop/3`, which is + `proc_lib:stop/3` (gen.erl:560-563). That function monitors the target, + calls `sys:terminate/3`, and on expiry — either from `sys:terminate` + raising `exit:{timeout, {sys, terminate, _}}` or from its own + `after RemainingTimeout` — demonitors and calls **`exit(timeout)`** + (proc_lib.erl:1575-1604). Two consequences follow, and both shape this + step: + + - **The target is not killed.** A timeout abandons the wait; the runtime + supervisor is still running afterwards. So the owner's kill is not a + belt-and-braces addition — it is the only thing that ends the tree. + - **The exit lands on the caller.** Left alone, the owner would die of + `timeout` and never reach step 4. So the call runs inside + `try … catch :exit, {:timeout, _} -> …`, which is the simplest form the + semantics allow: because `proc_lib:stop/3` exits the *caller*, a + `try/catch` in the owner is enough and no monitored helper process is + needed. + + On that catch the owner kills the runtime supervisor — + `Process.exit(runtime_supervisor, :kill)`. While the owner is blocked in + the stop call it cannot *act* on incoming exits, but it traps them, so they + queue as messages and are handled when the call returns; nothing is lost, + only deferred, which during a shutdown the owner is already performing is + what should happen. + + **What "crash-equivalent" does and does not claim.** An earlier draft said + the kill makes the tree crash-equivalent "by definition". That is true of + the coordinators and false of part of the tree, and the difference is worth + stating because a reader will otherwise assume more than holds. + `Process.exit(sup, :kill)` ends the root only; `killed` then propagates over + links, and a **trapping** descendant receives it as a message and unwinds on + its own clock. Three of the root's seven children are supervisors, and + `OwnerGroup` traps exits, carries `shutdown: :infinity`, and has a + `terminate/2` that itself calls `Supervisor.stop(workers, :shutdown, + :infinity)`. So: + + - coordinators, which do not trap, die at once; + - owner groups and their trapping workers unwind on their own clock, and + **the daemon does not wait for them**; + - the claim that survives is about the **journal**, not about processes: no + terminal mutation is claimed, nothing false is recorded, and the fencing + the journal already carries settles the ambiguous transaction at the next + activation — exactly as after a VM death. It is not the claim that every + process is gone when the daemon exits. + + Enumerating the subtree and killing it process by process was the + alternative and is rejected: there is no API that enumerates and kills a + supervision subtree without racing its own teardown, and a loop that walked + `which_children` would be reading a tree that is already dissolving. + 4. **The Store stops last**, and its `terminate/2` releases the writer marker - — see the marker invariant in ADR 0031. Stopping it last is what makes the - marker outlive every session operation that might still have needed it. - Then the socket path is unlinked and the owner **exits `0`**. + — see the marker invariant in ADR 0031. Then the socket path is unlinked + and the owner **exits `0`**. + + Stopping it last makes the marker outlive **every operation the owner can + end**, which is the honest form of a claim an earlier draft overstated. On + the ordinary path that is every operation. On the timeout path it is not: + an orphaned owner-group worker may still be unwinding when the Store goes, + and any call it then makes reaches a stopped Store and **fails as it would + after a VM death**. That is a refusal, never a write — the Store is gone, + so nothing can be appended behind the daemon's back — and it is why the + durability claim is about the journal rather than about quiescence. + + One dependency this step relies on is worth naming rather than assuming: + `Loopex.Store.Local` **traps exits**, so even an owner that crashes rather + than stopping runs the Store's `terminate/2` and gives the marker back. + The plan leans on that, and the adapter's own comment there says the same + thing from the other side — a kill or a power loss leaves the marker, which + is why recovery rather than release is what lets a successor open the + path. One ordering consequence is worth stating because it reverses an earlier draft: clients are told *before* work is drained, not after. That is @@ -857,19 +943,35 @@ not hold was ever promised, the marker left behind is reclaimed by the next daemon's verified stale-writer recovery, and the socket file is a stale path the next marker holder removes. -**The fatal-class map.** Every non-zero exit names one class on `stderr`. Its **reader is the owner's `{:EXIT, pid, reason}` clause**, which matches the pid against the four it holds and classifies the reason; there is one place in the daemon where a class is decided, and this is it: +**The fatal-class map.** Every non-zero exit names one class on `stderr`. Its +**reader is the owner's `{:EXIT, pid, reason}` clause**, which matches the pid +against the seven it holds, maps it to a component and classifies the reason; +there is one place in the daemon where a class is decided, and this is it. The +set is closed: **one class per linked component**, so no linked process can +die without a name for it. -| Class | When | -| --- | --- | -| `store_writer_active` | Startup: the marker is held by a live holder | -| `store_writer_unverifiable` | Startup: the marker's holder cannot be decided | -| `store_log_too_large` | Startup: the log is already past the capacity bound | -| `session_index_too_large` | Startup: the directory holds more than the index bound | -| `socket_path_too_long` | Startup: the path exceeds the derived `sun_path` bound | -| `socket_permission_unverified` | Startup: subdirectory or socket ownership/mode could not be verified | -| `store_lost` | Fail-stop: the Store terminated under a live listener | -| `store_capacity_exceeded` | Fail-stop: the Store terminated on the capacity refusal specifically | -| `supervision_fault` | Fail-stop: a lease owner failed, under ADR 0033's daemon-fatal rule. On the wire this is `fatal:supervision_fault`, since ADR 0032's `reason` set admits the fatal classes only under that prefix | +| Class | When | Wire reason | +| --- | --- | --- | +| `store_writer_active` | Startup: the marker is held by a live holder | — no socket exists | +| `store_writer_unverifiable` | Startup: the marker's holder cannot be decided | — | +| `store_log_too_large` | Startup: the log is already past the capacity bound | — | +| `session_index_too_large` | Startup: the directory holds more than the index bound | — | +| `socket_path_too_long` | Startup: the path exceeds the derived `sun_path` bound | — | +| `socket_permission_unverified` | Startup: subdirectory or socket ownership/mode could not be verified | — | +| `store_capacity_exceeded` | Linked process 1 exited **on the capacity refusal**, distinguished by the store's own reason | `store_capacity_exceeded` | +| `store_lost` | Linked process 1 exited for any other reason | `store_lost` | +| `runtime_lost` | Linked process 2, the runtime root, exited | `fatal:runtime_lost` | +| `transfers_lost` | Linked process 3, the artifact transfers owner, exited | `fatal:transfers_lost` | +| `workspace_lease_lost` | Linked process 4 exited | `fatal:workspace_lease_lost` | +| `executor_lost` | Linked process 5 exited | `fatal:executor_lost` | +| `supervision_fault` | Linked process 6, a lease owner, exited — ADR 0033's daemon-fatal rule | `fatal:supervision_fault` | +| `listener_lost` | Linked process 7 exited | `fatal:listener_lost` | + +The wire column matters because ADR 0032's `daemon.stopping` `reason` admits +`operator_stop`, `store_lost`, `store_capacity_exceeded` and `fatal:`, +so every class above that a running daemon can reach has a reason a client can +receive. The startup classes have none, deliberately: no socket exists when +they occur, so no client is holding one. **The daemon's own log is bounded and redacted by the rules that already exist.** Everything the daemon writes to `stderr` — refusals, warnings, the @@ -945,7 +1047,7 @@ plan names as new. It is the thing to check a change against. | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause, which treats any linked exit as fatal — ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause, which treats any of its seven linked processes' exits as fatal and maps the pid to a class — here `supervision_fault`. ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index e2937a2ca..86abc0785 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -114,8 +114,11 @@ read-only existence query — neither of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation -refuses with a stable reason, and the operator's remedy is to restart the -daemon. And `residency` means what the daemon can actually know: *this daemon +refuses with `activation_ceiling_reached`, and the operator's remedy is to +restart the daemon. **Creating a session spends one of those 64**, because a +created session has a coordinator like any other: `loopex run --daemon` costs +an activation exactly as `loopex resume --daemon` does, and an operator +planning a long-lived daemon should count both. And `residency` means what the daemon can actually know: *this daemon activated this session in this lifetime*, true by construction, never *a live coordinator exists*. A coordinator is core's `restart: :temporary` child and its loss is core's to supervise; it reaches a client as core's existing @@ -233,7 +236,7 @@ evidence that carries; ADR 0031 records why that is the successor's work and not M5's. No new store adapter, journal format version, migration or backup tooling enters M5. -A daemon activates a session when a client reaches for it, not at startup. +A daemon activates a session when a client creates or resumes it, not at startup — those are the two operations that start a coordinator, and acquiring control or attaching is neither. Sessions the root records are dormant until then, and the daemon holds at most a bounded number of active ones at a time; the rest stay dormant and cost nothing. One root is one host composition, so a recorded session the daemon's @@ -449,8 +452,11 @@ recorded because getting either wrong would be expensive to discover later. **The daemon owns its own lifetime, through an owner process rather than a supervisor.** Its top-level component is one `GenServer` that traps exits and -`start_link`s four things — the Store adapter, the runtime, the lease owner, -the listener — keeping the Store's pid and the runtime's struct. Any linked +`start_link`s seven processes: the five the composition function assembles in +its caller's process — the Store adapter, the runtime root, the artifact +transfers owner where enabled, the workspace lease and the local executor — +plus the daemon's own lease owner and listener. It keeps every pid, because +each one is a component it must be able to name when that component dies. Any linked exit is fatal, by that process's own clause, and that clause is what reads a dying Store's reason and turns it into the class the daemon reports. It is not an OTP `Supervisor`: a supervisor offers no callback that can read a child's From 334001cef9142a448d57f71e49c79a14612f20c1 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:21:29 -0700 Subject: [PATCH 057/585] plan(M5): fix what my adversarial pass found in the stop rewrite Five findings against this round's diff, two of them real gaps. AP1: the boundary table's signals row still named Runtime.stop/1 and runtime.supervisor, both of which R1 replaced. AP2/AP3, a real gap: I numbered the seven linked processes in the order I thought of them rather than the order composition starts them. Read again: Store.Local (:171), then artifact_placement's Transfers (:260), then open_executor's WorkspaceLease (:283) and Local (:289), and the runtime root (:177) LAST, because it depends on all of them. The table now carries that order, the fatal-class map's component numbers follow it, and the shutdown order falls out of reversing it -- runtime before the executor it drives, Store after everything that could still write to it. AP4, the larger half of the same gap: the ordered shutdown still had four steps for seven linked processes, so the executor, workspace lease and transfers owner would have been left running while the Store went out from under them. Step 4 now stops them in reverse order, executor first. AP5, the finding I would most have regretted missing: on the fail-stop path the owner exited without stopping the executor. The executor is the one linked process owning effects outside the VM, and it traps exits precisely to clean them up -- halting past it leaks OS effects no later daemon knows about. The fail-stop path now stops it before halting, and says why the other five need no such step. That exposed something else worth stating: BEAM exit semantics alone do not end a daemon, because a :normal exit from the owner is ignored by every linked process that does not trap. The owner's last act is halting the VM with the status, and both paths now say so -- on the ordered path the halt finds a quiet VM, on the fail-stop path it ends what remains after the executor has cleaned up. AP6: witnesses added for the classes and the timeout the rewrite introduced -- one case per linked component asserting its class and its wire reason, and a case that holds the runtime's teardown past the grace and asserts the owner SURVIVES proc_lib:stop/3's exit(timeout), kills the supervisor, and still reaches the Store stop and the socket unlink. --- docs/plans/M5-technical.md | 84 ++++++++++++++++++++++++++++++-------- 1 file changed, 66 insertions(+), 18 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 441785656..23827d021 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -725,13 +725,21 @@ own: | # | Linked process | Where it comes from | Optional? | | --- | --- | --- | --- | | 1 | The Store adapter | `start_edge(Store.Local, …)` | no | -| 2 | The runtime root | `start_edge(Loopex, …)` | no | -| 3 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | -| 4 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | -| 5 | The local executor | `start_edge(Local, …)` | no | +| 2 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | +| 3 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | +| 4 | The local executor | `start_edge(Local, …)` | no | +| 5 | The runtime root | `start_edge(Loopex, …)` | no | | 6 | The lease owner | The daemon's own, under ADR 0033 | no | | 7 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | +The numbering is the composition's actual start order, not a tidied one: the +Store first, then the artifact placement and the executor's own edges, and the +runtime **last**, because it is the thing that depends on all of them. Reverse +that and the shutdown order falls out — listener, lease owner, runtime, +executor, workspace lease, transfers, Store — with the runtime stopping before +the executor it drives and the Store stopping after everything that could +still have written to it. + The composition function therefore returns **every pid it linked**, not only the ones the daemon names in prose: a map carrying `store`, `runtime` (the `%Loopex.Runtime{}` struct), `runtime_supervisor`, `transfers` (absent when @@ -875,9 +883,18 @@ chooses. supervision subtree without racing its own teardown, and a loop that walked `which_children` would be reading a tree that is already dissolving. -4. **The Store stops last**, and its `terminate/2` releases the writer marker - — see the marker invariant in ADR 0031. Then the socket path is unlinked - and the owner **exits `0`**. +4. **The remaining composed edges stop, then the Store last.** Reverse start + order puts the executor, the workspace lease and the transfers owner + between the runtime and the Store, and each is stopped in turn — the + executor first, since it is the one with OS effects to clean up and it + traps exits to do so. Then the Store, whose `terminate/2` releases the + writer marker — see the marker invariant in ADR 0031. Finally the socket + path is unlinked and the owner **exits `0`**. + + An earlier draft of this list had four steps for what are seven linked + processes, which would have left the executor, the lease and the transfers + owner running while the Store went out from under them. They are stopped + here, in this order, for that reason. Stopping it last makes the marker outlive **every operation the owner can end**, which is the honest form of a claim an earlier draft overstated. On @@ -925,8 +942,14 @@ information lost on the way. Then, without the ordered sequence: 2. Close every connection, after one bounded best-effort `daemon.stopping` carrying `store_lost`, or `store_capacity_exceeded` when the store's own reason was the capacity refusal. -3. Unlink the socket. -4. Exit non-zero with that class on `stderr`. **There is no "stop the Store" +3. **Stop the executor**, even though the Store is already gone. This is not + tidiness: the executor is the one linked process that owns effects outside + the VM, and it traps exits precisely so it can clean them up. Halting + without stopping it would leave OS effects behind that no later daemon + knows about. The other linked processes need no such step — they own + nothing that outlives the VM. +4. Unlink the socket. +5. Exit non-zero with that class on `stderr`. **There is no "stop the Store" step**, because the Store already stopped and the marker is already released; the next daemon finds no marker to recover rather than a stale one. Nothing restarts the Store: the owner start_links its children and @@ -937,6 +960,16 @@ Nothing durable is at risk in that ordering: whatever was ambiguous is `commit_unknown` in the journal and is reconciled at the next activation, and whatever was not committed was never promised. +**How the daemon actually ends, on either path.** The owner's last act is to +halt the VM with the status — `0` for an operator stop, non-zero with the +class for a fatal one. That matters to state because BEAM exit semantics +alone would not do it: a `:normal` exit from the owner is ignored by every +linked process that does not trap, so "the owner exits" is not by itself a +shutdown. On the ordered path the halt finds a VM whose processes have +already been stopped in sequence; on the fail-stop path it ends whatever +remains, after step 3 has given the one process with external effects its +chance to clean up. + **An abrupt death** — `SIGKILL`, power loss — runs neither path, and is safe for the reasons the durability rules already give: nothing the journal does not hold was ever promised, the marker left behind is reclaimed by the next @@ -958,14 +991,14 @@ die without a name for it. | `session_index_too_large` | Startup: the directory holds more than the index bound | — | | `socket_path_too_long` | Startup: the path exceeds the derived `sun_path` bound | — | | `socket_permission_unverified` | Startup: subdirectory or socket ownership/mode could not be verified | — | -| `store_capacity_exceeded` | Linked process 1 exited **on the capacity refusal**, distinguished by the store's own reason | `store_capacity_exceeded` | -| `store_lost` | Linked process 1 exited for any other reason | `store_lost` | -| `runtime_lost` | Linked process 2, the runtime root, exited | `fatal:runtime_lost` | -| `transfers_lost` | Linked process 3, the artifact transfers owner, exited | `fatal:transfers_lost` | -| `workspace_lease_lost` | Linked process 4 exited | `fatal:workspace_lease_lost` | -| `executor_lost` | Linked process 5 exited | `fatal:executor_lost` | +| `store_capacity_exceeded` | Linked process 1, the Store, exited **on the capacity refusal**, distinguished by its own reason | `store_capacity_exceeded` | +| `store_lost` | Linked process 1, the Store, exited for any other reason | `store_lost` | +| `runtime_lost` | Linked process 5, the runtime root, exited | `fatal:runtime_lost` | +| `transfers_lost` | Linked process 2, the artifact transfers owner, exited | `fatal:transfers_lost` | +| `workspace_lease_lost` | Linked process 3, the workspace lease, exited | `fatal:workspace_lease_lost` | +| `executor_lost` | Linked process 4, the local executor, exited | `fatal:executor_lost` | | `supervision_fault` | Linked process 6, a lease owner, exited — ADR 0033's daemon-fatal rule | `fatal:supervision_fault` | -| `listener_lost` | Linked process 7 exited | `fatal:listener_lost` | +| `listener_lost` | Linked process 7, the listener, exited | `fatal:listener_lost` | The wire column matters because ADR 0032's `daemon.stopping` `reason` admits `operator_stop`, `store_lost`, `store_capacity_exceeded` and `fatal:`, @@ -1017,7 +1050,22 @@ what lets an operator fix the cause and try again without a recovery step. sequence, because the marker was already released by the Store's own `terminate/2` before the daemon could act. A second daemon starts on that root immediately with no stale marker to recover. The capacity variant - reports `store_capacity_exceeded` instead. + reports `store_capacity_exceeded` instead, and the case asserts the executor + was stopped before the halt, so no OS effect is left behind. +- **One class per linked component.** Each of the seven linked processes is + killed in turn, in its own case, and the daemon is asserted to exit with + that component's class and to send that component's `fatal:` on the + wire where a socket still exists — `runtime_lost`, `transfers_lost`, + `workspace_lease_lost`, `executor_lost`, `supervision_fault`, + `listener_lost`, beside the two store classes. The set is closed, so a + linked process dying without a class is a failing case rather than a silent + `:shutdown`. +- **The stop timeout is exercised, not assumed.** A session is made to hold + the runtime's teardown past the composed cleanup grace. The case asserts the + owner **survives** the resulting `exit(timeout)` from `proc_lib:stop/3` + rather than dying of it, that it then kills the runtime supervisor, and that + it still reaches the Store stop and the socket unlink — the whole point of + wrapping the call, and the step an unwrapped call would skip. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting @@ -1052,7 +1100,7 @@ plan names as new. It is the thing to check a change against. | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The owner stops its children in reverse order itself — listener, lease owner, runtime, Store — calling `Runtime.stop/1` under the composed cleanup grace and killing `runtime.supervisor` on expiry | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently, for which no terminal is claimed | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The owner stops its linked processes in reverse order itself — listener, lease owner, runtime, then the composed edges, Store last — calling `Supervisor.stop(runtime_supervisor, :normal, grace)` under `try/catch :exit`, since `proc_lib:stop/3` exits the caller on timeout without killing the target, and killing the supervisor on that catch | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | `terminate/2` in an orderly stop; `terminate/2` early on store loss; nothing on a kill | Nothing directly; the next daemon's start succeeds, succeeds, or recovers | **Not durable in the journal sense:** the marker is exclusion, not truth | From 80ad3fd007fcdd376c46ded2d6e1afff8daf412d Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:39:11 -0700 Subject: [PATCH 058/585] plan(M5): fix the exits the owner's own stops cause S1: the owner carries a `stopping` field naming the component it is stopping; that component's exit is consumed and clears the field, every other exit is classified as before. The field is cleared by the exit, not by the call returning, because a caught timeout followed by `Process.exit(pid, :kill)` also produces one and the EXIT/DOWN order to a single receiver is not ours to assume. A class recorded during a stop does not abort the sequence; the first class wins and the halt carries it. S2: the end is `System.halt(status)` (`:erlang.halt/1`), which runs no callbacks; `:init.stop/0` is rejected because it would wait on the orphaned owner-group subtree. Since no `terminate/2` runs at the halt, the fail-stop path stops the Store on the six classes where it is still alive, and the residual of an expired Store stop is the stale marker ADR 0031 already answers. S3: the stop chain read from the installed stdlib is `Supervisor.stop/3` (supervisor.ex:1152-1154) -> `GenServer.stop/3` (gen_server.ex:1076-1092, identical in both floor pairs) -> `:proc_lib.stop/3` (proc_lib.erl: 1575-1604). `GenServer.stop/3` wraps what it catches, so the owner matches `{:timeout, {GenServer, :stop, [pid, :normal, grace]}}`, not a bare `:timeout`. S4/S6: returning the runtime supervisor pid is a convenience, not an opacity repair. `@opaque` at runtime.ex:45 is unenforced here and `runtime_owner.ex:200` already destructures the field. S5: the executor, workspace lease, transfers owner and Store are each `GenServer.stop(pid, :normal, grace)` under the same catch-and-kill, all four being GenServers (executor.ex:22, workspace_lease.ex:15, transfers.ex:26, local.ex:55). Every bound is the composed cleanup grace; three are ceilings and only the executor is expected to spend the time. The executor is stopped before the lease because it reads the lease holder's DOWN as cancellation evidence (workspace_lease.ex:1-13). The residual is stated honestly: the Port-owning worker that would terminate the captured process group is a process in this VM, so the halt ends it too and operating-system children may survive; the journal does not, the effect stays `commit_unknown`. --- docs/plans/M5-technical.md | 276 ++++++++++++++++++++++++++++++------- 1 file changed, 226 insertions(+), 50 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 23827d021..e75b2dead 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -744,21 +744,72 @@ The composition function therefore returns **every pid it linked**, not only the ones the daemon names in prose: a map carrying `store`, `runtime` (the `%Loopex.Runtime{}` struct), `runtime_supervisor`, `transfers` (absent when disabled), `workspace_lease` and `executor`. Returning the runtime supervisor -pid separately matters: `%Loopex.Runtime{}`'s type is declared `@opaque`, so -the daemon reaching into its `supervisor` field would be an opacity violation -across applications. Composition already holds that pid, so handing it over -costs nothing and keeps the daemon out of another application's internals. +pid separately is a convenience rather than a necessity, and the plan says so +plainly: the owner needs that pid to bound its stop, composition already holds +it, so handing it over costs nothing. `%Loopex.Runtime{}`'s type is declared +`@opaque` at `runtime.ex:45`, but that is unenforced here — the repository +runs no dialyzer, and `RuntimeOwner` itself already destructures the field, at +`runtime_owner.ex:200`. An earlier draft called reading it a violation; it is +not, and the real argument is the simpler one above. **There is no restart strategy, because there are no restarts.** Every one of the seven is `start_link`ed by the owner, and the owner's -`handle_info({:EXIT, pid, reason}, state)` clause is the whole failure rule: -any linked exit, whatever the reason, is fatal to the daemon instance. That +`handle_info({:EXIT, pid, reason}, state)` clause is the failure rule. That clause is also the **reader** the fatal-class map needs — it matches the pid against the seven it holds, maps it to a component, classifies `reason`, and has the class in hand before anything else happens. Nothing here is `rest_for_one`, `one_for_all` or `max_restarts`; those words belonged to the withdrawn design and are gone. +**One field keeps that clause from firing on the owner's own work.** An +earlier draft said "any linked exit, whatever the reason, is fatal", which is +right for an exit the owner did not cause and wrong for every exit it does: +an orderly stop terminates all seven deliberately, so that rule would classify +step 1 as `listener_lost`, step 2 as `supervision_fault`, step 3's clean +return as `runtime_lost` — a daemon that could never exit `0`, and an +idle-shutdown witness that could never pass. + +So the owner carries a `stopping` field naming **the one component it is +currently stopping**, set immediately before each stop call. The EXIT clause +reads: + +- an exit from the pid named in `stopping`, while it is named, is **consumed** + and clears the field — it is the stop the owner asked for, arriving as a + signal; +- **every other exit is classified exactly as before**, including one from a + component not yet stopped that dies of its own accord *during* another + component's stop. A store that fails while the listener is being stopped is + still `store_lost`, and must be: the daemon is going down either way, but + the operator is owed the real reason rather than `operator_stop`. + +**The field is cleared by that exit, not by the call returning**, and the +distinction is not pedantry. A stop can end three ways — `:ok`, a caught +timeout followed by `Process.exit(pid, :kill)`, or the component having died +already — and in the first two the exit signal is still on its way when the +call returns; whether it or the monitor's `DOWN` arrives first is not ordered +for us. So after each stop the owner waits for that exact pid's exit, in a +selective receive it can only reach because the process is dead either way, +and only then names the next component. Messages that arrive meanwhile stay +in the mailbox and are classified when the owner returns to its loop; nothing +is skipped, only ordered. + +Two consequences the sequences below depend on, stated here once: + +- **A class recorded during a stop does not abort the sequence.** The owner + finishes stopping what remains — the components it has not reached still own + things worth ending — and then halts with that class instead of `0`. The + first class recorded wins; a later one does not overwrite it, so the + operator gets the reason the daemon went down for rather than the last thing + that happened on the way out. +- **A component already known dead is not stopped again.** Its exit was + classified, so the owner holds that fact; the step for it is a no-op rather + than a call on a dead pid. + +One field, one place, and it is what makes the two paths distinguishable at +all. Both sequences below rely on it, and the idle-shutdown witness asserts +the consequence directly: **no fatal class is recorded during an orderly +stop**. + Two of the seven trap exits, and the plan states that as contract rather than relying on it as luck: the **Store adapter** traps, so an owner that crashes still runs its `terminate/2` and returns the marker; the **local executor** @@ -833,13 +884,24 @@ chooses. step exists to supply. **What a timeout does, read from the installed stdlib rather than - assumed.** `Supervisor.stop/3` reaches `gen:stop/3`, which is - `proc_lib:stop/3` (gen.erl:560-563). That function monitors the target, - calls `sys:terminate/3`, and on expiry — either from `sys:terminate` - raising `exit:{timeout, {sys, terminate, _}}` or from its own - `after RemainingTimeout` — demonitors and calls **`exit(timeout)`** - (proc_lib.erl:1575-1604). Two consequences follow, and both shape this - step: + assumed — and the chain is not the obvious one.** `Supervisor.stop/3` is + `GenServer.stop(supervisor, reason, timeout)` (supervisor.ex:1152-1154), + and `GenServer.stop/3` calls **`:proc_lib.stop/3` directly**, not + `:gen.stop/3`, wrapping any exit it catches: + `catch :exit, err -> exit({err, {__MODULE__, :stop, [server, reason, + timeout]}})` (gen_server.ex:1076-1092, identical in both floor pairs, + 1.18.5-otp-27 and 1.20.3-otp-29). Beneath that wrapper, + `:proc_lib.stop/3` monitors the target, calls `sys:terminate/3`, and on + expiry — from `sys:terminate` raising `exit:{timeout, {sys, terminate, + _}}` or from its own `after RemainingTimeout` — demonitors and calls the + bare **`exit(timeout)`** (proc_lib.erl:1575-1604). + + So the shape the owner actually sees is + **`{:timeout, {GenServer, :stop, [pid, :normal, grace]}}`**, not a bare + `:timeout`. `catch :exit, {:timeout, _}` matches it — but only because of + that wrapper, and the plan names the wrapper so nobody later "simplifies" + the clause to match what `proc_lib` raises. Two consequences follow, and + both shape this step: - **The target is not killed.** A timeout abandons the wait; the runtime supervisor is still running afterwards. So the owner's kill is not a @@ -854,7 +916,9 @@ chooses. On that catch the owner kills the runtime supervisor — `Process.exit(runtime_supervisor, :kill)`. While the owner is blocked in the stop call it cannot *act* on incoming exits, but it traps them, so they - queue as messages and are handled when the call returns; nothing is lost, + queue as messages and are handled when the call returns — against the + `stopping` field, so the runtime's own exit is consumed and any other + component's is still classified; nothing is lost, only deferred, which during a shutdown the owner is already performing is what should happen. @@ -889,11 +953,61 @@ chooses. executor first, since it is the one with OS effects to clean up and it traps exits to do so. Then the Store, whose `terminate/2` releases the writer marker — see the marker invariant in ADR 0031. Finally the socket - path is unlinked and the owner **exits `0`**. - - An earlier draft of this list had four steps for what are seven linked - processes, which would have left the executor, the lease and the transfers - owner running while the Store went out from under them. They are stopped + path is unlinked and the owner **halts with `0`**. + + **The executor is stopped before the lease, and that order is load-bearing** + rather than alphabetical. The executor privately monitors the lease holder + for a job's full life and reads its `DOWN` as cancellation evidence + (`workspace_lease.ex:1-13`). Stopping the lease first would hand the + executor a cancellation in the middle of its own cleanup; stopping the + executor first means the lease's death is observed by nobody, which is + what an orderly stop wants. + + **Each of these four is `GenServer.stop(pid, :normal, bound)` under the + same treatment as step 3** — `try/catch :exit` on the wrapped timeout, then + `Process.exit(pid, :kill)` — because all four are `GenServer`s + (`executor.ex:22`, `workspace_lease.ex:15`, `transfers.ex:26`, + `local.ex:55`) and the same OTP semantics apply: a timeout does not kill + the target, and the exit lands on the owner. The bounds: + + | Process | Bound | What it is waiting for | + | --- | --- | --- | + | The executor | The **composed cleanup grace** | Its own cleanup of operating-system effects — the one stop here that can actually use the time, given the value the sessions were composed with, for the purpose that value names | + | The workspace lease | The same grace | Nothing: it has no `terminate/2` and holds no file — the lease *is* the live process, so stopping it revokes it. The bound is a ceiling it will not reach | + | The transfers owner | The same grace | Closing the open transfer descriptors its `terminate/2` holds (`transfers.ex:146-149`) | + | The Store | The same grace | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | + + No new number enters: every bound here is the composed cleanup grace, + which is what step 3 uses and what the sessions carry. Splitting it into + fractions would mean inventing ratios, and the minimalism budget takes + every number from an accepted or proposed decision. Three of the four are + ceilings rather than expected waits; only the executor is expected to spend + real time here. + + **A killed executor is the residual, and the plan states it rather than + explaining it away.** The kill by itself is not the leak. The executor + `GenServer` does not own the Port: a monitored worker owns it, watches the + executor, and *performs the same bounded group termination if that + authority disappears* (`executor.ex:3703-3724`, and `effect_owner/0` at + `executor.ex:4166-4173`) — the executor's own contract for exactly this + case, written after a kill once left a descendant running. + + But that worker is a process **in this VM**, and the halt a few steps later + ends it too. Whatever bounded termination it has not finished when the VM + goes does not finish. So the residual of an unresponsive executor is + honest and stated: **operating-system children may survive the daemon**, as + an orphaned process group an operator can see and reap. The plan does not + add a wait for that worker — an unbounded wait at the end of a sequence + whose purpose is to be bounded is the thing being avoided. + + What is *not* at risk is durable truth. The effect that was in flight is + `commit_unknown` in the journal and resolves to exactly one outcome at the + next activation, exactly as an abrupt death leaves it; nothing false is + recorded about it, and no terminal is claimed. + + An earlier draft ended at the runtime and the Store, naming neither the + executor, the lease nor the transfers owner — which would have left all + three running while the Store went out from under them. They are stopped here, in this order, for that reason. Stopping it last makes the marker outlive **every operation the owner can @@ -935,40 +1049,89 @@ fatal-class map's reader: it matches the pid, classifies `reason` as `store_capacity_exceeded` where that was the store's own refusal and `store_lost` otherwise, and has the class in hand before it does anything else. No link the owner does not already hold, no monitor to remember, and no -information lost on the way. Then, without the ordered sequence: +information lost on the way. + +**The steps below are the fail-stop path for every fatal class, not only the +two store ones.** Store loss is the instance worth reading first because it is +the one where the thing the daemon would otherwise stop is already gone; the +other six differ only in which component is missing by the time the owner +runs them. In all eight the owner has a class in hand, runs no ordered +sequence, and does not return to serving. A step whose component is already +gone is a no-op, by the rule the `stopping` field states above: under +`listener_lost` steps 1 and 2 are already true and the clients of that +listener learn by the close rather than by a `daemon.stopping` nothing is left +to write. 1. Refuse service immediately — no further admission, no further attach, and the listener closed. 2. Close every connection, after one bounded best-effort `daemon.stopping` - carrying `store_lost`, or `store_capacity_exceeded` when the store's own - reason was the capacity refusal. -3. **Stop the executor**, even though the Store is already gone. This is not - tidiness: the executor is the one linked process that owns effects outside - the VM, and it traps exits precisely so it can clean them up. Halting - without stopping it would leave OS effects behind that no later daemon - knows about. The other linked processes need no such step — they own - nothing that outlives the VM. -4. Unlink the socket. -5. Exit non-zero with that class on `stderr`. **There is no "stop the Store" - step**, because the Store already stopped and the marker is already - released; the next daemon finds no marker to recover rather than a stale - one. Nothing restarts the Store: the owner start_links its children and - restarts none of them, so any linked exit is fatal by its own clause — + carrying that class: `store_lost`, or `store_capacity_exceeded` when the + store's own reason was the capacity refusal, and the failed component's own + class on the other six. +3. **Stop the executor** — on every class but `executor_lost`, where it is + the component that already died — as `GenServer.stop(pid, :normal, grace)` + under the same try/catch-and-kill treatment and the same composed cleanup + grace the ordered path's step 4 uses. This is not tidiness: the executor is + the one linked process that owns effects outside the VM, and it traps exits + precisely so it can clean them up. Halting without stopping it would end + that cleanup where it stood. The residual is the one stated there and is + the same here: if the stop times out and the executor is killed, the halt + that follows also ends the Port-owning worker that would have terminated + the captured process group, so operating-system children may survive the + daemon. The journal does not: the effect is `commit_unknown` and reconciles + at the next activation. +4. **Stop the Store — on every class except the two store classes.** Where the + Store terminated itself, `store_lost` or `store_capacity_exceeded`, it is + already gone and its `terminate/2` has already released the marker; there + is nothing to stop. On the other six, the Store is **still alive**, and + because `System.halt/1` runs no `terminate/2`, halting past it would leave + the marker file behind on a daemon that shut down deliberately. So the + owner stops it here, under the same bounded treatment as every other stop. + + **If that stop times out and the Store is killed, the marker survives.** + That is the one residual on this path and the plan states it rather than + implying otherwise. It is bounded in consequence, not open-ended: the next + daemon meets exactly the stale marker ADR 0031's recovery rule already + covers, and reclaims it where the marker's own recorded holder is probed + and found dead, refuses with `store_writer_unverifiable` where it cannot be + decided, and refuses with `store_writer_active` where it is alive. A + surviving marker is a case with a defined answer, not a corruption. +5. Unlink the socket. +6. Write the class on `stderr`, then **halt with the non-zero status** for + that class. Nothing restarts anything: the owner `start_link`s its seven + and restarts none, so an exit it did not cause is fatal by its own clause — which is why this path exists at all rather than being a restart. Nothing durable is at risk in that ordering: whatever was ambiguous is `commit_unknown` in the journal and is reconciled at the next activation, and whatever was not committed was never promised. -**How the daemon actually ends, on either path.** The owner's last act is to -halt the VM with the status — `0` for an operator stop, non-zero with the -class for a fatal one. That matters to state because BEAM exit semantics -alone would not do it: a `:normal` exit from the owner is ignored by every -linked process that does not trap, so "the owner exits" is not by itself a -shutdown. On the ordered path the halt finds a VM whose processes have -already been stopped in sequence; on the fail-stop path it ends whatever -remains, after step 3 has given the one process with external effects its -chance to clean up. +**How the daemon actually ends, on either path.** The owner's last act is +`System.halt(status)` — `:erlang.halt/1` — with `0` for an operator stop and +the non-zero status for a fatal one. That matters to state because BEAM exit +semantics alone would not do it: a `:normal` exit from the owner is ignored by +every linked process that does not trap, so "the owner exits" is not by itself +a shutdown. + +**And `halt` runs no callbacks**, which is the whole reason the sequences +above stop things explicitly rather than trusting the exit. `:erlang.halt/1` +terminates the VM immediately: no `terminate/2` anywhere, no `Application` +stop callbacks. The alternative, `:init.stop/0`, does run them — and is +rejected here precisely for that, because it would walk the application tree +and wait on whatever the orphaned owner-group subtree is doing, which is the +unbounded wait the grace exists to avoid. The daemon takes a bounded stop it +performs itself, then a halt that cannot hang. + +**One consequence this had to fix.** `terminate/2` not running means the +Store's marker release does not happen at the halt. On the ordered path that +is fine — the Store was already stopped in step 4, and its `terminate/2` ran +then. On the **fatal** path it was not fine, and an earlier draft left a real +hole: for the six classes where the Store is still alive (`runtime_lost`, +`transfers_lost`, `workspace_lease_lost`, `executor_lost`, +`supervision_fault`, `listener_lost`), nothing stopped the Store, so the halt +left the marker file behind on a daemon that had shut down deliberately. The +fail-stop path above therefore stops the Store on every fatal class +**except** the two store classes, where it is already gone. **An abrupt death** — `SIGKILL`, power loss — runs neither path, and is safe for the reasons the durability rules already give: nothing the journal does @@ -1032,7 +1195,16 @@ what lets an operator fix the cause and try again without a recovery step. receives `SIGTERM`, writes nothing further to `stdout`, closes every connection with the stop reason, unlinks the socket, releases the marker and exits `0`; the foreground server then opens the same root immediately, which - is what proves the marker was actually released. + is what proves the marker was actually released. The case also asserts the + negative that the `stopping` field exists for: **no fatal class is recorded + at any point during the stop**, and nothing appears on `stderr` — stopping + seven linked processes deliberately produces seven exits, and every one of + them must be consumed rather than classified. +- **A real failure during an orderly stop is still classified.** The Store is + made to fail while the listener is being stopped. The daemon exits with + `store_lost`, not `operator_stop`, because the Store is not the component + named in `stopping` — the operator is owed the reason the daemon actually + went down for. - **In-flight shutdown.** A daemon with a dispatched tool effect and an unresolved mutation receives `SIGTERM`. What has not settled within the cleanup grace is ended crash-equivalently, and the case asserts the negative @@ -1051,11 +1223,15 @@ what lets an operator fix the cause and try again without a recovery step. `terminate/2` before the daemon could act. A second daemon starts on that root immediately with no stale marker to recover. The capacity variant reports `store_capacity_exceeded` instead, and the case asserts the executor - was stopped before the halt, so no OS effect is left behind. + was stopped — and that the stop *returned* rather than timing out into a + kill — before the halt, so its cleanup ran and no operating-system child is + left behind. - **One class per linked component.** Each of the seven linked processes is killed in turn, in its own case, and the daemon is asserted to exit with - that component's class and to send that component's `fatal:` on the - wire where a socket still exists — `runtime_lost`, `transfers_lost`, + that component's class, to send that component's `fatal:` on the wire + where a socket still exists, and — for the six classes where the Store is + still alive — **to leave no stale marker**, proved by the next daemon + opening that root with nothing to recover — `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `supervision_fault`, `listener_lost`, beside the two store classes. The set is closed, so a linked process dying without a class is a failing case rather than a silent @@ -1095,15 +1271,15 @@ plan names as new. It is the thing to check a change against. | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause, which treats any of its seven linked processes' exits as fatal and maps the pid to a class — here `supervision_fault`. ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause. The lease owner is not the component named in `stopping`, so the exit is classified rather than consumed, and the pid maps to `supervision_fault` — ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The owner stops its linked processes in reverse order itself — listener, lease owner, runtime, then the composed edges, Store last — calling `Supervisor.stop(runtime_supervisor, :normal, grace)` under `try/catch :exit`, since `proc_lib:stop/3` exits the caller on timeout without killing the target, and killing the supervisor on that catch | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The owner stops its linked processes in reverse order itself — listener, lease owner, runtime, then the composed edges, Store last — each bounded by the composed cleanup grace and each under `try/catch :exit` on the wrapped `{:timeout, {GenServer, :stop, _}}` (`Supervisor.stop/3` → `GenServer.stop/3` → `:proc_lib.stop/3`), since a timeout exits the caller without killing the target, then killing that target on the catch. Every exit these stops cause is consumed by the owner's `stopping` field rather than classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | -| **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | `terminate/2` in an orderly stop; `terminate/2` early on store loss; nothing on a kill | Nothing directly; the next daemon's start succeeds, succeeds, or recovers | **Not durable in the journal sense:** the marker is exclusion, not truth | +| **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | Three rows deserve their reading stated, because they are where earlier drafts went wrong. The **coordinator death** row is the one that forced `residency` From 3b8623943f492a40acece811322992d401ea516a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:39:18 -0700 Subject: [PATCH 059/585] plan(M5): align the concept and ADR 0031 with both stop paths Found by the adversarial pass over this round's diff, not by the review. M5.md still said "any linked exit is fatal", which S1 makes wrong for the seven exits an orderly stop causes; it now distinguishes an exit the owner did not ask for from the ones its own sequence causes. Outcome 1 claimed a fatal exit "runs the same sequence"; it runs the fail-stop instead, which drains nothing and stops the Store only where it is still alive. The store-loss paragraph omitted the executor stop. ADR 0031's marker dispositions were three and are four: a daemon that stops the Store releases the marker in order on an orderly stop and on a fatal class where the Store is still alive; a store loss releases it early; a kill, a power loss or a bounded stop that expired leaves it for verified stale-writer recovery. --- ...store-selection-and-migration-technical.md | 14 +++++++++----- docs/plans/M5.md | 19 +++++++++++++------ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 35a1873b2..0e6af5e88 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -36,8 +36,9 @@ exits. The adapter also **traps exits**, which this arrangement relies on: an owner that crashes rather than stopping still runs the Store's `terminate/2`, so the -marker comes back. Only a kill or a power loss leaves it, which is what the -next daemon's verified stale-writer recovery is for. +marker comes back. What leaves it is a kill, a power loss, or a bounded stop +of the Store that expired and had to be ended with `Process.exit(pid, :kill)` +— the three cases the next daemon's verified stale-writer recovery is for. **Store loss inverts it, and the daemon cannot order what it does not control.** This adapter answers an append error with @@ -62,9 +63,12 @@ the dying store already gave it back. An abrupt kill of the daemon runs no `terminate/2` at all, which is why *that* leaves a marker behind and why the next daemon's verified stale-writer -recovery exists. The three cases are distinct and the operator documentation -keeps them so: an orderly stop releases the marker in order, a store loss -releases it early and unexpectedly, and a kill leaves it for recovery. The adapter's limits are the +recovery exists. The cases are distinct and the operator documentation keeps +them so: a daemon that stops the Store releases the marker in order — whether +that is an orderly shutdown or a fatal class where the Store is still alive +and the daemon stops it before halting; a store loss releases it early and +unexpectedly; and a kill, a power loss or an expired stop leaves it for +recovery. The adapter's limits are the daemon's limits, and every one is an existing constant or refusal of `Loopex.Store.Local.Log`: diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 86abc0785..8a4f93fc8 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -48,7 +48,7 @@ transport, no second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, drains admitted work within the cleanup grace and settles the rest through cancellation bounds and fenced `commit_unknown` rather than abandoning it, tells every client the reason, unlinks the socket and stops the Store last, exiting `0`; a fatal exit runs the same sequence and returns a named reason class. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, drains admitted work within the cleanup grace and settles the rest through cancellation bounds and fenced `commit_unknown` rather than abandoning it, tells every client the reason, unlinks the socket and stops the Store last, exiting `0`; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -352,8 +352,11 @@ second loop this milestone forbids. append error by terminating itself, and its `terminate/2` releases the marker on the way out, so by the time the daemon observes anything the store is gone and the marker is already released. It is a fail-stop: refuse service, close -every connection with the reason, unlink the socket, exit non-zero. There is -no "stop the Store last" step to run when the Store is what died. The +every connection with the reason, stop the executor, unlink the socket, exit +non-zero. There is no "stop the Store last" step to run when the Store is what +died — though on a fatal class where the Store is still alive the daemon does +stop it, because the halt runs no `terminate/2` and the marker would otherwise +be left behind. The technical companion fixes both paths, the fatal-class map and the reverse cleanup a failed startup performs. @@ -456,9 +459,13 @@ supervisor.** Its top-level component is one `GenServer` that traps exits and its caller's process — the Store adapter, the runtime root, the artifact transfers owner where enabled, the workspace lease and the local executor — plus the daemon's own lease owner and listener. It keeps every pid, because -each one is a component it must be able to name when that component dies. Any linked -exit is fatal, by that process's own clause, and that clause is what reads a -dying Store's reason and turns it into the class the daemon reports. It is not +each one is a component it must be able to name when that component dies. An +exit the owner did not ask for is fatal, by that process's own clause, and +that clause is what reads a dying Store's reason and turns it into the class +the daemon reports. The exits the owner's own stop sequence causes are +consumed rather than classified — otherwise stopping the seven deliberately +would report a fatal class every time — and the technical companion states the +one field that tells the two apart. It is not an OTP `Supervisor`: a supervisor offers no callback that can read a child's exit reason, so `store_lost` and `store_capacity_exceeded` would be indistinguishable, and `Loopex.Runtime.start_link/1` returns a struct rather From f2e3dd3411caf5f09454f199e6c93ec77435c2fd Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:47:44 -0700 Subject: [PATCH 060/585] plan(M5): catch the noproc a mid-sequence death raises MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit T1: a component that dies during the stop sequence has its EXIT unread — the owner does not read its mailbox while stopping — so its own step calls `GenServer.stop` on a dead pid. `gen:call` fails with `noproc`, sys wraps it to `{noproc, {sys, terminate, _}}` (sys.erl:757-763), `:proc_lib.stop/3` re-raises the bare `exit(noproc)` (proc_lib.erl:1586-1589), and `GenServer.stop/3` wraps it as it wraps the timeout (gen_server.ex:1085-1090). `catch :exit, {:timeout, _}` does not match, so the owner died mid-shutdown with no class, no status and the socket left behind. The clause is now two, with `:exit, {:noproc, _} -> :already_gone`. The wait after each stop consumes the exit on `:ok` and on the kill, where it is the owner's own doing, and **classifies** it on `:noproc`, where the component died before being asked — first class wins. Nothing is lost without draining the mailbox, because a component that dies during the sequence always has its own step still ahead of it. "Known dead" now means "its exit has been consumed or the stop raised noproc", not "was classified before the sequence began". The mid-sequence witness asserts the sequence completes, the socket is unlinked and the exit is `store_lost` on `stderr`. T2: the selective receive carries no `after`, sits outside the composed grace, and terminates in all three endings because the exit it waits for is guaranteed to exist — stated in the step and beside the bounds table. T3: the fail-stop path stops neither the runtime root, the lease owner nor the transfers owner, and says why: a fail-stop is not a drain, none of the three owns anything outliving the VM, and on `executor_lost` no executor is left to read the lease holder's DOWN. T4: supervisor.ex is :1152-1154 at the floor pair and :1197-1199 at the current pair; gen_server.ex:1076-1092 is identical at both. T5: the transfers owner is absent when artifact transfers are disabled, so its bounds row and its step exist only where that pid does. --- docs/plans/M5-technical.md | 127 ++++++++++++++++++++++++++++++------- 1 file changed, 104 insertions(+), 23 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index e75b2dead..8050c0ba0 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -783,15 +783,58 @@ reads: the operator is owed the real reason rather than `operator_stop`. **The field is cleared by that exit, not by the call returning**, and the -distinction is not pedantry. A stop can end three ways — `:ok`, a caught -timeout followed by `Process.exit(pid, :kill)`, or the component having died -already — and in the first two the exit signal is still on its way when the -call returns; whether it or the monitor's `DOWN` arrives first is not ordered -for us. So after each stop the owner waits for that exact pid's exit, in a -selective receive it can only reach because the process is dead either way, -and only then names the next component. Messages that arrive meanwhile stay -in the mailbox and are classified when the owner returns to its loop; nothing -is skipped, only ordered. +distinction is not pedantry. A stop can end three ways, and the owner catches +two of them: + +| How the stop ends | What the owner sees | What it does | +| --- | --- | --- | +| The component stopped | `:ok` | Wait for its exit | +| It did not stop in time | `exit {:timeout, {GenServer, :stop, [pid, :normal, grace]}}` | `Process.exit(pid, :kill)`, then wait for its exit | +| **It was already dead** | `exit {:noproc, {GenServer, :stop, [pid, :normal, grace]}}` | Nothing to kill; read the exit already queued and **classify** it | + +The third row is the one an earlier draft got wrong, and it is not +hypothetical: it is exactly what a component that died *during* the sequence +produces. The owner does not read its mailbox while stopping, so that +component's `{:EXIT, …}` is still queued and unread when the sequence reaches +its step; the pid is dead; and `GenServer.stop/3` on a dead pid raises rather +than returning. `sys:terminate/3`'s `gen:call` fails with `noproc` and is +wrapped to `{noproc, {sys, terminate, _}}` (sys.erl:757-763), which +`:proc_lib.stop/3` catches and re-raises as the bare `exit(noproc)` +(proc_lib.erl:1586-1589), which `GenServer.stop/3` wraps exactly as it wraps +the timeout (gen_server.ex:1085-1090). A `catch :exit, {:timeout, _}` alone +does **not** match it, so the owner would die of `noproc` in the middle of its +own shutdown: no class on `stderr`, no status, the socket never unlinked. The +clause is therefore two, not one: + +```elixir +try do + GenServer.stop(pid, :normal, grace) +catch + :exit, {:timeout, _} -> Process.exit(pid, :kill) + :exit, {:noproc, _} -> :already_gone +end +``` + +After each of the three the owner waits for that exact pid's exit, in a +selective receive. That wait terminates in every row: on `:ok` and on the kill +the signal is already on its way — whether it or the monitor's `DOWN` arrived +first is not ordered for us, which is why the wait exists — and on +`:already_gone` it is already in the mailbox, which is how it got there. + +**What the wait does with that exit differs by row, and this is where the +class is saved.** On `:ok` and on the kill the exit is the owner's own doing, +so it is consumed. On `:already_gone` it is not: the component died before the +owner asked it to, which is the whole meaning of `noproc`, so the wait +**classifies** that exit exactly as the loop's clause would — first class +wins — and only then clears `stopping` and moves on. + +That is enough to lose nothing, without draining the mailbox before the halt, +because of one invariant: **a component that dies during the sequence always +has its own step still ahead of it.** A component whose step has passed is +already stopped and cannot die a second time; so every unexpected death meets +its own step, and meets it as `noproc`. Other messages sit unread meanwhile +and are read when the owner returns to its loop; nothing is skipped, only +ordered. Two consequences the sequences below depend on, stated here once: @@ -801,9 +844,13 @@ Two consequences the sequences below depend on, stated here once: first class recorded wins; a later one does not overwrite it, so the operator gets the reason the daemon went down for rather than the last thing that happened on the way out. -- **A component already known dead is not stopped again.** Its exit was - classified, so the owner holds that fact; the step for it is a no-op rather - than a call on a dead pid. +- **"Already dead" is something the owner learns, not something it knows.** + A component is known dead when its exit has been consumed — classified + before the sequence began, or read by the wait after `:already_gone`. It is + never assumed from a class recorded earlier in the same sequence, because + the unread `{:EXIT, …}` and the `noproc` are how the owner finds out, and + both are handled rather than avoided. A component that died before the + sequence started and was classified then is simply skipped. One field, one place, and it is what makes the two paths distinguishable at all. Both sequences below rely on it, and the idle-shutdown witness asserts @@ -885,12 +932,13 @@ chooses. **What a timeout does, read from the installed stdlib rather than assumed — and the chain is not the obvious one.** `Supervisor.stop/3` is - `GenServer.stop(supervisor, reason, timeout)` (supervisor.ex:1152-1154), + `GenServer.stop(supervisor, reason, timeout)` (supervisor.ex:1152-1154 at + the floor pair, :1197-1199 at the current pair), and `GenServer.stop/3` calls **`:proc_lib.stop/3` directly**, not `:gen.stop/3`, wrapping any exit it catches: `catch :exit, err -> exit({err, {__MODULE__, :stop, [server, reason, - timeout]}})` (gen_server.ex:1076-1092, identical in both floor pairs, - 1.18.5-otp-27 and 1.20.3-otp-29). Beneath that wrapper, + timeout]}})` (gen_server.ex:1076-1092, identical at the floor pair and the + current pair, 1.18.5-otp-27 and 1.20.3-otp-29). Beneath that wrapper, `:proc_lib.stop/3` monitors the target, calls `sys:terminate/3`, and on expiry — from `sys:terminate` raising `exit:{timeout, {sys, terminate, _}}` or from its own `after RemainingTimeout` — demonitors and calls the @@ -953,7 +1001,8 @@ chooses. executor first, since it is the one with OS effects to clean up and it traps exits to do so. Then the Store, whose `terminate/2` releases the writer marker — see the marker invariant in ADR 0031. Finally the socket - path is unlinked and the owner **halts with `0`**. + path is unlinked and the owner **halts with `0`** — or with the class, in + the case above where something failed on the way out. **The executor is stopped before the lease, and that order is load-bearing** rather than alphabetical. The executor privately monitors the lease holder @@ -982,7 +1031,23 @@ chooses. fractions would mean inventing ratios, and the minimalism budget takes every number from an accepted or proposed decision. Three of the four are ceilings rather than expected waits; only the executor is expected to spend - real time here. + real time here. **The transfers owner exists only when artifact transfers + were enabled**, as the composed set above says (`transfers` is listed there + as absent when disabled); where it is absent its row is not a stop the + owner skips at runtime so much as a pid it never held, and the step for it + does not exist in that daemon's sequence at all. + + **What bounds the wait after each stop: nothing, and that is the safe + answer.** The selective receive that follows a stop carries no `after`, so + it is outside the composed grace and adds no second bound to reason about. + It terminates in all three endings because the exit it waits for is + guaranteed to exist: on `:ok` the component has terminated and the signal + is in flight, on the timeout the owner's own `Process.exit(pid, :kill)` + guarantees one, and on `:noproc` it is already in the mailbox — the owner + only attempts a stop for a component whose exit it has not already + consumed, so a dead pid means an unread exit. An `after` here would be a + number with no failure to catch, and it would turn a guaranteed signal into + a second thing that can go wrong. **A killed executor is the residual, and the plan states it rather than explaining it away.** The kill by itself is not the leak. The executor @@ -1096,7 +1161,16 @@ to write. and found dead, refuses with `store_writer_unverifiable` where it cannot be decided, and refuses with `store_writer_active` where it is alive. A surviving marker is a case with a defined answer, not a corruption. -5. Unlink the socket. +5. Unlink the socket. **The runtime root, the lease owner and the transfers + owner are not stopped on this path**, and that is deliberate rather than an + omission. A fail-stop is not a drain, and none of the three owns anything + that outlives the VM: the executor does, which is why step 3 exists, and + the Store holds the marker, which is why step 4 does, while the transfers + owner's open descriptors are closed by the operating system when the VM + goes. Stopping the lease owner would buy less here than on the ordered + path, where the point was to stop the executor before it — on + `executor_lost` there is no executor left to read the lease holder's `DOWN` + at all. 6. Write the class on `stderr`, then **halt with the non-zero status** for that class. Nothing restarts anything: the owner `start_link`s its seven and restarts none, so an exit it did not cause is fatal by its own clause — @@ -1200,11 +1274,18 @@ what lets an operator fix the cause and try again without a recovery step. at any point during the stop**, and nothing appears on `stderr` — stopping seven linked processes deliberately produces seven exits, and every one of them must be consumed rather than classified. -- **A real failure during an orderly stop is still classified.** The Store is - made to fail while the listener is being stopped. The daemon exits with - `store_lost`, not `operator_stop`, because the Store is not the component - named in `stopping` — the operator is owed the reason the daemon actually - went down for. +- **A real failure during an orderly stop is still classified, and the + sequence still finishes.** The Store is made to fail while the listener is + being stopped. The case asserts three things, because the second and third + are what an earlier draft would have failed: the daemon exits with + `store_lost` rather than `operator_stop`, since the Store is not the + component named in `stopping` and the operator is owed the reason it + actually went down for; **the sequence runs to its end**, reaching the + Store's own step — where the stop raises `noproc` and is caught — then + unlinking the socket; and the class reaches `stderr` with a non-zero exit + rather than the owner dying of `noproc` with no status, no message and a + socket file left behind. A second daemon opens the same root immediately + afterwards, which is what proves the path completed. - **In-flight shutdown.** A daemon with a dispatched tool effect and an unresolved mutation receives `SIGTERM`. What has not settled within the cleanup grace is ended crash-equivalently, and the case asserts the negative From d2f7977aad9fcf4df4353dd5361c48604fbd7f0e Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:53:39 -0700 Subject: [PATCH 061/585] plan(M5): catch a component dying of its own reason mid-stop U1: `:proc_lib.stop/3` binds `Reason` from its function head, so a target that dies of anything other than the reason asked for takes the second DOWN clause and `exit(Reason2)` (proc_lib.erl:1597-1600 at the floor pair, :1612-1615 at the current pair); `GenServer.stop/3` wraps it like the others. Reproduced here at the current pair: a trapping GenServer whose `terminate/2` exits `{:badthing, :during_cleanup}`, stopped under the two-clause catch, killed the caller; under a three-clause catch it returned `:already_gone` with `{:EXIT, pid, {:badthing, :during_cleanup}}` already queued. Reachable at the executor, the Store and the runtime root. The third clause is a catch-all, since the component's own reason is whatever it had; the only other shape `GenServer.stop/3` raises is `{:calling_self, _}`, which the owner never produces. The wait classifies that exit rather than consuming it, the invariant gains its third branch, and a witness covers a `terminate/2` that fails mid-sequence: the sequence completes and the class is `transfers_lost`. U2: three ways becomes four, in the prose and in the stop-ending table. U3: M5.md said only an observer meets `session_dormant`; both roles do, and `--take-over` releases the lease it acquired before exiting, so the remedy it names is not blocked by that lease. U4: the selective receive carries no `after` and sits outside the composed cleanup grace, stated where the wait is defined as well as at the bounds table. U5: each catch branch returns a tag -- `:ok`, `{:killed, pid}`, `:already_gone` -- so the wait rule reads as one line with no case analysis left in it. Also corrected a citation of my own: gen_server.ex:1076-1092 is the floor pair only; the same code is :1131-1147 at the current pair. --- docs/plans/M5-technical.md | 135 ++++++++++++++++++++++++------------- docs/plans/M5.md | 6 +- 2 files changed, 92 insertions(+), 49 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8050c0ba0..1da29b2d5 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -783,58 +783,92 @@ reads: the operator is owed the real reason rather than `operator_stop`. **The field is cleared by that exit, not by the call returning**, and the -distinction is not pedantry. A stop can end three ways, and the owner catches -two of them: +distinction is not pedantry. **A stop can end four ways**, and the owner +catches three of them. Each branch returns a tag, so the wait that follows +reads mechanically rather than by re-deriving what happened: -| How the stop ends | What the owner sees | What it does | -| --- | --- | --- | -| The component stopped | `:ok` | Wait for its exit | -| It did not stop in time | `exit {:timeout, {GenServer, :stop, [pid, :normal, grace]}}` | `Process.exit(pid, :kill)`, then wait for its exit | -| **It was already dead** | `exit {:noproc, {GenServer, :stop, [pid, :normal, grace]}}` | Nothing to kill; read the exit already queued and **classify** it | - -The third row is the one an earlier draft got wrong, and it is not -hypothetical: it is exactly what a component that died *during* the sequence -produces. The owner does not read its mailbox while stopping, so that -component's `{:EXIT, …}` is still queued and unread when the sequence reaches -its step; the pid is dead; and `GenServer.stop/3` on a dead pid raises rather -than returning. `sys:terminate/3`'s `gen:call` fails with `noproc` and is -wrapped to `{noproc, {sys, terminate, _}}` (sys.erl:757-763), which -`:proc_lib.stop/3` catches and re-raises as the bare `exit(noproc)` -(proc_lib.erl:1586-1589), which `GenServer.stop/3` wraps exactly as it wraps -the timeout (gen_server.ex:1085-1090). A `catch :exit, {:timeout, _}` alone -does **not** match it, so the owner would die of `noproc` in the middle of its -own shutdown: no class on `stderr`, no status, the socket never unlinked. The -clause is therefore two, not one: +| How the stop ends | What the owner sees | What it does | Tag | +| --- | --- | --- | --- | +| The component stopped | `:ok` | Wait for its exit | `:ok` | +| It did not stop in time | `exit {:timeout, {GenServer, :stop, [pid, :normal, grace]}}` | `Process.exit(pid, :kill)`, then wait | `{:killed, pid}` | +| **It was already dead** | `exit {:noproc, {GenServer, :stop, [pid, :normal, grace]}}` | Nothing to kill; wait for the exit already queued | `:already_gone` | +| **It died of its own reason while stopping** | `exit {reason, {GenServer, :stop, [pid, :normal, grace]}}` for any other `reason` | Nothing to kill; wait for the exit its own death queued | `:already_gone` | + +The wait then has one rule with no case analysis left in it: **`:ok` and +`{:killed, pid}` are the owner's own doing, so the exit is consumed; +`:already_gone` is not, so the exit is classified** — first class wins — and +either way `stopping` is cleared before the next component is named. + +The last two rows are the ones earlier drafts got wrong, and neither is +hypothetical. The owner does not read its mailbox while stopping, so a +component that dies during the sequence has its `{:EXIT, …}` queued and unread +when the sequence reaches its step, and `GenServer.stop/3` raises rather than +returning: + +- **Already dead.** `sys:terminate/3`'s `gen:call` fails with `noproc` and is + wrapped to `{noproc, {sys, terminate, _}}` (sys.erl:757-763), which + `:proc_lib.stop/3` catches and re-raises as the bare `exit(noproc)` + (proc_lib.erl:1586-1589). +- **Dying of its own reason during its own stop.** `sys:terminate/3` succeeds, + and `:proc_lib.stop/3` then waits on its monitor with `Reason` **bound from + the function head** to the reason it was asked for. A `DOWN` carrying + anything else falls to the second clause, `exit(Reason2)` + (proc_lib.erl:1597-1600 at the floor pair, :1612-1615 at the current pair). + So a component whose `terminate/2` fails, or that was already terminating + for its own reason, ends the stop with *its* reason rather than `:normal`. + Verified by execution at the current pair: a trapping `GenServer` whose + `terminate/2` exits `{:badthing, :during_cleanup}`, stopped under the + two-clause catch, killed the caller — + `** (exit) exited in: GenServer.stop(…) ** (EXIT) {:badthing, + :during_cleanup}` — and under the three-clause catch returned + `:already_gone` with `{:EXIT, pid, {:badthing, :during_cleanup}}` waiting in + the mailbox, which is exactly the exit the wait then classifies. + +`GenServer.stop/3` wraps all three the same way (gen_server.ex:1076-1092 at +the floor pair, :1131-1147 at the current pair), and a catch matching only +`{:timeout, _}` matches none of them: the owner would die mid-shutdown with no +class on `stderr`, no status and the socket never unlinked. The clause is +therefore three, and the third is deliberately a catch-all, because the +component's own reason is whatever the component had. The breadth costs +nothing it should keep: the only other shape `GenServer.stop/3` raises is +`{:calling_self, _}`, and the owner passes a child's pid, never its own. ```elixir try do GenServer.stop(pid, :normal, grace) + :ok catch - :exit, {:timeout, _} -> Process.exit(pid, :kill) - :exit, {:noproc, _} -> :already_gone + :exit, {:timeout, _} -> + Process.exit(pid, :kill) + {:killed, pid} + + :exit, {:noproc, _} -> + :already_gone + + :exit, _other -> + :already_gone end ``` -After each of the three the owner waits for that exact pid's exit, in a -selective receive. That wait terminates in every row: on `:ok` and on the kill -the signal is already on its way — whether it or the monitor's `DOWN` arrived -first is not ordered for us, which is why the wait exists — and on -`:already_gone` it is already in the mailbox, which is how it got there. - -**What the wait does with that exit differs by row, and this is where the -class is saved.** On `:ok` and on the kill the exit is the owner's own doing, -so it is consumed. On `:already_gone` it is not: the component died before the -owner asked it to, which is the whole meaning of `noproc`, so the wait -**classifies** that exit exactly as the loop's clause would — first class -wins — and only then clears `stopping` and moves on. +After each of the four the owner waits for that exact pid's exit, in a +selective receive. **That receive carries no `after`**, so it sits outside the +composed cleanup grace and adds no second bound to reason about; it terminates +in every row because the exit it waits for is guaranteed to exist — on `:ok` +the component has terminated and the signal is in flight, on the timeout the +owner's own kill guarantees one, and on both `:already_gone` rows it is +already in the mailbox, which is how the owner found out. Whether the exit or +the monitor's `DOWN` reached the owner first is not ordered for us, which is +why the wait exists at all. That is enough to lose nothing, without draining the mailbox before the halt, because of one invariant: **a component that dies during the sequence always has its own step still ahead of it.** A component whose step has passed is -already stopped and cannot die a second time; so every unexpected death meets -its own step, and meets it as `noproc`. Other messages sit unread meanwhile -and are read when the owner returns to its loop; nothing is skipped, only -ordered. +already stopped and cannot die a second time. So every unexpected death meets +its own step, and meets it in one of three ways: classified before the +sequence began, as `noproc` where it died earlier in the sequence, or as its +own reason where it died during its own step. Other messages sit unread +meanwhile and are read when the owner returns to its loop; nothing is skipped, +only ordered. Two consequences the sequences below depend on, stated here once: @@ -1040,14 +1074,14 @@ chooses. **What bounds the wait after each stop: nothing, and that is the safe answer.** The selective receive that follows a stop carries no `after`, so it is outside the composed grace and adds no second bound to reason about. - It terminates in all three endings because the exit it waits for is - guaranteed to exist: on `:ok` the component has terminated and the signal - is in flight, on the timeout the owner's own `Process.exit(pid, :kill)` - guarantees one, and on `:noproc` it is already in the mailbox — the owner - only attempts a stop for a component whose exit it has not already - consumed, so a dead pid means an unread exit. An `after` here would be a - number with no failure to catch, and it would turn a guaranteed signal into - a second thing that can go wrong. + It terminates in all four endings, for the reason the stop-ending table + above gives: the exit it waits for is guaranteed to exist, in flight on + `:ok`, guaranteed by the owner's own kill on the timeout, and already in + the mailbox on both `:already_gone` rows — the owner only attempts a stop + for a component whose exit it has not already consumed, so a stop that + raises means an unread exit. An `after` here would be a number with no + failure to catch, and it would turn a guaranteed signal into a second thing + that can go wrong. **A killed executor is the residual, and the plan states it rather than explaining it away.** The kill by itself is not the leak. The executor @@ -1286,6 +1320,13 @@ what lets an operator fix the cause and try again without a recovery step. rather than the owner dying of `noproc` with no status, no message and a socket file left behind. A second daemon opens the same root immediately afterwards, which is what proves the path completed. +- **A component that fails while it is being stopped.** The transfers owner + is made to raise in its own `terminate/2` during an orderly stop, so its + stop returns that reason rather than `:normal` and the two-clause catch + would have killed the owner. The case asserts the sequence completes — the + Store still stopped, the socket still unlinked — and that the exit class is + `transfers_lost` rather than `operator_stop`, because the component died of + its own reason and not because the owner asked. - **In-flight shutdown.** A daemon with a dispatched tool effect and an unresolved mutation receives `SIGTERM`. What has not settled within the cleanup grace is ended crash-equivalently, and the case asserts the negative diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 8a4f93fc8..136573287 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -330,8 +330,10 @@ a fresh command ID and attach, and `loopex attach` joins one that is already activated — as an observer, or as a one-shot controller with `--take-over`. There is no interactive multi-turn controller in M5, which is a restriction stated rather than an omission: driving many turns is what the `run` and -`resume` forms already do. Attaching never activates, so an observer meets -`session_dormant` and is told to resume. A reconnecting controller acquires +`resume` forms already do. Attaching never activates, so a client meets `session_dormant` +in either role and is told to resume — and `--take-over`, which acquires +before it attaches, releases that lease before exiting, so the remedy it names +is not blocked by the lease it just took. A reconnecting controller acquires again and receives a fresh epoch before any further mutation. The released offline `loopex sessions`, `run` and `resume` are unchanged, and each live form is a separate explicit `--daemon` form of them. From bc3a5ed035a3881b1fe3715d1c1d6bf7e81b33e2 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 22:57:42 -0700 Subject: [PATCH 062/585] plan(M5): guard the timeout branch against a bare :timeout death N1: a component dying with the bare atom `:timeout` during its own stop wraps to `{:timeout, {GenServer, :stop, [pid, :normal, grace]}}`, byte for byte what `:proc_lib.stop/3` raises when its own wait expires. Unguarded, the owner would kill a dead pid, tag `{:killed, pid}`, and the wait would consume that component's exit as its own doing -- class lost, exit `0` on a failure. The branch now asks `Process.alive?(pid)`: alive means a real timeout and the kill ends the tree; dead means it died of that atom, the exit is queued, and the tag is `:already_gone` so the wait classifies it. Unreachable with the seven composed today -- their reasons are tuples, and a `{:timeout, {GenServer, :call, ...}}` death is tuple-headed and reaches the catch-all -- so the guard is for the lease owner and the listener M5 writes, with the rule stated beside it: no daemon component exits with the bare atom `:timeout`. N2: both pairs cited for the remaining floor-only lines -- sys.erl:757-763 floor and :756-762 current, proc_lib.erl:1586-1589 floor and :1599-1601 current. N3: one clause says the last three table rows share a tag because the owner's response to all three is the same -- it killed nothing, so the exit is not its own doing. --- docs/plans/M5-technical.md | 53 +++++++++++++++++++++++++++++--------- 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 1da29b2d5..7b134ceb6 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -784,31 +784,38 @@ reads: **The field is cleared by that exit, not by the call returning**, and the distinction is not pedantry. **A stop can end four ways**, and the owner -catches three of them. Each branch returns a tag, so the wait that follows -reads mechanically rather than by re-deriving what happened: +catches three of them — and one of those shapes can mean two different +things, which is why one branch carries a guard. Each branch returns a tag, +so the wait that follows reads mechanically rather than by re-deriving what +happened: | How the stop ends | What the owner sees | What it does | Tag | | --- | --- | --- | --- | | The component stopped | `:ok` | Wait for its exit | `:ok` | -| It did not stop in time | `exit {:timeout, {GenServer, :stop, [pid, :normal, grace]}}` | `Process.exit(pid, :kill)`, then wait | `{:killed, pid}` | +| It did not stop in time | `exit {:timeout, {GenServer, :stop, [pid, :normal, grace]}}` | `Process.alive?(pid)` first: alive, so `Process.exit(pid, :kill)`, then wait | `{:killed, pid}` | +| It died **of the bare atom** `:timeout` | the same shape — the two are indistinguishable | `Process.alive?(pid)` is false, so nothing to kill; wait | `:already_gone` | | **It was already dead** | `exit {:noproc, {GenServer, :stop, [pid, :normal, grace]}}` | Nothing to kill; wait for the exit already queued | `:already_gone` | | **It died of its own reason while stopping** | `exit {reason, {GenServer, :stop, [pid, :normal, grace]}}` for any other `reason` | Nothing to kill; wait for the exit its own death queued | `:already_gone` | +The last three rows share one tag because the owner's response to them is the +same: it killed nothing, so the exit waiting for it is not its own doing. + The wait then has one rule with no case analysis left in it: **`:ok` and `{:killed, pid}` are the owner's own doing, so the exit is consumed; `:already_gone` is not, so the exit is classified** — first class wins — and either way `stopping` is cleared before the next component is named. -The last two rows are the ones earlier drafts got wrong, and neither is +Those same three are what earlier drafts got wrong, and none of them is hypothetical. The owner does not read its mailbox while stopping, so a component that dies during the sequence has its `{:EXIT, …}` queued and unread when the sequence reaches its step, and `GenServer.stop/3` raises rather than returning: - **Already dead.** `sys:terminate/3`'s `gen:call` fails with `noproc` and is - wrapped to `{noproc, {sys, terminate, _}}` (sys.erl:757-763), which - `:proc_lib.stop/3` catches and re-raises as the bare `exit(noproc)` - (proc_lib.erl:1586-1589). + wrapped to `{noproc, {sys, terminate, _}}` (sys.erl:757-763 at the floor + pair, :756-762 at the current pair), which `:proc_lib.stop/3` catches and + re-raises as the bare `exit(noproc)` (proc_lib.erl:1586-1589 at the floor + pair, :1599-1601 at the current pair). - **Dying of its own reason during its own stop.** `sys:terminate/3` succeeds, and `:proc_lib.stop/3` then waits on its monitor with `Reason` **bound from the function head** to the reason it was asked for. A `DOWN` carrying @@ -833,14 +840,36 @@ component's own reason is whatever the component had. The breadth costs nothing it should keep: the only other shape `GenServer.stop/3` raises is `{:calling_self, _}`, and the owner passes a child's pid, never its own. +**The timeout branch is guarded, because one reason collides with it.** A +component that dies with the *bare atom* `:timeout` during its own stop wraps +to `{:timeout, {GenServer, :stop, [pid, :normal, grace]}}` — byte for byte +what `:proc_lib.stop/3` raises when its own wait expires. Unguarded, the owner +would kill an already-dead pid, tag the branch `{:killed, pid}`, and the wait +would *consume* that component's exit as its own doing: the class lost and the +daemon exiting `0` on a failure. So the branch asks `Process.alive?(pid)` +first — alive means a real timeout and the kill is the only thing that ends +the tree; dead means the component died of that atom, the exit is already +queued, and the tag is `:already_gone` so the wait classifies it. No component +composed today reaches this: their reasons are tuples — `{:store_capacity_exceeded, N}`, +a `File.close` error, a crash tuple, `:shutdown` — and even a death by +`{:timeout, {GenServer, :call, …}}` is tuple-headed and lands on the catch-all +correctly. The guard is for the two components M5 itself writes, and the rule +that goes with it is stated here so it is not discovered later: **no daemon +component exits with the bare atom `:timeout`**; the lease owner and the +listener report an expiry or a refusal as a tagged reason. + ```elixir try do GenServer.stop(pid, :normal, grace) :ok catch :exit, {:timeout, _} -> - Process.exit(pid, :kill) - {:killed, pid} + if Process.alive?(pid) do + Process.exit(pid, :kill) + {:killed, pid} + else + :already_gone + end :exit, {:noproc, _} -> :already_gone @@ -850,7 +879,7 @@ catch end ``` -After each of the four the owner waits for that exact pid's exit, in a +After every one of them the owner waits for that exact pid's exit, in a selective receive. **That receive carries no `after`**, so it sits outside the composed cleanup grace and adds no second bound to reason about; it terminates in every row because the exit it waits for is guaranteed to exist — on `:ok` @@ -1074,8 +1103,8 @@ chooses. **What bounds the wait after each stop: nothing, and that is the safe answer.** The selective receive that follows a stop carries no `after`, so it is outside the composed grace and adds no second bound to reason about. - It terminates in all four endings, for the reason the stop-ending table - above gives: the exit it waits for is guaranteed to exist, in flight on + It terminates in every row of the stop-ending table above, for the reason + that table gives: the exit it waits for is guaranteed to exist, in flight on `:ok`, guaranteed by the owner's own kill on the timeout, and already in the mailbox on both `:already_gone` rows — the owner only attempts a stop for a component whose exit it has not already consumed, so a stop that From 01c61065f05537eadc0189d77fd65810ea831841 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 23:48:23 -0700 Subject: [PATCH 063/585] plan(M5): rebuild the daemon lifecycle on observed exits P0-A: socket ownership is derived from the writer marker, so it ends when the marker does. The orderly stop unlinks in step 1, while the marker is still held, instead of after the Store released it; the fail-stop, where the marker is already gone, unlinks only when the path's `File.stat` device and inode equal the pair captured at bind. Probe: a bound unix socket stats with an inode, a rebind of the same path yields a different one, a removed path answers `{:error, :enoent}`. The stat-then-unlink window is stated as the residual; a second daemon-owned lock file is rejected as duplicating the marker's stale-writer machinery. `--socket` must resolve inside the selected root's `daemon/` directory, else `invalid_socket_path`, because two roots hold two markers and have no exclusion between them. P1-C: the owner never calls `GenServer.stop/3` itself. At a 1 ms cleanup grace -- which `executor.ex:897` validates as composable -- the call raises `ErlangError`/`:timeout_value` rather than exiting, so no `catch :exit` clause runs and the owner dies; observed at both toolchain pairs, together with `Process.alive?` answering true for a component that had in fact exited `:normal`. Each stop is now a monitored helper, and classification comes only from the exit reason the owner observes on its own link: `:normal`, `:shutdown` and the owner's own `:killed` consumed, everything else classified. The four-row catch table, the shape clauses, the `Process.alive?` guard and the bare-`:timeout` rule are withdrawn. Signals are specified against `interrupt.ex`: `:sigint` cannot be installed on (:13-17), so it is the launcher's route (bin/loopex:51-60) while the daemon installs `SIGTERM` via `:os.set_signal/2` (:782), the `:erl_signal_server` handler (:806, :818) and removal of the default (:870-873) -- before the marker, so no default-handler exit can strand it. `owner_lost` halts when a signal finds no owner. P1-D: the linked set is nine with transfers enabled and eight without, and includes ADR 0034's registry and custody processes, which the daemon owns because the daemon is the host. They start first, since the model options carry the handle, and stop just before the Store. `registry_lost` and `custody_lost` join the fatal map, whose rows are now named rather than numbered. P1-E: startup follows the composition seam -- signal handlers, registry and custody, the one composition call, the directory read, lease owner, socket, readiness -- and reverse cleanup stops every returned edge in reverse start order under the same helper discipline. The cost is stated: a directory refusal now happens after the workspace lease was taken and released. A staged two-function seam is rejected. --- docs/plans/M5-technical.md | 728 +++++++++++++++++++++++-------------- 1 file changed, 461 insertions(+), 267 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 7b134ceb6..ae4b9db9d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -494,11 +494,21 @@ possible, so the common operator mistake costs nothing and leaves nothing behind; the ones that can only fail later are covered by the reverse-cleanup rule. -A `--socket` override is constrained exactly as the default is: its parent +A `--socket` override is constrained exactly as the default is — its parent directory must be owned by the daemon's user and mode `0700`, no component below the state root may be a symbolic link the daemon did not create, and the -socket is created `0600` and verified after bind. An override does not buy a -weaker rule; it only moves where the rule applies. +socket is created `0600` and verified after bind — **and it must resolve +inside the selected root's `daemon/` directory**. A path outside it is refused +at startup with `invalid_socket_path`, before the marker is acquired. + +That last constraint is not tidiness. Socket ownership in this design is +derived from the writer marker, and a marker is per state root: two daemons on +two different roots hold two different markers and have no exclusion between +them at all. An override that let them name one path would put two daemons +with equal claim on one file, which no rule in this plan can adjudicate. +Inside one root there is exactly one marker holder, so there is exactly one +daemon entitled to bind or unlink. An override therefore moves where the rule +applies, never which root it applies within. **Readiness.** Exactly one line on `stdout`, and nothing else on that stream. It is **one JSON object on one line**, not a space-separated phrase, because a @@ -526,10 +536,22 @@ carry and this milestone does not grant. **Exit status.** `0` when an orderly shutdown completes, whatever the sessions were doing. Non-zero, with one reason line on `stderr`, for every fatal exit, -naming its class rather than a stack: `store_writer_active`, -`store_writer_unverifiable`, `store_log_too_large`, `socket_path_too_long`, -`socket_permission_unverified`, `session_index_too_large`, `store_lost`, and -`supervision_fault` for the daemon-fatal rules ADR 0032 and ADR 0033 define. +naming its class rather than a stack. The classes are the fatal-class map's, +in full, and this list is derived from it rather than summarising it: + +- **at startup**, before any socket exists: `store_writer_active`, + `store_writer_unverifiable`, `store_log_too_large`, `socket_path_too_long`, + `invalid_socket_path`, `socket_permission_unverified`, + `session_index_too_large`, and one class per missing or invalid composition + input; +- **while running**, one per linked component: `store_lost`, + `store_capacity_exceeded`, `runtime_lost`, `transfers_lost`, + `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, + `supervision_fault` for the lease owner — the daemon-fatal rule ADR 0033 + defines — and `listener_lost`; +- **from the signal handler**, `owner_lost`, the one class no component + produces: a signal arrived and the owner that would run the shutdown is not + there to receive it. #### How a session is created and driven over the socket @@ -674,15 +696,45 @@ Outcome 1 requires that an orderly stop and an abrupt death both leave only what the journal proves. That is a claim about a sequence, so the sequence is written out rather than left implied by the words "foreground process". -**Startup, in order.** Resolve root and socket path; open the Store and -acquire the writer marker, with `recover_stale_writer: true` and the three -holder outcomes ADR 0032 fixes; read the session directory and build the -index, refusing at the recorded-entry bound; create the `0700` subdirectory -and bind the `0600` socket, then read back and verify ownership and mode; -begin accepting; print the readiness line. A failure at any step exits -non-zero with that step's reason class and touches nothing after it — in -particular, a daemon that does not hold the marker never reads, unlinks or -binds the socket path. +**Startup, in order.** The order is written against the seam that actually +exists — one composition function that assembles every edge and ends with the +runtime — rather than against a staged one the plan would have to invent: + +1. **Resolve root and socket path**, including the `--socket` constraint + below; a path outside the root's `daemon/` directory is refused here with + `invalid_socket_path`, before anything is acquired. +2. **Install the signal handlers**, for the reason the signal section gives: + before this, the default handler would stop the VM outright and strand + whatever the next steps take. +3. **Start the credential routing registry and the custody process.** They are + the daemon's own, as ADR 0034's host, and they must exist before the model + configuration that carries the registry handle and the token is built. +4. **Call the composition function**, which opens the Store and acquires the + writer marker with `recover_stale_writer: true` and the three holder + outcomes ADR 0032 fixes, then assembles the artifact transfers owner where + enabled, the workspace lease, the executor and the runtime, and returns + every pid it linked. A daemon that does not hold the marker fails here and + never reads, unlinks or binds the socket path. +5. **Read the session directory and build the index**, refusing at the + recorded-entry bound. +6. **Start the lease owner.** +7. **Create the `0700` subdirectory and bind the `0600` socket**, read back + and verify ownership and mode, and **capture the bound path's device and + inode** — the identity the fail-stop unlink rule below compares against. +8. **Begin accepting**, then **print the readiness line**. + +A failure at any step exits non-zero with that step's reason class, after the +reverse cleanup below, and touches nothing after it. + +**One cost of matching the seam is stated rather than hidden.** The directory +and index read is step 5, after the composition function has already taken the +workspace lease and started the executor, so a root whose directory exceeds +the recorded-entry bound is now refused *after* those were taken and released +rather than before they were taken. Nothing durable is at risk — the reverse +cleanup below releases them in order — and the alternative was worse: a staged +seam, two public composition functions where one suffices, so that the daemon +could interleave its own step between them. That is rejected; the minimalism +budget does not buy a second public function to reorder a refusal. **The daemon's top-level component is an owner process, not a supervisor.** That is a decision this section has to make before it can describe any @@ -715,35 +767,51 @@ So `apps/loopex_daemon` has one top-level process, `Loopex.Daemon.Owner`, a `GenServer` that traps exits and holds the links itself — the same pattern `RuntimeOwner` already uses, for the same reason. -**It links seven processes, not four.** An earlier draft of this section said -four, having counted the components the daemon *thinks* about rather than the -processes composition actually starts. Because the new composition function -runs the edge-assembly chain in the caller's process, every `start_edge/2` in -that chain links the owner — five of them — and the daemon adds two of its -own: +**It links nine processes when artifact transfers are enabled, eight when +they are not.** Earlier drafts said four and then seven, each time having +counted the components the daemon *thinks* about rather than the processes +that actually exist. The set is fixed — nothing here is started dynamically, +per session or on demand — and it is this: -| # | Linked process | Where it comes from | Optional? | +| Start order | Linked process | Where it comes from | Optional? | | --- | --- | --- | --- | -| 1 | The Store adapter | `start_edge(Store.Local, …)` | no | -| 2 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | -| 3 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | -| 4 | The local executor | `start_edge(Local, …)` | no | -| 5 | The runtime root | `start_edge(Loopex, …)` | no | -| 6 | The lease owner | The daemon's own, under ADR 0033 | no | -| 7 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | - -The numbering is the composition's actual start order, not a tidied one: the -Store first, then the artifact placement and the executor's own edges, and the -runtime **last**, because it is the thing that depends on all of them. Reverse -that and the shutdown order falls out — listener, lease owner, runtime, -executor, workspace lease, transfers, Store — with the runtime stopping before -the executor it drives and the Store stopping after everything that could -still have written to it. +| 1 | The credential **routing registry** | The daemon's own, as the host ADR 0034 names | no | +| 2 | The credential **custody process** | The daemon's own, as the host ADR 0034 names | no | +| 3 | The Store adapter | `start_edge(Store.Local, …)` | no | +| 4 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | +| 5 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | +| 6 | The local executor | `start_edge(Local, …)` | no | +| 7 | The runtime root | `start_edge(Loopex, …)` | no | +| 8 | The lease owner | The daemon's own, under ADR 0033 — **one process for the daemon**, holding one lease record per session | no | +| 9 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | + +**The registry and the custody process are first, and that is forced rather +than chosen.** ADR 0034 makes the *host* own both, and for a daemon the host +is the daemon. The runtime's model configuration carries the registry handle +and the token in `options`, so both processes must exist before the +composition function builds that configuration — which means before the +runtime starts, and the composition function starts the runtime at the end of +its own chain, so before the composition call itself. + +Order 3 to 7 is the composition's actual chain, not a tidied one: the Store +first, then the artifact placement and the executor's own edges, and the +runtime last within that chain, because it depends on all of them. + +**The stop order is the reverse, with one deliberate exception.** Reversed: +listener, lease owner, runtime, executor, workspace lease, transfers, custody, +registry — and then **the Store, last of all**, out of reverse order. The +Store is moved to the end because its `terminate/2` releases the writer +marker, and the marker must outlive every operation the owner can end; +custody and registry hold nothing durable, so stopping them before it costs +nothing and keeps the one exception to one line. The socket is unlinked +earlier still, for the reason the socket-ownership rule below gives. The composition function therefore returns **every pid it linked**, not only the ones the daemon names in prose: a map carrying `store`, `runtime` (the `%Loopex.Runtime{}` struct), `runtime_supervisor`, `transfers` (absent when -disabled), `workspace_lease` and `executor`. Returning the runtime supervisor +disabled), `workspace_lease` and `executor`. The registry and custody pids are +not in it: the daemon started them itself, before the call, and already holds +them. Returning the runtime supervisor pid separately is a convenience rather than a necessity, and the plan says so plainly: the owner needs that pid to bound its stop, composition already holds it, so handing it over costs nothing. `%Loopex.Runtime{}`'s type is declared @@ -753,10 +821,10 @@ runs no dialyzer, and `RuntimeOwner` itself already destructures the field, at not, and the real argument is the simpler one above. **There is no restart strategy, because there are no restarts.** Every one of -the seven is `start_link`ed by the owner, and the owner's +the nine is `start_link`ed by the owner, and the owner's `handle_info({:EXIT, pid, reason}, state)` clause is the failure rule. That clause is also the **reader** the fatal-class map needs — it matches the pid -against the seven it holds, maps it to a component, classifies `reason`, and +against the set it holds, maps it to a component, classifies `reason`, and has the class in hand before anything else happens. Nothing here is `rest_for_one`, `one_for_all` or `max_restarts`; those words belonged to the withdrawn design and are gone. @@ -764,7 +832,7 @@ withdrawn design and are gone. **One field keeps that clause from firing on the owner's own work.** An earlier draft said "any linked exit, whatever the reason, is fatal", which is right for an exit the owner did not cause and wrong for every exit it does: -an orderly stop terminates all seven deliberately, so that rule would classify +an orderly stop terminates them all deliberately, so that rule would classify step 1 as `listener_lost`, step 2 as `supervision_fault`, step 3's clean return as `runtime_lost` — a daemon that could never exit `0`, and an idle-shutdown witness that could never pass. @@ -782,122 +850,100 @@ reads: still `store_lost`, and must be: the daemon is going down either way, but the operator is owed the real reason rather than `operator_stop`. -**The field is cleared by that exit, not by the call returning**, and the -distinction is not pedantry. **A stop can end four ways**, and the owner -catches three of them — and one of those shapes can mean two different -things, which is why one branch carries a guard. Each branch returns a tag, -so the wait that follows reads mechanically rather than by re-deriving what -happened: - -| How the stop ends | What the owner sees | What it does | Tag | -| --- | --- | --- | --- | -| The component stopped | `:ok` | Wait for its exit | `:ok` | -| It did not stop in time | `exit {:timeout, {GenServer, :stop, [pid, :normal, grace]}}` | `Process.alive?(pid)` first: alive, so `Process.exit(pid, :kill)`, then wait | `{:killed, pid}` | -| It died **of the bare atom** `:timeout` | the same shape — the two are indistinguishable | `Process.alive?(pid)` is false, so nothing to kill; wait | `:already_gone` | -| **It was already dead** | `exit {:noproc, {GenServer, :stop, [pid, :normal, grace]}}` | Nothing to kill; wait for the exit already queued | `:already_gone` | -| **It died of its own reason while stopping** | `exit {reason, {GenServer, :stop, [pid, :normal, grace]}}` for any other `reason` | Nothing to kill; wait for the exit its own death queued | `:already_gone` | - -The last three rows share one tag because the owner's response to them is the -same: it killed nothing, so the exit waiting for it is not its own doing. - -The wait then has one rule with no case analysis left in it: **`:ok` and -`{:killed, pid}` are the owner's own doing, so the exit is consumed; -`:already_gone` is not, so the exit is classified** — first class wins — and -either way `stopping` is cleared before the next component is named. - -Those same three are what earlier drafts got wrong, and none of them is -hypothetical. The owner does not read its mailbox while stopping, so a -component that dies during the sequence has its `{:EXIT, …}` queued and unread -when the sequence reaches its step, and `GenServer.stop/3` raises rather than -returning: - -- **Already dead.** `sys:terminate/3`'s `gen:call` fails with `noproc` and is - wrapped to `{noproc, {sys, terminate, _}}` (sys.erl:757-763 at the floor - pair, :756-762 at the current pair), which `:proc_lib.stop/3` catches and - re-raises as the bare `exit(noproc)` (proc_lib.erl:1586-1589 at the floor - pair, :1599-1601 at the current pair). -- **Dying of its own reason during its own stop.** `sys:terminate/3` succeeds, - and `:proc_lib.stop/3` then waits on its monitor with `Reason` **bound from - the function head** to the reason it was asked for. A `DOWN` carrying - anything else falls to the second clause, `exit(Reason2)` - (proc_lib.erl:1597-1600 at the floor pair, :1612-1615 at the current pair). - So a component whose `terminate/2` fails, or that was already terminating - for its own reason, ends the stop with *its* reason rather than `:normal`. - Verified by execution at the current pair: a trapping `GenServer` whose - `terminate/2` exits `{:badthing, :during_cleanup}`, stopped under the - two-clause catch, killed the caller — - `** (exit) exited in: GenServer.stop(…) ** (EXIT) {:badthing, - :during_cleanup}` — and under the three-clause catch returned - `:already_gone` with `{:EXIT, pid, {:badthing, :during_cleanup}}` waiting in - the mailbox, which is exactly the exit the wait then classifies. - -`GenServer.stop/3` wraps all three the same way (gen_server.ex:1076-1092 at -the floor pair, :1131-1147 at the current pair), and a catch matching only -`{:timeout, _}` matches none of them: the owner would die mid-shutdown with no -class on `stderr`, no status and the socket never unlinked. The clause is -therefore three, and the third is deliberately a catch-all, because the -component's own reason is whatever the component had. The breadth costs -nothing it should keep: the only other shape `GenServer.stop/3` raises is -`{:calling_self, _}`, and the owner passes a child's pid, never its own. - -**The timeout branch is guarded, because one reason collides with it.** A -component that dies with the *bare atom* `:timeout` during its own stop wraps -to `{:timeout, {GenServer, :stop, [pid, :normal, grace]}}` — byte for byte -what `:proc_lib.stop/3` raises when its own wait expires. Unguarded, the owner -would kill an already-dead pid, tag the branch `{:killed, pid}`, and the wait -would *consume* that component's exit as its own doing: the class lost and the -daemon exiting `0` on a failure. So the branch asks `Process.alive?(pid)` -first — alive means a real timeout and the kill is the only thing that ends -the tree; dead means the component died of that atom, the exit is already -queued, and the tag is `:already_gone` so the wait classifies it. No component -composed today reaches this: their reasons are tuples — `{:store_capacity_exceeded, N}`, -a `File.close` error, a crash tuple, `:shutdown` — and even a death by -`{:timeout, {GenServer, :call, …}}` is tuple-headed and lands on the catch-all -correctly. The guard is for the two components M5 itself writes, and the rule -that goes with it is stated here so it is not discovered later: **no daemon -component exits with the bare atom `:timeout`**; the lease owner and the -listener report an expiry or a refusal as a tagged reason. +**The owner never calls `GenServer.stop/3` itself**, and the reason is a +result an earlier draft did not have. Every previous version of this section +put the call in the owner and tried to name the shapes it must catch. That +approach is abandoned here, because at a boundary the composition already +admits the call does not raise an *exit* at all. + +**The probe.** A trapping `GenServer` whose `terminate/2` takes longer than +the grace, stopped with the grace the executor admits at its lower end +— the local executor validates it as `is_integer(cleanup_grace_ms) and +cleanup_grace_ms >= 0` (`executor.ex:897`), so `1` is a composable value, not +a contrived one — run at both toolchain pairs: + +| grace | `terminate/2` | what `GenServer.stop/3` did | `Process.alive?` right after | the link exit the owner then got | +| --- | --- | --- | --- | --- | +| 1 ms | 50 ms | **raised `ErlangError`, `:timeout_value`** | `true` | `:normal` | +| 1 ms | 0 ms | returned `:ok` | `false` | `:normal` | +| 5000 ms | 50 ms | returned `:ok` | `false` | `:normal` | +| 10 ms | 500 ms | exited `{:timeout, {GenServer, :stop, [pid, :normal, 10]}}` | `true` | `:normal` | + +Identical on 1.18.5-otp-27 and 1.20.3-otp-29. Two things in that table end the +inline design: + +- **Row 1 is an error, not an exit.** `:proc_lib.stop/3` computes + `RemainingTimeout = Timeout - elapsed` after `sys:terminate/3` returns, and + at a grace that small the subtraction goes negative, so its `receive … after + RemainingTimeout` raises `error:timeout_value` (proc_lib.erl:1578-1604 at + the floor pair, :1591-1618 at the current pair). No `catch :exit` clause + matches an error; the owner would die mid-shutdown with no class, no status + and the socket left behind — the same failure the last two rounds fixed + twice, reached by a third route. Chasing shapes is what keeps failing. +- **`Process.alive?` cannot tell success from failure here.** In rows 1 and 4 + it answered `true`, and in both the component then exited `:normal` a + moment later — it had stopped correctly. A design that kills on "alive after + the call" turns a successful stop into a killed one; the guard an earlier + round added on exactly that test is withdrawn with the rest. + +**So the stop is driven from outside the owner, and the classification comes +only from the exit the owner observes on its own link.** For each component: + +1. The owner sets `stopping` to that component, as before. +2. It `spawn_monitor`s a **helper** whose whole body is + `GenServer.stop(pid, :normal, grace)`. The helper is monitored, never + linked, so whatever that call raises, exits or returns dies with the helper + and never reaches the owner. The owner needs nothing from it — not its + return value, not its `DOWN` — and ignores both. +3. The owner then waits on the link it already holds: ```elixir -try do - GenServer.stop(pid, :normal, grace) - :ok -catch - :exit, {:timeout, _} -> - if Process.alive?(pid) do - Process.exit(pid, :kill) - {:killed, pid} - else - :already_gone +receive do + {:EXIT, ^pid, reason} -> reason +after + grace -> + Process.exit(pid, :kill) + + receive do + {:EXIT, ^pid, reason} -> reason end - - :exit, {:noproc, _} -> - :already_gone - - :exit, _other -> - :already_gone end ``` -After every one of them the owner waits for that exact pid's exit, in a -selective receive. **That receive carries no `after`**, so it sits outside the -composed cleanup grace and adds no second bound to reason about; it terminates -in every row because the exit it waits for is guaranteed to exist — on `:ok` -the component has terminated and the signal is in flight, on the timeout the -owner's own kill guarantees one, and on both `:already_gone` rows it is -already in the mailbox, which is how the owner found out. Whether the exit or -the monitor's `DOWN` reached the owner first is not ordered for us, which is -why the wait exists at all. - -That is enough to lose nothing, without draining the mailbox before the halt, -because of one invariant: **a component that dies during the sequence always -has its own step still ahead of it.** A component whose step has passed is -already stopped and cannot die a second time. So every unexpected death meets -its own step, and meets it in one of three ways: classified before the -sequence began, as `noproc` where it died earlier in the sequence, or as its -own reason where it died during its own step. Other messages sit unread -meanwhile and are read when the owner returns to its loop; nothing is skipped, -only ordered. +4. **The reason decides, and nothing else does.** `:normal` and `:shutdown` + are the stop the owner asked for, so the exit is consumed. `:killed` + following the owner's own kill is likewise the owner's doing — nothing else + in the daemon holds these pids — and is consumed. **Every other reason is + classified**, first class wins, and that is true whether the component died + before the stop, during it, or of something unrelated at that moment. + +This is smaller than what it replaces and it is total. There is no shape to +enumerate, because the owner reads the one thing the VM guarantees it: the +exit reason on a link it holds. The four-row catch table of the previous +revision, its `{:timeout, _}` / `{:noproc, _}` / catch-all clauses, its +`Process.alive?` guard and its "no daemon component exits with the bare atom +`:timeout`" rule are all withdrawn — they were an attempt to classify a +component's fate from what a library function did to the caller, and row 1 +shows that is not derivable. + +**What bounds each step.** The outer `receive` carries `after grace`, the +composed cleanup grace — one bound per component, the same number everywhere, +and the same number the helper passed to `GenServer.stop/3`, so a component +gets the grace once rather than twice. The inner `receive` after the kill +carries no `after`, and needs none: `Process.exit(pid, :kill)` on a live +process is unconditional, and on one already dead the exit the owner is +waiting for is the one that made it dead, already queued. It is a wait for a +signal that exists, not a second bound. + +**Other messages wait their turn.** Both receives are selective on one pid, so +an exit from another component, a client's frame, or anything else stays in +the mailbox and is read when the owner returns to its loop. Nothing is +skipped, only ordered — and nothing is lost even so, because of one invariant: +**a component that dies during the sequence always has its own step still +ahead of it.** One whose step has passed is already stopped and cannot die a +second time. So every unexpected death is met at its own step, by the wait +above, as a reason that is neither `:normal`, `:shutdown` nor the owner's own +`:killed` — and is classified there. Two consequences the sequences below depend on, stated here once: @@ -908,19 +954,20 @@ Two consequences the sequences below depend on, stated here once: operator gets the reason the daemon went down for rather than the last thing that happened on the way out. - **"Already dead" is something the owner learns, not something it knows.** - A component is known dead when its exit has been consumed — classified - before the sequence began, or read by the wait after `:already_gone`. It is - never assumed from a class recorded earlier in the same sequence, because - the unread `{:EXIT, …}` and the `noproc` are how the owner finds out, and - both are handled rather than avoided. A component that died before the - sequence started and was classified then is simply skipped. + A component is known dead when its exit has been consumed or classified. A + component that died before the sequence began was classified then and its + step is skipped; one that dies during the sequence is found at its own step, + where the helper's call fails in whatever way it fails — which the owner + never sees — and the wait reads the exit that is already queued. The owner + never assumes a component is gone from a class recorded earlier in the same + sequence. One field, one place, and it is what makes the two paths distinguishable at all. Both sequences below rely on it, and the idle-shutdown witness asserts the consequence directly: **no fatal class is recorded during an orderly stop**. -Two of the seven trap exits, and the plan states that as contract rather than +Two of them trap exits, and the plan states that as contract rather than relying on it as luck: the **Store adapter** traps, so an owner that crashes still runs its `terminate/2` and returns the marker; the **local executor** traps, so an owner exit lets it complete its own cleanup rather than leaving @@ -969,69 +1016,137 @@ than in taste: `Loopex.Store.Local` answers an append error with observes it, the store is gone and the marker is already released. A sequence that ends "then stop the Store" cannot run when the Store is what died. +**Who may unlink the socket, and when that stops being this daemon.** The +socket path is not the daemon's by possession; it is the daemon's *because it +holds the writer marker*, which is what ADR 0032 already says — only the +marker holder may unlink or bind. The consequence an earlier revision missed +is that the permission **ends when the marker does**, and the marker is +released by the Store's `terminate/2` (`local.ex:166`), which can happen +before the daemon is finished. + +Two paths, two rules: + +- **Orderly stop: unlink while still holding the marker.** Step 1 does it, + immediately after the listener stops and long before the Store. No successor + can have acquired the marker yet, so the path being unlinked is certainly + this daemon's. Leaving the unlink to the end — where earlier revisions had + it — meant unlinking after the marker was already released, and a successor + that acquired it in that window would have had *its* socket removed by a + daemon on its way out. +- **Fail-stop where the marker is already gone.** On `store_lost` and + `store_capacity_exceeded` the Store released the marker before the daemon + could act, so the daemon can no longer assume the path is its own. It + therefore compares identity rather than presence: at bind it captured the + path's `File.stat` device and inode, and at unlink it stats the path again. + **Equal device and inode: unlink. Anything else — a different inode, or + `{:error, :enoent}` — leave the path alone.** A successor's socket is a + different inode, which is what makes this decidable; verified by probe: a + bound path stats as `type: :other` with an inode, and a rebind of the same + path yields a different inode. + +**The residual is the window between the stat and the unlink**, and it is +stated rather than papered over: a successor that acquires the marker, removes +the stale path and binds entirely between our two syscalls would still lose +its socket file. Nothing narrows that further without a second lock, and a +second daemon-owned lock file is rejected — it would duplicate the marker's +stale-writer recovery machinery, including its own staleness question, to +guard a window one syscall pair wide. What is at stake is also bounded: the +socket is a path, never durable truth. A successor that loses its file serves +no client and is restarted; the marker it holds, which is the real exclusion, +is untouched, so nothing can write to the root behind it. + +**`--socket` is constrained to the selected root.** An override must resolve +inside that root's `daemon/` directory — the same directory the default path +sits in, under the same owner and symbolic-link rules — and a path outside it +is refused at startup with `invalid_socket_path`, before the marker is +acquired. Without that constraint two daemons on *different* roots could be +pointed at one path, and neither's marker would say anything about the other's +socket: the identity rule above would be comparing inodes between daemons that +have no exclusion between them at all. Inside one root, the marker is the +exclusion and there is exactly one holder. + +**How a signal reaches the owner, and when the handler is installed.** The +daemon does not inherit a usable signal disposition; it installs one, and the +order matters more than the mechanism. + +`SIGINT` cannot be installed on at all: the emulator reserves it for its break +handler and `:os.set_signal/2` refuses the name outright, which +`LoopexCli.Interrupt` states as a fact about that function rather than about +the command (`interrupt.ex:13-17`). So a terminal `Ctrl-C` reaches a daemon +the only way a reserved signal can — from outside the emulator. +`apps/loopex_cli/bin/loopex` traps `INT TERM HUP QUIT` and forwards +`kill -TERM` to its child (`bin/loopex:51-60`), so **`SIGINT` is a launcher +concern and `SIGTERM` is the escript's**. A daemon started without that +launcher has no `SIGINT` behaviour to specify, and the plan says so rather +than implying one. + +For `SIGTERM`, `SIGHUP` and `SIGQUIT` the daemon does what the CLI already +does, and reuses the same mechanism rather than inventing one: +`:os.set_signal(signal, :handle)` (`interrupt.ex:782`), a `:gen_event` handler +added to `:erl_signal_server` (`interrupt.ex:806` and `:818`), and the +**default handler removed** (`interrupt.ex:870-873`) because the runtime's +default stops the emulator immediately, which would end the process before any +of the sequence below could run. + +**The installation happens before the marker is acquired**, before the socket +is bound, and before any other resource whose release depends on the daemon +still running. That order is the whole point: with the default handler still +in place, a `SIGTERM` in the window between taking the marker and installing +the handler would stop the VM with no `terminate/2` anywhere, stranding the +marker for the next daemon's stale-writer recovery and leaving the socket file +behind. Installing first costs nothing — there is nothing to shut down yet, so +a signal arriving before startup completes ends a daemon that holds nothing. + +**The handler does one thing: it sends the owner a stop message.** It runs in +`:erl_signal_server`, not in the owner, so it performs no teardown, holds no +state and makes no decision; the owner's own code runs the sequence, from its +own process, exactly as it does for every other path. + +**The owner-loss backstop.** If the owner is not alive when the signal +arrives — it crashed, or the signal raced its own start — there is nobody to +run the sequence and nothing to wait for. The handler halts with +`fatal:owner_lost` on `stderr` rather than returning and leaving the process +running with a handler and no owner. That class is in the exit list above and +in the fatal-class map's note, and it is the one class no linked component +produces. + **Daemon-initiated shutdown is the owner stopping its children, in reverse order.** `SIGTERM` or `SIGINT` reaches the owner, which performs these four steps itself. They are the owner's code, not a supervisor's behaviour, which is what lets each one carry a reason and lets step 3 use a bound the owner chooses. -1. **The listener stops first.** It stops accepting, so a new connection is - refused rather than queued; it writes each open connection one - `daemon.stopping` naming `operator_stop`, bounded best-effort as ADR 0032 - fixes — one write attempt into the existing 4 MiB output buffer — and - closes it. Clients therefore learn *first*, before anything else is torn +1. **The listener stops first, and the socket path is unlinked with it.** It + stops accepting, so a new connection is refused rather than queued; it + attempts one `daemon.stopping` naming `operator_stop` per open connection, + bounded best-effort as ADR 0032 fixes — one write attempt into the existing + 4 MiB output buffer — and closes it. **Then the owner unlinks the socket + path, here and not at the end**, because this is the last moment at which + the daemon is certainly still the marker holder. Clients therefore learn + *first*, before anything else is torn down, which is the right order for the one party that cannot see inside the daemon. 2. **The lease owner stops.** Every lease vanishes with it. Nothing durable is involved, and no client is left holding one, because no connection survived step 1. -3. **The runtime stops, and this is where admitted work ends.** The owner - calls `Supervisor.stop(runtime_supervisor, :normal, grace)` on the pid the - composition function handed it, with `grace` the **composed cleanup - grace** — the same value the sessions were composed with, so no number is - introduced. It does **not** call `Loopex.Runtime.stop/1`: that is arity one - and uses the default `:infinity` timeout, which is exactly the bound this - step exists to supply. - - **What a timeout does, read from the installed stdlib rather than - assumed — and the chain is not the obvious one.** `Supervisor.stop/3` is - `GenServer.stop(supervisor, reason, timeout)` (supervisor.ex:1152-1154 at - the floor pair, :1197-1199 at the current pair), - and `GenServer.stop/3` calls **`:proc_lib.stop/3` directly**, not - `:gen.stop/3`, wrapping any exit it catches: - `catch :exit, err -> exit({err, {__MODULE__, :stop, [server, reason, - timeout]}})` (gen_server.ex:1076-1092, identical at the floor pair and the - current pair, 1.18.5-otp-27 and 1.20.3-otp-29). Beneath that wrapper, - `:proc_lib.stop/3` monitors the target, calls `sys:terminate/3`, and on - expiry — from `sys:terminate` raising `exit:{timeout, {sys, terminate, - _}}` or from its own `after RemainingTimeout` — demonitors and calls the - bare **`exit(timeout)`** (proc_lib.erl:1575-1604). - - So the shape the owner actually sees is - **`{:timeout, {GenServer, :stop, [pid, :normal, grace]}}`**, not a bare - `:timeout`. `catch :exit, {:timeout, _}` matches it — but only because of - that wrapper, and the plan names the wrapper so nobody later "simplifies" - the clause to match what `proc_lib` raises. Two consequences follow, and - both shape this step: - - - **The target is not killed.** A timeout abandons the wait; the runtime - supervisor is still running afterwards. So the owner's kill is not a - belt-and-braces addition — it is the only thing that ends the tree. - - **The exit lands on the caller.** Left alone, the owner would die of - `timeout` and never reach step 4. So the call runs inside - `try … catch :exit, {:timeout, _} -> …`, which is the simplest form the - semantics allow: because `proc_lib:stop/3` exits the *caller*, a - `try/catch` in the owner is enough and no monitored helper process is - needed. - - On that catch the owner kills the runtime supervisor — - `Process.exit(runtime_supervisor, :kill)`. While the owner is blocked in - the stop call it cannot *act* on incoming exits, but it traps them, so they - queue as messages and are handled when the call returns — against the - `stopping` field, so the runtime's own exit is consumed and any other - component's is still classified; nothing is lost, - only deferred, which during a shutdown the owner is already performing is - what should happen. +3. **The runtime stops, and this is where admitted work ends.** The helper + for this step calls `Supervisor.stop(runtime_supervisor, :normal, grace)` + on the pid the composition function handed it, with `grace` the **composed + cleanup grace** — the same value the sessions were composed with, so no + number is introduced. It does **not** call `Loopex.Runtime.stop/1`: that is + arity one and uses the default `:infinity` timeout, which is exactly the + bound this step exists to supply. + + `Supervisor.stop/3` is `GenServer.stop(supervisor, reason, timeout)` + (supervisor.ex:1152-1154 at the floor pair, :1197-1199 at the current + pair), so it is the same call the general rule above describes, made in the + same place — the helper — and its outcome is read the same way, from the + exit on the owner's link. What `:proc_lib.stop/3` does to *its* caller on + expiry, whatever shape that takes, is the helper's business and dies with + it. The owner's `after grace` fires, it kills the runtime supervisor with + `Process.exit(runtime_supervisor, :kill)`, and it reads the exit that + follows: `:normal` or `:shutdown` where the tree came down on its own, + `:killed` where the kill ended it, anything else classified. **What "crash-equivalent" does and does not claim.** An earlier draft said the kill makes the tree crash-equivalent "by definition". That is true of @@ -1039,7 +1154,7 @@ chooses. stating because a reader will otherwise assume more than holds. `Process.exit(sup, :kill)` ends the root only; `killed` then propagates over links, and a **trapping** descendant receives it as a message and unwinds on - its own clock. Three of the root's seven children are supervisors, and + its own clock. Three of the runtime root's own children are supervisors, and `OwnerGroup` traps exits, carries `shutdown: :infinity`, and has a `terminate/2` that itself calls `Supervisor.stop(workers, :shutdown, :infinity)`. So: @@ -1062,10 +1177,11 @@ chooses. order puts the executor, the workspace lease and the transfers owner between the runtime and the Store, and each is stopped in turn — the executor first, since it is the one with OS effects to clean up and it - traps exits to do so. Then the Store, whose `terminate/2` releases the - writer marker — see the marker invariant in ADR 0031. Finally the socket - path is unlinked and the owner **halts with `0`** — or with the class, in - the case above where something failed on the way out. + traps exits to do so. Then custody and the registry, which hold nothing + durable. Then the Store, whose `terminate/2` releases the writer marker — + see the marker invariant in ADR 0031. The socket path is already gone, + unlinked in step 1, so the last act is the halt: **`0`**, or the class, + in the case above where something failed on the way out. **The executor is stopped before the lease, and that order is load-bearing** rather than alphabetical. The executor privately monitors the lease holder @@ -1075,12 +1191,11 @@ chooses. executor first means the lease's death is observed by nobody, which is what an orderly stop wants. - **Each of these four is `GenServer.stop(pid, :normal, bound)` under the - same treatment as step 3** — `try/catch :exit` on the wrapped timeout, then - `Process.exit(pid, :kill)` — because all four are `GenServer`s + **Each of these four is a helper calling + `GenServer.stop(pid, :normal, bound)`, with the owner waiting on its own + link** — the same rule as step 3, and all four are `GenServer`s (`executor.ex:22`, `workspace_lease.ex:15`, `transfers.ex:26`, - `local.ex:55`) and the same OTP semantics apply: a timeout does not kill - the target, and the exit lands on the owner. The bounds: + `local.ex:55`), so the same call fits all four. The bounds: | Process | Bound | What it is waiting for | | --- | --- | --- | @@ -1100,17 +1215,11 @@ chooses. owner skips at runtime so much as a pid it never held, and the step for it does not exist in that daemon's sequence at all. - **What bounds the wait after each stop: nothing, and that is the safe - answer.** The selective receive that follows a stop carries no `after`, so - it is outside the composed grace and adds no second bound to reason about. - It terminates in every row of the stop-ending table above, for the reason - that table gives: the exit it waits for is guaranteed to exist, in flight on - `:ok`, guaranteed by the owner's own kill on the timeout, and already in - the mailbox on both `:already_gone` rows — the owner only attempts a stop - for a component whose exit it has not already consumed, so a stop that - raises means an unread exit. An `after` here would be a number with no - failure to catch, and it would turn a guaranteed signal into a second thing - that can go wrong. + Each of these bounds is the `after grace` on the owner's own wait, not a + second clock: the helper passes the same number to `GenServer.stop/3`, so a + component is given the grace once. The wait after the kill carries no + `after`, for the reason the general rule gives — it waits for a signal that + already exists. **A killed executor is the residual, and the plan states it rather than explaining it away.** The kill by itself is not the leak. The executor @@ -1197,9 +1306,10 @@ to write. store's own reason was the capacity refusal, and the failed component's own class on the other six. 3. **Stop the executor** — on every class but `executor_lost`, where it is - the component that already died — as `GenServer.stop(pid, :normal, grace)` - under the same try/catch-and-kill treatment and the same composed cleanup - grace the ordered path's step 4 uses. This is not tidiness: the executor is + the component that already died — under the same discipline as every other + stop: a monitored helper calling `GenServer.stop(pid, :normal, grace)`, the + owner waiting on its own link with `after grace` and killing on expiry, and + the composed cleanup grace the ordered path's step 4 uses. This is not tidiness: the executor is the one linked process that owns effects outside the VM, and it traps exits precisely so it can clean them up. Halting without stopping it would end that cleanup where it stood. The residual is the one stated there and is @@ -1224,10 +1334,15 @@ to write. and found dead, refuses with `store_writer_unverifiable` where it cannot be decided, and refuses with `store_writer_active` where it is alive. A surviving marker is a case with a defined answer, not a corruption. -5. Unlink the socket. **The runtime root, the lease owner and the transfers - owner are not stopped on this path**, and that is deliberate rather than an - omission. A fail-stop is not a drain, and none of the three owns anything - that outlives the VM: the executor does, which is why step 3 exists, and +5. Unlink the socket **only if it is still ours**. On the six classes where + the daemon still holds the marker this is unconditional. On the two store + classes the marker is already gone, so the owner applies the identity rule + above: stat the path, unlink on an equal device and inode, leave it alone + on anything else. **The runtime root, the lease owner, the registry, the + custody process and the transfers owner are not stopped on this path**, and + that is deliberate rather than an omission. A fail-stop is not a drain, and + none of them owns anything that outlives the VM: the executor does, which + is why step 3 exists, and the Store holds the marker, which is why step 4 does, while the transfers owner's open descriptors are closed by the operating system when the VM goes. Stopping the lease owner would buy less here than on the ordered @@ -1235,8 +1350,8 @@ to write. `executor_lost` there is no executor left to read the lease holder's `DOWN` at all. 6. Write the class on `stderr`, then **halt with the non-zero status** for - that class. Nothing restarts anything: the owner `start_link`s its seven - and restarts none, so an exit it did not cause is fatal by its own clause — + that class. Nothing restarts anything: the owner `start_link`s its fixed + set and restarts none, so an exit it did not cause is fatal by its own clause — which is why this path exists at all rather than being a restart. Nothing durable is at risk in that ordering: whatever was ambiguous is @@ -1278,7 +1393,7 @@ the next marker holder removes. **The fatal-class map.** Every non-zero exit names one class on `stderr`. Its **reader is the owner's `{:EXIT, pid, reason}` clause**, which matches the pid -against the seven it holds, maps it to a component and classifies the reason; +against the fixed set it holds, maps it to a component and classifies the reason; there is one place in the daemon where a class is decided, and this is it. The set is closed: **one class per linked component**, so no linked process can die without a name for it. @@ -1291,20 +1406,45 @@ die without a name for it. | `session_index_too_large` | Startup: the directory holds more than the index bound | — | | `socket_path_too_long` | Startup: the path exceeds the derived `sun_path` bound | — | | `socket_permission_unverified` | Startup: subdirectory or socket ownership/mode could not be verified | — | -| `store_capacity_exceeded` | Linked process 1, the Store, exited **on the capacity refusal**, distinguished by its own reason | `store_capacity_exceeded` | -| `store_lost` | Linked process 1, the Store, exited for any other reason | `store_lost` | -| `runtime_lost` | Linked process 5, the runtime root, exited | `fatal:runtime_lost` | -| `transfers_lost` | Linked process 2, the artifact transfers owner, exited | `fatal:transfers_lost` | -| `workspace_lease_lost` | Linked process 3, the workspace lease, exited | `fatal:workspace_lease_lost` | -| `executor_lost` | Linked process 4, the local executor, exited | `fatal:executor_lost` | -| `supervision_fault` | Linked process 6, a lease owner, exited — ADR 0033's daemon-fatal rule | `fatal:supervision_fault` | -| `listener_lost` | Linked process 7, the listener, exited | `fatal:listener_lost` | +| `invalid_socket_path` | Startup: a `--socket` override outside the selected root's `daemon/` directory | — | +| `store_capacity_exceeded` | The Store exited **on the capacity refusal**, distinguished by its own reason | `store_capacity_exceeded` | +| `store_lost` | The Store exited for any other reason | `store_lost` | +| `transfers_lost` | The artifact transfers owner exited | `fatal:transfers_lost` | +| `workspace_lease_lost` | The workspace lease exited | `fatal:workspace_lease_lost` | +| `executor_lost` | The local executor exited | `fatal:executor_lost` | +| `registry_lost` | The credential routing registry exited | `fatal:registry_lost` | +| `custody_lost` | The credential custody process exited | `fatal:custody_lost` | +| `runtime_lost` | The runtime root exited | `fatal:runtime_lost` | +| `supervision_fault` | The lease owner exited — ADR 0033's daemon-fatal rule | `fatal:supervision_fault` | +| `listener_lost` | The listener exited | `fatal:listener_lost` | + +The rows are named rather than numbered, because a number is a fact about the +start order and this table is a fact about which pid died; the two drifted +apart in an earlier revision and the numbers are gone for that reason. There +is one row per linked process, and the transfers row exists only in a daemon +that has one. + +**`registry_lost` and `custody_lost` are fail-stop like every other row, and +that follows from ADR 0034 rather than adding to it.** That ADR makes a dead +registry answer `:unavailable` for every later resolution *until the host +recomposes*; in a daemon, recomposing is restarting the process. A daemon that +kept running would serve a runtime whose every model invocation refuses for a +reason no client can fix, which is exactly the shape the fail-stop rule +exists for. + +**One class comes from outside this map:** `owner_lost`, which the signal +handler halts with when a signal arrives and the owner is not alive to run the +sequence. No linked process produces it, and it is the only exit class that is +not a row above. The wire column matters because ADR 0032's `daemon.stopping` `reason` admits `operator_stop`, `store_lost`, `store_capacity_exceeded` and `fatal:`, so every class above that a running daemon can reach has a reason a client can -receive. The startup classes have none, deliberately: no socket exists when -they occur, so no client is holding one. +receive — *if* there is still a socket and the write succeeds. The startup +classes have none, deliberately: no socket exists when they occur, so no +client is holding one. Neither does `listener_lost`, where the listener is +what died, nor `owner_lost`, where the process that would write it is gone: +those clients learn by EOF. **The daemon's own log is bounded and redacted by the rules that already exist.** Everything the daemon writes to `stderr` — refusals, warnings, the @@ -1317,14 +1457,27 @@ already sends on the wire, and the fatal-class map above is the whole vocabulary of what an exit may say. **Reverse cleanup.** Startup happens inside the owner, so a failure at any -step unwinds what that step and its predecessors did, in reverse: a bound -socket is closed and its path unlinked, a `daemon/` subdirectory the owner -created is removed, and the Store is stopped so its `terminate/2` releases the -marker. The owner does this in its own start path rather than leaving it to a -crash, because a crashing owner would take the links down without unlinking -the socket file, which no exit signal removes. A daemon -that refuses to start leaves no marker and no socket file behind, which is -what lets an operator fix the cause and try again without a recovery step. +step unwinds what that step and its predecessors did, in reverse — and +"predecessors" means **every process the startup started**, not the three an +earlier revision named. A bound socket is closed and its path unlinked, a +`daemon/` subdirectory the owner created is removed, the lease owner is +stopped, **every pid the composition function returned is stopped in reverse +start order** — runtime, executor, workspace lease, transfers where it exists +— then custody and the registry, and the Store last, so its `terminate/2` +releases the marker. + +Each of those stops is the same call and the same discipline as a shutdown +stop: a monitored helper running `GenServer.stop(pid, :normal, grace)` with +the composed cleanup grace, the owner waiting on its own link with `after +grace`, and a kill on expiry. Startup introduces no second teardown +mechanism; it reuses the one the shutdown sequence defines, against the pid +map it already holds. + +The owner does this in its own start path rather than leaving it to a crash, +because a crashing owner would take the links down without unlinking the +socket file, which no exit signal removes. A daemon that refuses to start +leaves no marker and no socket file behind, which is what lets an operator fix +the cause and try again without a recovery step. **Witnesses**, all on real operating-system processes: @@ -1335,7 +1488,7 @@ what lets an operator fix the cause and try again without a recovery step. is what proves the marker was actually released. The case also asserts the negative that the `stopping` field exists for: **no fatal class is recorded at any point during the stop**, and nothing appears on `stderr` — stopping - seven linked processes deliberately produces seven exits, and every one of + every linked process deliberately produces an exit from each, and every one of them must be consumed rather than classified. - **A real failure during an orderly stop is still classified, and the sequence still finishes.** The Store is made to fail while the listener is @@ -1377,7 +1530,7 @@ what lets an operator fix the cause and try again without a recovery step. was stopped — and that the stop *returned* rather than timing out into a kill — before the halt, so its cleanup ran and no operating-system child is left behind. -- **One class per linked component.** Each of the seven linked processes is +- **One class per linked component.** Each linked process is killed in turn, in its own case, and the daemon is asserted to exit with that component's class, to send that component's `fatal:` on the wire where a socket still exists, and — for the six classes where the Store is @@ -1387,12 +1540,53 @@ what lets an operator fix the cause and try again without a recovery step. `listener_lost`, beside the two store classes. The set is closed, so a linked process dying without a class is a failing case rather than a silent `:shutdown`. +- **A successor's socket survives its predecessor's exit.** Two daemons on + one root. The first is paused between the Store's marker release and its + unlink — the fail-stop window, reached by making the Store terminate and + holding the owner at that point. The second acquires the marker, removes the + stale path, binds its own socket, and prints readiness. The first is then + released. The case asserts that it **does not unlink** the path, because the + inode it stats is not the one it captured at bind, and that the second + daemon's socket is still bound and still serving a client afterwards. The + orderly variant asserts the other half: the unlink happens in step 1, while + the marker is still held, so a successor cannot even reach that window. +- **A `--socket` path outside the root is refused.** A path in a directory + that is otherwise perfectly valid — right owner, right mode — but outside + the selected root's `daemon/` directory exits `invalid_socket_path` with no + marker taken, no socket bound and nothing left behind. +- **Signals, one case per delivery route.** `SIGTERM` sent to the daemon + process itself begins the orderly sequence; `SIGINT` is sent **to the + launcher**, `apps/loopex_cli/bin/loopex`, which forwards `SIGTERM` to the + child, because `:os.set_signal/2` refuses `:sigint` and a `SIGINT` sent to + the daemon process directly is not this plan's to specify. Each case names + which process it signals. A third asserts the install order: a `SIGTERM` + delivered before startup completes ends a daemon that holds no marker and + has bound no socket, proved by a following daemon starting with nothing to + recover. +- **`owner_lost`.** The owner is killed while the daemon is otherwise healthy, + then `SIGTERM` is delivered. The process halts with `fatal:owner_lost` on + `stderr` rather than sitting with a handler and no owner. +- **The credential processes are fatal like every other component.** The + registry and the custody process are each killed in their own case; the + daemon exits `registry_lost` and `custody_lost` respectively, sends that + `fatal:` on the wire, and leaves no stale marker. - **The stop timeout is exercised, not assumed.** A session is made to hold the runtime's teardown past the composed cleanup grace. The case asserts the - owner **survives** the resulting `exit(timeout)` from `proc_lib:stop/3` - rather than dying of it, that it then kills the runtime supervisor, and that - it still reaches the Store stop and the socket unlink — the whole point of - wrapping the call, and the step an unwrapped call would skip. + owner **survives** rather than dying of whatever the stop did to the helper, + that it then kills the runtime supervisor, and that it still reaches the + Store stop and the socket unlink — the step a stop called inline would skip. +- **Cleanup grace 1 ms: the owner survives and classifies from the exit.** The + same daemon is composed with `cleanup_grace_ms: 1`, a value the local + executor's own validation admits (`executor.ex:897`), and stopped with a + component whose teardown takes longer than that. This is the case that broke + every inline design: at that grace `GenServer.stop/3` raises + `ErlangError`/`:timeout_value` rather than exiting, so no `catch :exit` + clause would have run. The case asserts the owner survives, that it kills + and reads the exit, that the class follows the **exit reason** and not the + stop's outcome — `operator_stop` and exit `0` where the component still + managed to exit `:normal`, its own class where it did not — and that the + sequence still reaches the Store stop and the socket unlink. It runs at both + toolchain pairs, because the result was observed at both. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting @@ -1427,7 +1621,7 @@ plan names as new. It is the thing to check a change against. | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT` | The owner stops its linked processes in reverse order itself — listener, lease owner, runtime, then the composed edges, Store last — each bounded by the composed cleanup grace and each under `try/catch :exit` on the wrapped `{:timeout, {GenServer, :stop, _}}` (`Supervisor.stop/3` → `GenServer.stop/3` → `:proc_lib.stop/3`), since a timeout exits the caller without killing the target, then killing that target on the catch. Every exit these stops cause is consumed by the owner's `stopping` field rather than classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT`, delivered to the handler the daemon installs before it takes the marker | The owner stops its linked processes in reverse order itself, each stop driven by a monitored helper calling `GenServer.stop(pid, :normal, grace)` while the owner waits on its own link with `after grace` and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | From b685d65d8fc770ea1ce32e574f9754f9d293a125 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 23:49:47 -0700 Subject: [PATCH 064/585] plan(M5): withdraw the drain promise, add control_pending P1-B: the Concept file promised that an orderly stop drains admitted work within the grace and settles the rest through cancellation bounds. Neither has a mechanism: coordinators are temporary children with no drain callback (session_coordinator.ex:133-142) and the daemon runs no cancellation. Both are withdrawn for the smaller sequence that is actually implemented -- refuse, attempt one stop record per connection, close, unlink while the marker is held, bounded crash-equivalent teardown, reconcile at the next activation. "Every client receives the record" is withdrawn with them: ADR 0032 already admits an EOF alone, and on `listener_lost` nothing is left to write it, so a client learns by the record where the write succeeds and by the close where it does not. P1-H: ADR 0033 refuses an acquisition whose own deadline elapses behind an unresolved admission, and ADR 0032's generation-2 error inventory claimed completeness while carrying no code for it. `control_pending` is added to the inventory, the digest table and the vectors, and named in ADR 0033 as distinct from `control_held`. Also carried here: the `daemon.stopping` reason row gains `fatal: registry_lost` and `fatal:custody_lost` from the topology fix, and records that `owner_lost` reaches no client because the process that would write it is the one that is gone. --- ...tachment-residency-and-replay-technical.md | 14 ++++++- ...controller-lease-and-takeover-technical.md | 11 ++++-- docs/plans/M5-technical.md | 34 ++++++++++++---- docs/plans/M5.md | 39 +++++++++++++------ 4 files changed, 73 insertions(+), 25 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 0200dff4c..567330f14 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -156,7 +156,7 @@ which no client requests and every client may receive: | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:supervision_fault`, `fatal:listener_lost`. The startup classes carry no reason, because no socket exists when they occur | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:supervision_fault`, `fatal:listener_lost`. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | @@ -186,9 +186,19 @@ limits — five inputs, and generation 2 changes four of them: | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_pending`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | | Limits | Unchanged from ADR 0023's ceilings | +**`control_pending` is the acquisition timeout, and it was missing.** ADR 0033 +refuses an acquisition whose own deadline elapses while it waits behind an +unresolved admission, with a stable reason — and the inventory above claimed +to be complete while having no code for it. `control_pending` is that code: it +says the lease is not held by anyone the client must wait for indefinitely, +only that this acquisition did not get it in time, which is a different fact +from `control_held` and deserves a different refusal. It enters the ordered +error list, the digest above, and the generation-2 vectors alongside the +others. + Listing the error codes matters because it is the input most easily forgotten: a refusal reason invented at implementation time and not entered in the ordered list would make the served contract differ from the digest the server diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 98f7d766e..ed2d374e8 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -178,8 +178,11 @@ admitted at expiry with no grace. The linearization rule is: 3. A takeover becomes **eligible** at the deadline and is **granted** only once every in-flight mutation for that session has resolved. Until then the acquire waits, bounded by the acquiring request's own deadline; a wait that - exceeds it refuses with a stable reason naming the in-flight admission, and - the client may acquire again. + exceeds it refuses with **`control_pending`**, the stable reason ADR 0032's + generation-2 error inventory carries for exactly this case, and the client + may acquire again. It is distinct from `control_held`, which says another + client holds the lease; `control_pending` says only that this acquisition + ran out of time behind an admission that had not resolved. 4. The grant then mints a fresh epoch, so nothing admitted under the previous lease can be confused with anything after it. @@ -228,8 +231,8 @@ controller unaffected; a lease transition racing command admission preserves this order; the expiry linearization above, with a mutation blocked inside core across the deadline settling under its own lease while the eligible takeover waits and is granted only after it resolves, the holder's next -mutation refused at the deadline, the acquiring request refusing with its -stable reason when its own deadline elapses first, the holder's connection +mutation refused at the deadline, the acquiring request refusing with +`control_pending` when its own deadline elapses first, the holder's connection disconnecting while its mutation is in flight, and the per-session lease owner failing while a mutation is in flight — in every case exactly one of settle or refuse, never both, and no epoch reused; takeover only after release or expiry diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index ae4b9db9d..dd7f7937a 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,9 +130,9 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, every client given one bounded best-effort `daemon.stopping` naming `operator_stop`, the socket unlinked, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `supervision_fault`, `listener_lost`) — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with its stable reason when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease releasing it explicitly on every exit path; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in two tiers, against `Loopex.Trace` as implemented rather than against ADR 0030's prose: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** the adapter module, entries for the three may exist and each is asserted to carry placeholders and no credential bytes and no token. That second tier holds because ADR 0034 binds the **shape**: the three carry credential bytes only under a credential-named key, which `@credential_pattern` placeholders at any size. It does not hold by size — running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim, and only a credential-keyed value placeholdered at every size — so the witness calls each of the three with a **one-byte** credential under a session naming the module, and asserts no entry contains that byte. A third case asserts the three identities, so neither tier can pass vacuously. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -1265,10 +1265,18 @@ chooses. path. One ordering consequence is worth stating because it reverses an earlier -draft: clients are told *before* work is drained, not after. That is -deliberate. The drain does not need connections to exist, and a client that -must reconnect elsewhere is better served by learning immediately than by -waiting out a cleanup grace it cannot see. +draft: clients are told *before* the teardown, not after. That is deliberate. +The teardown does not need connections to exist, and a client that must +reconnect elsewhere is better served by learning immediately than by waiting +out a cleanup grace it cannot see. + +**And "told" is an attempt, not a guarantee.** The write is one attempt into +the existing 4 MiB output buffer, on a transport the client may already have +dropped; ADR 0032 admits an EOF alone as a complete ending for exactly this +reason, and on `listener_lost` there is nothing left to write with. A client +learns the reason from the record where the write succeeds and from the close +where it does not — that is the whole promise, and no part of this plan +depends on a stronger one. **Cancellation is not the daemon's to run**, which an earlier draft claimed. It is the coordinator's, as part of a session's own durable command, and a @@ -1279,6 +1287,15 @@ have the daemon issuing mutations on nobody's authority, at the moment it is least able to see them through. An unbounded natural drain would make `SIGTERM` unbounded, which is not a stop. +**Nor does the daemon drain.** No step waits for admitted work to finish: the +runtime stop is bounded by the composed cleanup grace and ends what has not +finished crash-equivalently, and the grace bounds the teardown rather than the +work. An earlier revision of the Concept file promised a drain and a +settlement through cancellation bounds; neither had a mechanism here — +coordinators are temporary children with no drain callback +(`session_coordinator.ex:133-142`) — and both are withdrawn rather than +restated. + **Store loss, a fail-stop path.** The owner holds the Store's link and its pid, so the adapter's termination arrives as `{:EXIT, store_pid, reason}` at the owner's own clause, carrying the store's real reason. That clause is the @@ -1514,8 +1531,9 @@ the cause and try again without a recovery step. cleanup grace is ended crash-equivalently, and the case asserts the negative that matters: **no terminal mutation is claimed** for it — no `cancelled`, no `outcome_unknown`, no abort record appears in the journal on the way - down. The ambiguous mutation stays `commit_unknown`, every client receives - the stop reason, and the exit is still `0`. Activating that session again + down. The ambiguous mutation stays `commit_unknown`, each client is sent the + stop reason on a transport that accepts it and sees the close either way, + and the exit is still `0`. Activating that session again afterwards resolves the transaction to exactly one outcome through the existing reconciliation, and the journal is byte-identical to what an abrupt death at the same instant would have left. diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 136573287..a15ff1f32 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -48,7 +48,7 @@ transport, no second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, drains admitted work within the cleanup grace and settles the rest through cancellation bounds and fenced `commit_unknown` rather than abandoning it, tells every client the reason, unlinks the socket and stops the Store last, exiting `0`; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, attempts one stop record per client, closes every connection, unlinks the socket while the marker is still held, and then ends admitted work crash-equivalently within the composed cleanup grace, claiming **no terminal outcome** for it and leaving the ambiguous mutation as fenced `commit_unknown` for the reconciliation that already exists, stopping the Store last and exiting `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -339,16 +339,33 @@ offline `loopex sessions`, `run` and `resume` are unchanged, and each live form is a separate explicit `--daemon` form of them. A daemon ends in one of two ways and the plan keeps them apart, because the -code does. **A daemon-initiated stop** is a sequence: refuse new connections -and new admissions, let admitted work drain within the composed cleanup grace, -then end what has not settled by stopping the runtime — which is -crash-equivalent by construction and therefore **claims no terminal outcome** -for that work, leaving `commit_unknown` fenced for the reconciliation that -already exists — then tell every client the reason on the wire, unlink the -socket, and stop the Store last, which is when its `terminate/2` releases the -marker. The daemon runs no cancellation of its own; cancellation is a -session's own durable command and a daemon-side path for it would be the -second loop this milestone forbids. +code does. **A daemon-initiated stop** is a short sequence, and it is short +deliberately: refuse new connections and new admissions; attempt **one** +best-effort stop record per open connection and close it; unlink the socket +while the marker is still held; end admitted work by stopping the runtime +within the composed cleanup grace, which is crash-equivalent by construction +and therefore **claims no terminal outcome** for that work, leaving +`commit_unknown` fenced for the reconciliation that already exists; stop the +remaining edges; and stop the Store last, which is when its `terminate/2` +releases the marker. + +**There is no drain, and no settlement, and the plan says so where it used to +promise both.** An earlier revision described admitted work draining within +the grace and the rest settling through cancellation bounds. Neither has a +mechanism: coordinators are temporary children with no drain callback, the +daemon runs no cancellation of its own — cancellation is a session's own +durable command, and a daemon-side path for it would be the second loop this +milestone forbids — and nothing in the sequence waits for work to finish. +What the grace bounds is the teardown, not the work. What survives is what the +journal already proves, and the ambiguous transaction resolves to exactly one +outcome at the next activation. + +**A client learns by the record or by the close.** The stop record is one +bounded write attempt into a buffer that may be full, on a transport that may +already be gone, and on the one path where the listener itself is what failed +there is nothing left to write it with. So the promise is the honest one: a +client is told the reason where that write succeeds, and learns by EOF where +it does not. **A store loss is not that sequence at all.** The local adapter answers an append error by terminating itself, and its `terminate/2` releases the marker From 404fd5375eb7c5062c7228048c0f06efde19d7b1 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 23:50:45 -0700 Subject: [PATCH 065/585] adr(0033): one lease-owner process per daemon, lease as data P1-D: ADR 0033-technical required one lease-owner process per session while the plan's topology had one, and its own consequence paragraph still said "one of four processes" with "any linked exit" fatal. On the maintainer's decision the ADR now requires one lease-owner process for the daemon holding one lease record per session: each session's transitions are still serialized against its own admissions, because the process holds each session's record and in-flight set separately. The rejected option is recorded -- a process per session makes the daemon's population dynamic and needs a retirement rule, a bound and per-session fatal semantics that the lease itself never asks for. The stale count and the stale "any linked exit" rule are corrected, and the Concept file now states the fixed set: nine linked processes with transfers enabled, eight without, including the credential registry and custody processes ADR 0034 gives the host. --- ...tachment-residency-and-replay-technical.md | 2 +- ...controller-lease-and-takeover-technical.md | 36 ++++++++++++------- docs/plans/M5-technical.md | 4 +-- docs/plans/M5.md | 26 ++++++++------ 4 files changed, 43 insertions(+), 25 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 567330f14..d9a7ac06c 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -229,7 +229,7 @@ the daemon itself owns or reads once: this lifetime*, set to `active` at activation and never set back, because activation is one-way. It is not a claim about a live coordinator; - `controlled`, a daemon fact, updated on every lease grant, release and - expiry by the same per-session owner ADR 0033 gives those transitions. + expiry by the same lease owner ADR 0033 gives those transitions. **`residency` says what the daemon knows, not what core is doing.** Its two values mean exactly: diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index ed2d374e8..70b3e367d 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -37,11 +37,22 @@ idempotency. Those remain the commit-authority fence, and they answer a different question — which coordinator owner may commit — than the writer epoch does, which is which client may drive. -One owner process per session serializes every lease read, grant, renewal, -release and expiry transition with that session's mutation-admission handoff, -so a takeover cannot pass a mutation whose holder check has already started -but whose core admission is unresolved; that admission first resolves, or the -daemon's own holder-and-epoch check refuses it before it ever reaches core. +**One lease-owner process per daemon**, holding **one lease record per +session**, serializes every lease read, grant, renewal, release and expiry +transition with that session's mutation-admission handoff, so a takeover +cannot pass a mutation whose holder check has already started but whose core +admission is unresolved; that admission first resolves, or the daemon's own +holder-and-epoch check refuses it before it ever reaches core. + +The serialization a session needs is against **its own** lease transitions, +and one process serializes each session's independently by holding each +session's record and in-flight set separately; sessions do not contend for +anything but that process's mailbox. An earlier revision required a process +per session. That is withdrawn on the maintainer's decision: it made the +daemon's process population dynamic, needing a retirement rule, a per-session +fatal semantics and a place for the population to be bounded, none of which +the lease itself asks for. **The lease is data; the process count is +topology.** **A lease owner's failure is fatal to that daemon instance, deliberately.** The owner holds the session's in-flight admission set in its own memory, and @@ -53,11 +64,12 @@ sockets intact; that was withdrawn on 2026-09-20, on an independent review's finding, because a successor acquire could then be granted while a forgotten admission was still able to settle. -So a lease owner's failure is fatal to the daemon instance, and the daemon's +So the lease owner's failure is fatal to the daemon instance, and the daemon's own structure supplies that without special-case code: the lease owner is one -of four processes the daemon's owner process `start_link`s, the owner traps -exits, and its `{:EXIT, pid, reason}` clause treats **any** linked exit as -fatal. There are no restarts to configure and no strategy to get wrong. The +of the fixed set of processes the daemon's owner process `start_link`s, the +owner traps exits, and its `{:EXIT, pid, reason}` clause classifies an exit it +did not ask for — which is every exit outside its own stop sequence — as +fatal, mapping this pid to `supervision_fault`. There are no restarts to configure and no strategy to get wrong. The owner classifies the exit as `fatal:supervision_fault`, has the listener tell every client, closes them, unlinks the socket and exits non-zero; the daemon comes back with no lease anywhere, no connection and no session activated. No @@ -162,7 +174,7 @@ the local store's writer marker, unchanged. ### Expiry against an in-flight admission Two rules above meet at the deadline and their order has to be stated, not -left to the implementation. The per-session owner serializes a lease +left to the implementation. The lease owner serializes a lease transition against a mutation whose holder check has already started, so a takeover cannot pass an admission core has not yet resolved; and takeover is admitted at expiry with no grace. The linearization rule is: @@ -233,7 +245,7 @@ core across the deadline settling under its own lease while the eligible takeover waits and is granted only after it resolves, the holder's next mutation refused at the deadline, the acquiring request refusing with `control_pending` when its own deadline elapses first, the holder's connection -disconnecting while its mutation is in flight, and the per-session lease owner +disconnecting while its mutation is in flight, and the lease owner failing while a mutation is in flight — in every case exactly one of settle or refuse, never both, and no epoch reused; takeover only after release or expiry with a fresh epoch minted before the successor's first command; the three ways @@ -243,7 +255,7 @@ early and the transport cannot tell the other two apart — an explicit closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after it in both cases; a controller killed mid-run fenced after takeover, its late commands refused; a -per-session lease owner killed while a mutation is in flight taking the +lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease, has activated nothing, and the previous holder's delayed command is refused on both the holder and the epoch check; diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index dd7f7937a..6c5d1b29a 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -132,7 +132,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `supervision_fault`, `listener_lost`) — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A per-session lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease releasing it explicitly on every exit path; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in two tiers, against `Loopex.Trace` as implemented rather than against ADR 0030's prose: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** the adapter module, entries for the three may exist and each is asserted to carry placeholders and no credential bytes and no token. That second tier holds because ADR 0034 binds the **shape**: the three carry credential bytes only under a credential-named key, which `@credential_pattern` placeholders at any size. It does not hold by size — running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim, and only a credential-keyed value placeholdered at every size — so the witness calls each of the three with a **one-byte** credential under a session naming the module, and asserts no entry contains that byte. A third case asserts the three identities, so neither tier can pass vacuously. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -1634,7 +1634,7 @@ plan names as new. It is the thing to check a change against. | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | The per-session lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause. The lease owner is not the component named in `stopping`, so the exit is classified rather than consumed, and the pid maps to `supervision_fault` — ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Lease owner ↔ connections** | `loopex_daemon` | The lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause. The lease owner is not the component named in `stopping`, so the exit is classified rather than consumed, and the pid maps to `supervision_fault` — ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index a15ff1f32..5d055e0e9 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -201,10 +201,13 @@ a fresh epoch before the successor's first command. The lease lives in the daemo for the daemon process's lifetime, never in the session journal or any durable record; every writer epoch is minted fresh and never reused, so a daemon restart leaves every session uncontrolled with every earlier epoch stale, and -the core keeps mandating no lease. A lease owner's failure is fatal to the -daemon instance rather than survivable: it holds the session's in-flight -admission set, which is what a takeover waits on, so losing it silently could -let a successor be granted while a forgotten admission could still settle. +the core keeps mandating no lease. One process holds every session's record +and in-flight set, serializing each session's transitions against its own +admissions; the lease is data, and the process count is topology. That +owner's failure is fatal to the daemon instance rather than survivable: it +holds the in-flight admission sets a takeover waits on, so losing it silently +could let a successor be granted while a forgotten admission could still +settle. Every connection closes and the daemon restarts. Cancellation crosses processes because the core owns dispatch: the current controller's `session.abort` cancels work an earlier controller started, with the truthful @@ -465,7 +468,7 @@ implementation that depends on it, not before unrelated work. | --- | --- | --- | | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence and the operator root-retirement procedure documented; a daemon-grade adapter and any migration are left open for a separate decision and prescribed nowhere | 1, 5 | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | -| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | +| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease **record** per session, held by one lease-owner process for the daemon, with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is named by an opaque token bound at composition and **resolved per invocation**, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | **Two design decisions are settled here rather than in an ADR**, because both @@ -474,15 +477,18 @@ recorded because getting either wrong would be expensive to discover later. **The daemon owns its own lifetime, through an owner process rather than a supervisor.** Its top-level component is one `GenServer` that traps exits and -`start_link`s seven processes: the five the composition function assembles in -its caller's process — the Store adapter, the runtime root, the artifact -transfers owner where enabled, the workspace lease and the local executor — -plus the daemon's own lease owner and listener. It keeps every pid, because +`start_link`s a **fixed set** of them: the five the composition function +assembles in its caller's process — the Store adapter, the runtime root, the +artifact transfers owner where enabled, the workspace lease and the local +executor — plus four of the daemon's own, the credential routing registry and +custody process ADR 0034 gives the host, one lease owner, and the listener. +Nine where transfers are enabled, eight where they are not; nothing here is +started per session or on demand. It keeps every pid, because each one is a component it must be able to name when that component dies. An exit the owner did not ask for is fatal, by that process's own clause, and that clause is what reads a dying Store's reason and turns it into the class the daemon reports. The exits the owner's own stop sequence causes are -consumed rather than classified — otherwise stopping the seven deliberately +consumed rather than classified — otherwise stopping them all deliberately would report a fatal class every time — and the technical companion states the one field that tells the two apart. It is not an OTP `Supervisor`: a supervisor offers no callback that can read a child's From ac5e4fbd48d0aecd105ee0efeea15c9e660dc264 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 23:53:10 -0700 Subject: [PATCH 066/585] adr(0034): exclude credential calls before delivery, as 0030 requires P0-F: ADR 0030-technical:27 requires the key-bearing call to be excluded by match specification. An earlier revision of ADR 0034 found no such mechanism and substituted namespace omission plus sink-time redaction -- which cannot satisfy it, because tracing delivers the raw call tuple to the tracer (trace.ex:331, :152, :219) before `Entry.render/2` ever runs, so a host naming the adapter would create one more message holding the credential. That substitution is withdrawn. M5 implements the requirement instead, as core's third change: `Loopex.Trace` gains an excluded-MFA list, installed by clearing each `{module, function, arity}` after the module pattern. Verified by probe at both toolchain pairs before being written: setting `{Probe, :_, :_}` to true covers 6 functions, clearing `{Probe, :secret, 1}` with false covers 1, and the tracer then receives the call to `visible/1` and nothing at all for `secret/1`. The excluded inventory is complete rather than illustrative. Besides the three ProviderBridge functions, the credential frame is encoded by the same generic encoder as every other frame -- `send/3` calls `encode/2` (provider_codec.ex:127-131, :87-92), which calls `valid_payload?/2` and `encode_value/4`, recursing through `encode_members/5`, `encode_pairs/4` and `encode_key/2,3` -- and `[:local]` tracing covers private calls. So `ProviderCodec` is excluded as a module; an MFA list of private helpers is rejected as a list that rots silently, and the cost of losing codec tracing is stated. The keyed-shape rule stays as defence in depth. ADR 0030 is not edited; its prose is honoured once this lands, and the change to an accepted ADR's subject matter is flagged as such in the plan. The explicit-tracing witness now reads the tracer rather than the sink, and asserts a non-excluded function still produces a message so it cannot pass by tracing nothing. --- ...andoff-over-bootstrap-channel-technical.md | 197 +++++++++--------- ...edential-handoff-over-bootstrap-channel.md | 21 +- docs/plans/M5-technical.md | 15 +- docs/plans/M5.md | 42 ++-- 4 files changed, 152 insertions(+), 123 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 5dac45537..4ce2c97c3 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -219,100 +219,104 @@ boundary, not an absolute: already protects that process — the sender installs its own group-leader sink so no IO request can carry anything out of it, it is unregistered, and it reports only an atom or a `{:error, atom}` pair to the guardian. -- **What actually keeps credential bytes out of a trace, verified against - `Loopex.Trace` rather than against prose.** ADR 0030's companion says "the - key-bearing call is excluded by match specification". No such mechanism - exists in the implementation, and this pair says so rather than promising - it: `Loopex.Trace` installs one pattern per **module**, - `:trace.function(session, {module, :_, :_}, match_spec(level), [:local])`, - with no function or arity selectivity, and its only exclusion is by **pid**, - decided inside core by role — the tracer itself and, on the diagnostics - sink, the dispatcher. There is no adapter-side API to exclude a pid and no - way to exclude one function of a traced module. **That prose-implementation - drift is a finding for the maintainer about an accepted ADR; M5 does not - edit ADR 0030 and its progress entry flags it.** - - What does hold is a two-tier property, and both tiers are real: - - 1. **The adapter is not in the default traced set.** A session's modules come - from `modules/1`, which expands the `:loopex` and `:loopex_protocol` - namespaces through `:application.get_key(application, :modules)` — the - application's own module list, and the code says why it is not a name - prefix: "reading the application's module list rather than matching a - name prefix keeps a module that merely starts with `Loopex` in some other - application out of the session." `Loopex.LLM.ReqLLM.ProviderBridge` lives - in `loopex_llm_reqllm`, so **no namespace wildcard reaches it**. Under - every default configuration the credential-bearing work is untraced, - which is the strong property and the one M5 proves first. - 2. **If a host explicitly names the adapter module**, its functions become - traceable — a host may name any module through the explicit-module route, - `supervised/1` recurses so the sender is in scope, and `process_flags/2` - sets `:set_on_spawn` on every non-root traced process — and what protects - the bytes then is the redaction pass, which *is* implemented. But it - protects them **only in one shape**, and that shape is therefore part of - this contract rather than an implementation detail. - - `Entry.render/2` calls `redact/3`, which placeholders a value whose - **key** matches `@credential_pattern` — `credential|secret|token|api[_-]? - key|password|authorization` — at any size, and otherwise placeholders a - binary only when it is **longer than `@identity_bytes`, which is 64**. - Bare list and tuple elements are walked with `key = nil` and a short - binary falls through to `redact(term, _, _) -> term`, returned verbatim. - - An earlier draft of this pair concluded from that code that a credential - is "redacted by size even as a bare positional argument". **That is - false**, and running `Entry.render/2` says so: - - | Credential size | Bare arg `[cred]` | Tuple `{:ok, cred}` | Keyed `%{credential: cred}` | - | --- | --- | --- | --- | - | 1 byte | **leaks** | **leaks** | placeholdered | - | 40 bytes | **leaks** | **leaks** | placeholdered | - | 51 bytes | **leaks** | **leaks** | placeholdered | - | 64 bytes | **leaks** | **leaks** | placeholdered | - | 65 bytes | placeholdered | placeholdered | placeholdered | - - ADR 0019 admits a credential of 1 to 65,536 bytes, so the leaking range - is real, not hypothetical. The size reading is withdrawn with those - numbers recorded. - - **So the shape is bound, and that is what makes the second tier true.** The - three functions below carry credential bytes **only as a value under a - credential-named key**, in every argument and every return value: - `receive_custody_reply/2` returns `{:ok, %{credential: bytes}}` and never - `{:ok, bytes}`; `write_credential_frame/2` takes that keyed map, not a bare - binary. Under `@credential_pattern` the key `credential` matches, so the - value is placeholdered at **any** size, including one byte. Nothing relies - on how long a credential happens to be. - - **The three functions stay, and their role is now precise.** They are not - match-specification targets, because those do not exist; they are **the only - functions that touch credential bytes, all executed in the sender process, - and all carrying them keyed**: - - | Function | What it touches | +- **What keeps credential bytes out of a trace: exclusion before delivery, + which M5 implements because ADR 0030 already requires it.** That accepted + companion says the key-bearing call "is excluded by match specification" + (`0030-…-technical.md:27`). An earlier revision of this pair found no such + mechanism in `Loopex.Trace` and substituted namespace omission plus + sink-time redaction. That substitution is withdrawn: redaction happens in + `Entry.render/2`, at the sink, while tracing delivers the **raw** call tuple + to the tracer process first (`trace.ex:331`, `:152`, `:219`). A host that + names the adapter module would therefore create another message carrying the + credential — one more place the bytes exist — which is precisely what the + "only permitted transfer" contract forbids. Redaction cannot satisfy a + pre-delivery requirement. + + **So M5 implements the requirement.** `Loopex.Trace` gains an excluded-MFA + list applied when a session's patterns are installed: the module pattern + first, then each excluded `{module, function, arity}` cleared. The mechanism + is the one `:trace.function/4` already supports, and it was verified by + probe at **both** toolchain pairs before being written here: + + ``` + :trace.function(session, {Probe, :_, :_}, true, [:local]) # => 6 + :trace.function(session, {Probe, :secret, 1}, false, [:local]) # => 1 + # tracer then receives, for a process calling both: + # {:trace, #PID<…>, :call, {Probe, :visible, ~c"\n"}} + # and nothing at all for Probe.secret/1 + ``` + + A later, more specific pattern replaces the module-wide one for that MFA, so + the excluded function is not traced at all — no raw message, nothing for the + tracer to hold, nothing for the sink to redact. This is core's **third** M5 + change, recorded as such in the plan's ownership table and minimalism + budget. + + **The excluded inventory is complete, and completeness is why it is drawn + this way.** Credential bytes and the token reach exactly two places in the + parent: + + | Excluded | Why | | --- | --- | | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | The registry handle and the token | | `Loopex.LLM.ReqLLM.ProviderBridge.receive_custody_reply/2` | The resolved credential | | `Loopex.LLM.ReqLLM.ProviderBridge.write_credential_frame/2` | The resolved credential | - - Naming them is what makes the witness precise and the redaction obligation - checkable: any credential byte in the parent passes through one of these - three and nowhere else. The names, the arities **and the keyed shape** are - the contract, and one case asserts all three: that the functions exist with - these identities, and that calling each with a **one-byte** credential under - a trace session naming the module explicitly produces no entry containing - that byte. One byte is the point — it is the size at which a size-based - redaction would fail and a shape-based one does not — so an inlining, a - rename, or a change that passes bytes bare breaks the proof loudly. - - **The proof is two cases, matching the two tiers.** Under the **default** - configuration, a real trace session at the `arguments` level over a real - invocation produces no entry naming any of the three, no raw trace message - for them, and no credential bytes or token anywhere in the captured entries. - Under a configuration that **explicitly names** `ProviderBridge`, entries for - the three may exist and every one of them is asserted to carry placeholders - and no credential bytes and no token. Proving only the first would leave the - case a host can actually create unproved. + | **`Loopex.LLM.ReqLLM.ProviderCodec`, every function** | The credential frame is encoded by the same generic encoder as every other frame: `send/3` calls `encode/2` (`provider_codec.ex:127-131`, `:87-92`), which calls `valid_payload?/2` and `encode_value/4`, which recurse through `encode_members/5`, `encode_pairs/4` and `encode_key/2,3`. `[:local]` tracing covers private calls, so every one of those frames carries the bytes | + + The codec is excluded as a **module** rather than as a list of private + MFAs, and the rejected option is recorded: an MFA list of private helpers + would be a list that rots silently, since a refactor inside the codec could + add a private function carrying the payload and no test would notice. The + cost is stated too — codec calls are not traceable for any frame — and it is + small, because the encode path is shared, so excluding only the + credential-carrying calls was never possible: the same functions encode + every frame. + + **The keyed shape stays, as defence in depth rather than as the mechanism.** + The three bridge functions carry credential bytes only as a value under a + credential-named key — `receive_custody_reply/2` returns + `{:ok, %{credential: bytes}}` and never `{:ok, bytes}`; + `write_credential_frame/2` takes that keyed map, not a bare binary — so if + an exclusion were ever lost, `@credential_pattern` still placeholders the + value at any size. That matters because the size rule alone does not: an + earlier draft of this pair concluded a credential is "redacted by size even + as a bare positional argument", and running `Entry.render/2` says otherwise. + + | Credential size | Bare arg `[cred]` | Tuple `{:ok, cred}` | Keyed `%{credential: cred}` | + | --- | --- | --- | --- | + | 1 byte | **leaks** | **leaks** | placeholdered | + | 40 bytes | **leaks** | **leaks** | placeholdered | + | 51 bytes | **leaks** | **leaks** | placeholdered | + | 64 bytes | **leaks** | **leaks** | placeholdered | + | 65 bytes | placeholdered | placeholdered | placeholdered | + + ADR 0019 admits a credential of 1 to 65,536 bytes, so the leaking range is + real. The size reading is withdrawn with those numbers recorded, and the + shape is contract. + + **ADR 0030 is not edited.** Its prose is honoured once this change lands, + and not before; until then the requirement is real and the implementation is + missing, which is the finding an earlier revision recorded and this one + closes rather than reinterprets. The alternative — amending ADR 0030 down to + what the code did — is rejected: it would weaken an accepted security + contract to match an omission. + + **The proof is three cases.** Under the **default** configuration, a real + trace session at the `arguments` level over a real invocation produces no + entry naming any excluded function, no raw trace message for them, and no + credential bytes or token anywhere in the captured entries — the adapter is + not in the default traced set, because `modules/1` expands the `:loopex` and + `:loopex_protocol` namespaces through `:application.get_key(application, + :modules)` and `Loopex.LLM.ReqLLM.ProviderBridge` is in + `loopex_llm_reqllm`. Under a configuration that **explicitly names** + `ProviderBridge` and `ProviderCodec`, the tracer is asserted to receive **no + raw trace message** for any excluded MFA — the pre-delivery property itself, + read from the tracer rather than from the sink — while a non-excluded + function of the same module is asserted to produce one, so the case cannot + pass by tracing nothing. A third case calls each of the three bridge + functions with a **one-byte** credential and asserts no captured entry + contains that byte, which is the keyed-shape tier and would fail under a + size-based rule. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or @@ -585,11 +589,14 @@ Three proofs are new: `receive_custody_reply/2` or `write_credential_frame/2`, no raw trace message for them, and no credential bytes or token anywhere — because the adapter is in no namespace wildcard. Under a configuration that - **explicitly names** `Loopex.LLM.ReqLLM.ProviderBridge`, entries for those - three may exist, and every one is asserted to carry placeholders and no - credential bytes and no token, which is what the redaction pass promises. A - third case asserts the three functions exist with their exact identities, so - neither of the first two can pass vacuously. + **explicitly names** `Loopex.LLM.ReqLLM.ProviderBridge` and + `Loopex.LLM.ReqLLM.ProviderCodec`, the tracer is asserted to receive **no + raw trace message** for any excluded MFA, while a non-excluded function of + the same module is asserted to produce one — the pre-delivery property read + where it holds, and a case that cannot pass by tracing nothing. A third case + asserts the three functions exist with their exact identities and that a + one-byte credential appears in no captured entry, so neither of the first + two can pass vacuously. - **Host custody, proved at each host rather than in the adapter.** The adapter's test tree cannot prove a claim about the CLI's or the daemon's composition, and an earlier draft filed all three there. Each case lives diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index a1475efa7..81bff143a 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -93,15 +93,18 @@ secret can be seen. What keeps those bytes out of a trace is stated against the implementation rather than against ADR 0030's prose, which claims a match-specification exclusion the tracer does not have: the adapter is in no default trace namespace, so the credential work is untraced under every -default configuration, and a host that explicitly names the adapter module -gets entries whose credential values the implemented redaction pass replaces -with placeholders — which holds because the companion binds the *shape*, so -those bytes always travel under a credential-named key and are placeholdered -at any size. It would not hold by size alone: the pass leaves a short binary -verbatim, and a credential may be one byte. The companion names the three functions that touch -credential bytes — they are the whole of the parent-side surface — and M5 -proves both tiers. The drift between ADR 0030's prose and its implementation -is flagged for the maintainer, not patched here. +default configuration; and where a host explicitly names the adapter module, +the credential-bearing functions are **excluded before a trace message is +delivered at all**, which is what ADR 0030 already requires and what M5 adds +to `Loopex.Trace` to honour. Redaction at the sink cannot serve that purpose, +because the raw call reaches the tracer first; it stays as defence in depth, +resting on a bound *shape* — those bytes always travel under a +credential-named key and are placeholdered at any size, which size alone would +not give, since the pass leaves a short binary verbatim and a credential may +be one byte. The companion names every excluded function and module — together +the whole of the parent-side surface — and M5 proves the exclusion at the +tracer rather than at the sink. ADR 0030 is not edited: its prose is honoured +once this lands. **Everywhere else the boundary is where the adapter's claims stop.** Inside it — the token, the sender, the frame, the child — the adapter proves what it diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 6c5d1b29a..a3b710146 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -37,7 +37,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace`'s excluded-MFA list, which keeps a named function out of a trace session before any message is delivered**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -135,7 +135,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease releasing it explicitly on every exit path; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in two tiers, against `Loopex.Trace` as implemented rather than against ADR 0030's prose: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** the adapter module, entries for the three may exist and each is asserted to carry placeholders and no credential bytes and no token. That second tier holds because ADR 0034 binds the **shape**: the three carry credential bytes only under a credential-named key, which `@credential_pattern` placeholders at any size. It does not hold by size — running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim, and only a credential-keyed value placeholdered at every size — so the witness calls each of the three with a **one-byte** credential under a session naming the module, and asserts no entry contains that byte. A third case asserts the three identities, so neither tier can pass vacuously. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in three tiers, against `Loopex.Trace` including the excluded-MFA list M5 adds to it: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec`, the tracer is asserted to receive **no raw trace message at all** for any excluded identity — read from the tracer process, which is where a pre-delivery claim is decidable — while a non-excluded function of the same module is asserted to produce one, so the case cannot pass by tracing nothing; and the keyed-shape tier, defence in depth if an exclusion were ever lost, calls each of the three bridge functions with a **one-byte** credential and asserts no captured entry contains that byte. The shape tier matters because size alone does not protect: running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim, and only a credential-keyed value placeholdered at every size. A fourth case asserts the three identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a module pattern installed and one `{module, function, arity}` cleared after it, with the tracer receiving the non-excluded call and nothing for the excluded one, at both toolchain pairs The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -1674,7 +1674,16 @@ daemon is a host and a host is an application. One daemon owner process, one new the two callers that need the edges assembled, `RuntimeOwner` and the daemon's owner, and which direct code cannot replace because the alternative is a second copy of the whole wiring layer. One socket listener, one narrow -core concurrent-attachment change, one read-only core existence query — which +core concurrent-attachment change, **one excluded-MFA list in `Loopex.Trace`** +— which unifies nothing and is not asked for by this milestone's features at +all: it exists because accepted ADR 0030 already requires that a key-bearing +call be excluded by match specification before delivery, and the +implementation did not do it. Direct code cannot supply it, because exclusion +has to happen where the patterns are installed; redaction at the sink is too +late, the raw call having already reached the tracer. It is the smallest form +of the requirement: a list of `{module, function, arity}` identities cleared +after the module pattern, using `:trace.function/4` exactly as it already +does. One read-only core existence query — which unifies the three daemon paths that must know whether an ID exists before doing anything with it (acquire, activation of a session the index does not hold, and the crash-cut recovery), and which direct code cannot supply, diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 5d055e0e9..c1cf46513 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -93,8 +93,8 @@ serves generation `loopex.experimental/2` only, which adds `session.list`, `daemon.status`, the two control methods and the writer-epoch field, and lifts the one-attachment-per-process rule to residency limits. It adds no durable method: core owns durable session truth and its M5 changes are concurrent -attachment and one read-only existence query, neither of which is a durable -command, so a daemon method that ended a session durably would have to add +attachment, one read-only existence query and `Loopex.Trace`'s excluded-MFA +list, none of which is a durable command, so a daemon method that ended a session durably would have to add one, which M5 does not do. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by @@ -109,8 +109,9 @@ effect dispatched, an interaction awaiting an answer, a recovery running, an unresolved `commit_unknown` or an admission executing inside core, so "idle" is not "quiescent" and stopping on idleness would destroy exactly what Outcome 1 exists to prove. And there is nothing to stop it with: core owns -coordinator lifetime, and M5's two core changes — concurrent attachment and a -read-only existence query — neither of them stops a coordinator. +coordinator lifetime, and M5's three core changes — concurrent attachment, a +read-only existence query, and `Loopex.Trace`'s excluded-MFA list — none of +them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation @@ -420,8 +421,9 @@ Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan ### Non-Goals No controller lease, transport, socket or collaboration rule inside core. Its -only M5 changes are independent concurrent attachment support and one -read-only session-existence query, neither of which is a durable command. No daemon-grade +only M5 changes are independent concurrent attachment support, one read-only +session-existence query, and the excluded-MFA list in `Loopex.Trace` that +accepted ADR 0030 already requires — none of which is a durable command. No daemon-grade store adapter, journal format version, migration, backup tooling, compaction, retention cutoff or NIF dependency; no daemon-served generation 1; no durable lease record; no exactly-once delivery promise beyond the founding @@ -811,18 +813,26 @@ remains Proposed and wholly deferred; decision 4 neither accepts nor partially implements it. ADRs 0019 and 0030 remain Accepted and unchanged, and nothing in this pair asks for an amendment to either. -**One drift flagged, not patched.** Accepted +**One drift closed by implementing it, not by amending it.** Accepted [ADR 0030](../adr/0030-observability-tracing-and-telemetry-technical.md#technical-depth) says "the key-bearing call is excluded by match specification". `Loopex.Trace` -has no such mechanism: it installs one pattern per module, `{module, :_, :_}`, -with no function or arity selectivity, and its only exclusion is by pid, -decided inside core by role. The sentence describes something the -implementation does not do. M5 does **not** edit ADR 0030 — an accepted ADR -changes through its own amendment path — and does not rely on the claim: ADR -0034 states the two properties that do hold, that the adapter is in no default -trace namespace and that the implemented redaction pass replaces credential -values with placeholders where a host names the module explicitly. The drift -is recorded here for the maintainer to disposition. +had no such mechanism: it installed one pattern per module, `{module, :_, :_}`, +with no function or arity selectivity, and its only exclusion was by pid. +An earlier revision of this plan recorded that as drift and leaned on +sink-time redaction instead — which cannot satisfy the requirement, because +tracing delivers the raw call to the tracer before any redaction runs, so a +host that named the adapter would create one more message holding the +credential. + +M5 therefore **implements what the accepted ADR already requires**, as core's +third change in this milestone: `Loopex.Trace` gains a list of excluded +`{module, function, arity}` identities, cleared after the module pattern is +installed, so an excluded function produces no trace message at all. The +mechanism was verified by probe at both toolchain pairs before it was written +down. ADR 0030 is **not** edited — an accepted ADR changes through its own +amendment path — and its prose is honoured once this change lands. This is a +change to an accepted ADR's subject matter rather than to its text, so it is +flagged for the maintainer as such. ## Governance Records From 171e05713c0b06e455f2e10b89aebe0907593845 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 23:54:15 -0700 Subject: [PATCH 067/585] adr(0034): make the credential token a struct, one per provider P1-G: the pair bound the token at composition in one section and said the caller "supplies" it per invocation in another, and defined its value as an opaque binary while refusing "a bare binary that could plausibly be bytes" -- a test nothing can apply, since a credential is a bare binary and many are alphabet-clean and under 256 bytes. The token is now `%Loopex.LLM.ReqLLM.CredentialToken{id: <<_::128>>}`, never a bare binary, one per configured provider, bound at composition and resolved once per invocation; the registry refuses anything that is not that struct, so the refusal is a pattern match rather than a judgement. `:invalid_token` and the failure table follow. ADR 0035 repeated "one token per call" in both files and called the generalisation a prerequisite amendment to ADR 0034. That was a misreading: one per provider is what ADR 0034 fixes, so a second provider is a second token, row and custody process composed the same way, and no amendment is required. Both files are corrected, including the compatibility note. --- ...andoff-over-bootstrap-channel-technical.md | 44 ++++++++++++++----- ...ision-models-as-policy-inputs-technical.md | 43 +++++++++--------- ...-typed-decision-models-as-policy-inputs.md | 14 +++--- 3 files changed, 61 insertions(+), 40 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 4ce2c97c3..49fa531e8 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -70,12 +70,33 @@ So a token "supplied with each call" has nowhere to arrive from. The token therefore sits in `options`, beside the registry handle, and is the same class as the executor `reference:` the runtime already takes and `LoopexComposition` already fills with a live process reference. Its value is -an **opaque token**: a binary of at most 256 bytes from ADR 0023's identifier -alphabet, carrying no structure the adapter interprets and no authority of its -own. It is not the credential, it does not name a module, and it cannot be -resolved by anyone not already holding the host's registry. Any other shape — -outside the alphabet, over the bound, or a bare binary that could plausibly be -bytes — is refused as an invalid option before any child is spawned. +a **struct**, not a binary: + +```elixir +%Loopex.LLM.ReqLLM.CredentialToken{id: <<_::128>>} +``` + +— sixteen random bytes under a tagged name, carrying no structure the adapter +interprets and no authority of its own. It is not the credential, it does not +name a module, and it cannot be resolved by anyone not already holding the +host's registry. The registry **refuses anything that is not that struct**, +and an option carrying anything else is refused as invalid before any child is +spawned. + +**A bare binary was the earlier shape, and it could not be validated.** That +revision called the token an opaque binary of at most 256 bytes from ADR +0023's alphabet and then said a bare binary "that could plausibly be bytes" is +refused — which is not decidable, because a credential *is* a bare binary and +many credentials are alphabet-clean and under 256 bytes. There is no content +test that separates a token from a secret. A struct separates them by type: +credential bytes never arrive as `%CredentialToken{}`, so the refusal is a +pattern match rather than a judgement, and a credential accidentally passed as +a token is refused at composition instead of being routed. + +**One token per configured provider, bound at composition.** A runtime that +names two providers carries two tokens, each with its own registry row and its +own custody process; it does not mint one per call. That is what makes ADR +0035's second credential a second row rather than a widened value. **Every later use of "per-invocation" in this pair qualifies the resolution.** On each call the sender routes the token through the handle, receives the @@ -136,8 +157,11 @@ separate: validates and hands to `complete/3` unchanged, so it is the seam that already exists for exactly this: something the host decides once, per runtime, that every invocation needs. Composition puts the registry - reference there, under its own key, beside the token the caller supplies per - invocation. + reference there, under its own key, beside the token — which composition + also puts there, once, per configured provider. An earlier sentence said + the caller supplies the token "per invocation"; that contradicted this + pair's own binding rule and is corrected: what happens per invocation is the + **resolution**, never the supply. - **It is a runtime-local capability handle, exactly the class the runtime already takes.** The precedent is the executor: `Loopex.Runtime`'s executor configuration carries `reference:`, and `LoopexComposition` fills it with @@ -358,7 +382,7 @@ produced, and nothing else is accepted. | Atom | Produced by | For | | --- | --- | --- | | `:no_token` | The adapter | The configuration carries no `:credential_token` at all | -| `:invalid_token` | The adapter | A token outside the identifier alphabet or over 256 bytes, refused before any lookup | +| `:invalid_token` | The adapter | A `:credential_token` that is not a `%Loopex.LLM.ReqLLM.CredentialToken{}` struct with a 16-byte `id`, refused before any lookup | | `:missing` | A custody process | It has no credential for this token | | `:expired` | A custody process | It has one and considers it no longer valid | | `:oversized` | The sender | A successful reply whose bytes fall outside 1 to 65,536 | @@ -395,7 +419,7 @@ leaves no retained copy of anything the resolver may have produced: | Condition | Outcome | | --- | --- | | No `:credential_token` in the configuration | `:no_token`, refused before the namespace is created and before any child is spawned | -| Malformed token — outside the identifier alphabet or over 256 bytes | `:invalid_token`, refused before any lookup and before any child is spawned | +| Malformed token — anything that is not a `%CredentialToken{}` struct with a 16-byte `id`, a bare binary included | `:invalid_token`, refused before any lookup and before any child is spawned. The struct is what makes this decidable: a credential is a bare binary, and no content test separates one from a token | | A successful custody reply that is malformed — not `{:ok, %{credential: binary}}`, a bare binary included | `:unavailable`; a bare binary is refused rather than accepted, because accepting it would carry bytes in a shape the redaction pass leaves verbatim below 65 bytes | | The registry holds no row for the token, the registry is gone, or the custody process is dead | `:unavailable`. The host recomposes; nothing is reconstructed, because the registry holds no bytes to reconstruct from | | Custody answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 194b3f7c5..43188e584 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -80,25 +80,23 @@ bounded plain-data contract stay out by the rules that already exclude them. `TYPESAFE_API_KEY` is a **second** provider credential, and this is the one place where this decision constrains an earlier one. [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) -fixes a per-invocation credential **token**, opaque to the adapter, routed by -a host-owned registry to the custody process that holds the bytes — and it -fixes **one** token per call, which is right for the one provider that exists -today. A second provider needs one token per provider: a call says which -credential is wanted, and a host composing both registers two tokens. ADR 0034 -does not define that, and this pair does not pretend it does — the -generalisation is **a prerequisite change to ADR 0034**, made by its own -amendment or by an ADR superseding it, proposed with the milestone that -accepts this decision. - -The token shape makes that change smaller than it would otherwise have been, -which is worth recording because it is the practical consequence of the -maintainer's decision of 2026-09-20. The registry already maps token to -custody process, so a second provider is a second row and a second token, not -a wider value: the option becomes one token per provider being invoked, -resolution looks up the row for the token that call carries, and nothing about -the registry's routing-only contents, custody, rotation, the -guardian-enforced deadline or the closed reason set changes. Until that change -is accepted and landed, this decision cannot be implemented, and nothing in M5 +fixes a credential **token** — a `%Loopex.LLM.ReqLLM.CredentialToken{}` +struct, opaque to the adapter, routed by a host-owned registry to the custody +process that holds the bytes — as **one per configured provider, bound at +composition**, with resolution happening per invocation. An earlier revision +of this pair said ADR 0034 fixed "one token per call" and called the +generalisation a prerequisite amendment. That was a misreading of ADR 0034, +and it is withdrawn: a second provider is a second token, a second registry +row and a second custody process, composed the same way the first is, and +**no amendment to ADR 0034 is required**. + +What remains true is the shape of the consequence. The registry maps token to +custody process, so a second provider costs a row rather than a wider value: +a runtime carries the token for each provider it is configured with, +resolution looks up the row for the token that invocation carries, and nothing +about the registry's routing-only contents, custody, rotation, the +guardian-enforced deadline or the closed reason set changes. Until ADR 0034 is +accepted and landed, this decision cannot be implemented, and nothing in M5 anticipates it. ### Seams, in the order they are worth doing @@ -186,10 +184,9 @@ Nothing public changes. The `Loopex.Policy` and `Loopex.Model` callbacks, the public protocol and its generations, public events, snapshots, artifacts, the executor protocol and every durable record are untouched. A runtime with no evaluation configured is byte-for-byte the runtime that exists today. The one -compatibility effect is on host composition, and it arrives with the -prerequisite amendment to ADR 0034 rather than with this pair: a credential -token becomes one per provider instead of one per call, and a host registers a -second routing row. +compatibility effect is on host composition and arrives with this pair: a host +that configures evaluation composes a second credential token, a second +registry row and a second custody process, exactly as it composes the first. Rollback is removing the evaluation. Every seam is an input, so a host that stops asking decides as it did before by the same path; a journaled answer diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md index 7bdbd8568..b827aa4c2 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -107,13 +107,13 @@ Three consequences are real costs rather than benefits, and are stated as such. It is a **second provider credential**, `TYPESAFE_API_KEY` alongside the model credential, which means [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept)'s -per-invocation credential **token** has to become one per provider rather than -one per call. ADR 0034 fixes one token per call and does not define that, so -the generalisation is a prerequisite amendment to it, proposed with the -milestone that accepts this decision; this one cannot be implemented before -that lands. Because a token is routed through a host-owned registry, a second -provider is a second row and a second token rather than a wider value, which -is what keeps that amendment small. The **state sent to the model** is bounded, redacted, provenance-typed +credential **token** — already one per configured provider, bound at +composition, with resolution happening per invocation — is composed a second +time, with a second registry row and a second custody process. No amendment to +ADR 0034 is needed for that: it is the arrangement that pair already fixes, +and an earlier revision of this one described it as "one token per call", +which ADR 0034 never said. A second provider is a second row and a second +token rather than a wider value. The **state sent to the model** is bounded, redacted, provenance-typed data the runtime already holds, under the same context-admission discipline that governs anything else staged for a provider; nothing new becomes sendable. And **latency and price are unmeasured** until the first real call; From fa3fc1b8ac1e935d53d1502407662c4433e21522 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sat, 19 Sep 2026 23:59:07 -0700 Subject: [PATCH 068/585] adr(0033): keep the per-session owner, scope its failure to the session Reverses this round's earlier P1-D edit on the maintainer's decision of 2026-09-20: ADR 0033 keeps one lease-owner process per session -- the process is the serialization boundary and the holder of that session's in-flight admission set -- and the rejected alternative, one process holding a record per session, is recorded with its date. Its failure is now session-scoped rather than daemon-fatal, which is the second half of the same decision. The daemon closes that session's controller attachment with `control_owner_lost`, leaves observers attached, and lets the next `session.acquire_control` start a fresh owner with a fresh epoch -- ADR 0033's own takeover mechanics for a lease that is gone. What is not claimed is stated: the daemon cannot know whether an admission the dead owner passed into core is still settling, and the fresh epoch is what keeps the old tenure from adding another. `supervision_fault` leaves the class set; `control_owner_lost` enters ADR 0032's generation-2 error inventory, digest and vectors. The plan gains the dynamic population and every question it raises: started on activation, stopped at daemon exit, bounded by the 64-activation ceiling rather than by a second number, and stopped in sequence after the listener and before the runtime -- sequence because each has no `terminate/2` to run and a concurrent stop would need a second wait rule and a way to attribute a timeout among sixty-four pids. Startup starts no owner; reverse cleanup therefore meets none. Witnesses: owner death leaves the daemon serving with the observer attached and yields a fresh epoch on re-acquire with the activation count unchanged, and the 65th activation starts no owner. --- ...tachment-residency-and-replay-technical.md | 13 +- ...controller-lease-and-takeover-technical.md | 121 +++++++++------- docs/plans/M5-technical.md | 131 ++++++++++++------ docs/plans/M5.md | 30 ++-- 4 files changed, 188 insertions(+), 107 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index d9a7ac06c..8d7666ff6 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -156,7 +156,7 @@ which no client requests and every client may receive: | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:supervision_fault`, `fatal:listener_lost`. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:listener_lost`. A lease owner's death is not among them: it closes one session's controller attachment with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | @@ -186,9 +186,18 @@ limits — five inputs, and generation 2 changes four of them: | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_pending`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_pending`, `control_owner_lost`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | | Limits | Unchanged from ADR 0023's ceilings | +**`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 +makes a lease owner's failure session-scoped: the daemon closes that session's +controller attachment, leaves its observers attached, and lets the next +acquisition start a fresh owner with a fresh epoch. The closing client is owed +a reason for a close it did not ask for, and this is it — distinct from +`control_held`, which refuses an acquisition, and from `control_pending`, +which times one out. It enters the ordered error list, the digest and the +generation-2 vectors with the others. + **`control_pending` is the acquisition timeout, and it was missing.** ADR 0033 refuses an acquisition whose own deadline elapses while it waits behind an unresolved admission, with a stable reason — and the inventory above claimed diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 70b3e367d..ab7e0b7c3 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -37,63 +37,80 @@ idempotency. Those remain the commit-authority fence, and they answer a different question — which coordinator owner may commit — than the writer epoch does, which is which client may drive. -**One lease-owner process per daemon**, holding **one lease record per -session**, serializes every lease read, grant, renewal, release and expiry -transition with that session's mutation-admission handoff, so a takeover -cannot pass a mutation whose holder check has already started but whose core -admission is unresolved; that admission first resolves, or the daemon's own -holder-and-epoch check refuses it before it ever reaches core. - -The serialization a session needs is against **its own** lease transitions, -and one process serializes each session's independently by holding each -session's record and in-flight set separately; sessions do not contend for -anything but that process's mailbox. An earlier revision required a process -per session. That is withdrawn on the maintainer's decision: it made the -daemon's process population dynamic, needing a retirement rule, a per-session -fatal semantics and a place for the population to be bounded, none of which -the lease itself asks for. **The lease is data; the process count is -topology.** - -**A lease owner's failure is fatal to that daemon instance, deliberately.** -The owner holds the session's in-flight admission set in its own memory, and -that set is the whole basis of the expiry rule below: a takeover is granted -only when it is empty. An owner that dies takes the set with it, so a -restarted owner cannot know whether an admission is still on its way into -core. An earlier draft had the daemon restart the owner and carry on with its -sockets intact; that was withdrawn on 2026-09-20, on an independent review's -finding, because a successor acquire -could then be granted while a forgotten admission was still able to settle. - -So the lease owner's failure is fatal to the daemon instance, and the daemon's -own structure supplies that without special-case code: the lease owner is one -of the fixed set of processes the daemon's owner process `start_link`s, the -owner traps exits, and its `{:EXIT, pid, reason}` clause classifies an exit it -did not ask for — which is every exit outside its own stop sequence — as -fatal, mapping this pid to `supervision_fault`. There are no restarts to configure and no strategy to get wrong. The -owner classifies the exit as `fatal:supervision_fault`, has the listener tell -every client, closes them, unlinks the socket and exits non-zero; the daemon -comes back with no lease anywhere, no connection and no session activated. No -successor acquire exists to be granted wrongly, because no connection -survives to make one. - -That rule stands on its own, and this pair does not lean on core to help it. -An earlier draft said core would fence the forgotten admission by epoch -regardless, making the daemon-fatal rule defence in depth. The maintainer -withdrew that on 2026-09-20 because it was not true: core never sees the -writer epoch, as the lease record above sets out, and the fences core does -have protect against a stale *coordinator owner* rather than a stale -*controller* — which is the gap this ADR exists to fill. So the daemon rule -is the only thing preventing a successor's grant from racing a forgotten -admission, and it has to be absolute for that reason. +One owner process per session serializes every lease read, grant, renewal, +release and expiry transition with that session's mutation-admission handoff, +so a takeover cannot pass a mutation whose holder check has already started +but whose core admission is unresolved; that admission first resolves, or the +daemon's own holder-and-epoch check refuses it before it ever reaches core. + +A revision of 2026-09-20 proposed collapsing these into one process for the +daemon holding a record per session. The maintainer rejected that on +2026-09-20 and kept the process per session: the process *is* the +serialization boundary and the holder of that session's in-flight admission +set, and collapsing it would put every session's lease transitions behind one +mailbox. The plan's companion states the population and its bound. + +**A lease owner's failure ends that session's collaboration state, not the +daemon**, on the maintainer's decision of 2026-09-20. The owner holds the +session's in-flight admission set in its own memory, and that set is the basis +of the expiry rule below: a takeover is granted only when it is empty. An +owner that dies takes the set with it, so no successor owner can inherit it — +and none tries to. What happens instead is exactly what happens when a lease +is gone by any other route: + +- the daemon closes that session's **controller** attachment with + `control_owner_lost`, the wire reason ADR 0032's generation-2 inventory + carries for it, and leaves every observer attached, because an observer + holds no lease and loses nothing; +- the lease itself is gone, held by nobody; +- the next `session.acquire_control` for that session starts a **fresh** + owner, holding no lease and no admission set, and mints a **fresh epoch** — + the same takeover mechanics this ADR already defines for a lease that has + been released. + +The fresh epoch is what makes the lost set harmless: a command admitted under +the dead owner's epoch cannot be accepted after the new grant, and a mutation +already inside core settles or refuses exactly once under the serial ownership +core enforces, which no lease transition can affect. What is *not* claimed is +that the daemon knows whether such a mutation is still settling; it does not, +and a successor's work is ordered after it by core rather than by the daemon. + +An earlier draft had the daemon restart the owner and carry on with its +sockets intact, and a 2026-09-20 revision made the failure fatal to the whole +daemon instance. Both are superseded by the decision above: the restart was +wrong because a restarted owner would claim an admission set it cannot know, +and daemon-fatal was more than the fault requires — one session's +collaboration state is not grounds to end every other session's. + +So a lease owner's failure is **session-scoped**, and the daemon's own +structure supplies that without special-case code: each lease owner is +`start_link`ed by the daemon's owner process, which traps exits, and its +`{:EXIT, pid, reason}` clause maps the pid to the session it belonged to +rather than to a daemon-wide class. Every other linked process the daemon +holds is still daemon-fatal; the lease owners are the one class with a +session-scoped rule, and the reason is the one above. There are no restarts to +configure and no strategy to get wrong: nothing is restarted, and the next +acquisition starts a new owner from nothing. + +**What this does not claim, stated because an earlier draft claimed it.** +Core never sees the writer epoch, as the lease record above sets out, and the +fences core does have protect against a stale *coordinator owner* rather than +a stale *controller* — which is the gap this ADR exists to fill. So the daemon +is the only thing keeping a successor's grant from racing an admission the +dead owner had already passed into core. What the session-scoped rule gives is +not that the race cannot exist; it is that the successor is granted a **fresh +epoch** and the dead controller's connection is closed, so no command from the +old tenure can be admitted afterwards, and the one admission already inside +core settles or refuses exactly once under core's own serial ownership. The +cost is the honest one: the daemon cannot tell a new controller whether an +earlier mutation is still settling, and does not pretend to. Retaining the in-flight set in a survivor was the alternative and was rejected: whichever process held it would then be the process whose failure loses it, so the window moves up one level rather than closing, and a daemon that cannot lose the set is a daemon that has made the set durable — a durable -lease record by another name, which this decision rejects for its own reasons. -The cost is real and is stated: one supervision fault takes the daemon down -and every client reconnects. That is the honest price of not inventing a -recovery for state whose whole purpose is to be exact. +lease record by another name, which this decision rejects for its own +reasons. Expiry and admission use the daemon's monotonic clock: a deadline is set only by a diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index a3b710146..6ddc1db7a 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -131,7 +131,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `supervision_fault`, `listener_lost`) — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease releasing it explicitly on every exit path; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -544,11 +544,12 @@ in full, and this list is derived from it rather than summarising it: `invalid_socket_path`, `socket_permission_unverified`, `session_index_too_large`, and one class per missing or invalid composition input; -- **while running**, one per linked component: `store_lost`, +- **while running**, one per linked component in the fixed set: `store_lost`, `store_capacity_exceeded`, `runtime_lost`, `transfers_lost`, - `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, - `supervision_fault` for the lease owner — the daemon-fatal rule ADR 0033 - defines — and `listener_lost`; + `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost` + and `listener_lost`. A lease owner's death is **not** in this list: it is + session-scoped, closes that session's controller with `control_owner_lost`, + and the daemon keeps running; - **from the signal handler**, `owner_lost`, the one class no component produces: a signal arrived and the owner that would run the shutdown is not there to receive it. @@ -717,11 +718,13 @@ runtime — rather than against a staged one the plan would have to invent: never reads, unlinks or binds the socket path. 5. **Read the session directory and build the index**, refusing at the recorded-entry bound. -6. **Start the lease owner.** -7. **Create the `0700` subdirectory and bind the `0600` socket**, read back +6. **Create the `0700` subdirectory and bind the `0600` socket**, read back and verify ownership and mode, and **capture the bound path's device and inode** — the identity the fail-stop unlink rule below compares against. -8. **Begin accepting**, then **print the readiness line**. +7. **Begin accepting**, then **print the readiness line**. + +No lease owner exists at this point, and none is started here: one is started +when a session is activated, which cannot happen before a client connects. A failure at any step exits non-zero with that step's reason class, after the reverse cleanup below, and touches nothing after it. @@ -759,19 +762,19 @@ shutdown, and three facts in the code force it. `{:ok, %Loopex.Runtime{}}` — a **struct**, not `{:ok, pid}` — so the runtime is not a startable child at all; a supervisor rejects that return. Beyond that, a supervisor offers no callback that can read a terminating child's - exit reason, so `store_lost`, `store_capacity_exceeded` and - `supervision_fault` would be indistinguishable at exactly the moment the - daemon must name one. + exit reason, so `store_lost`, `store_capacity_exceeded` and a lease owner's + session-scoped exit would be indistinguishable at exactly the moment the + daemon must tell them apart. So `apps/loopex_daemon` has one top-level process, `Loopex.Daemon.Owner`, a `GenServer` that traps exits and holds the links itself — the same pattern `RuntimeOwner` already uses, for the same reason. -**It links nine processes when artifact transfers are enabled, eight when -they are not.** Earlier drafts said four and then seven, each time having -counted the components the daemon *thinks* about rather than the processes -that actually exist. The set is fixed — nothing here is started dynamically, -per session or on demand — and it is this: +**It links a fixed set of eight processes — seven without artifact +transfers — and a bounded, dynamic population of lease owners beside them.** +Earlier drafts said four, then seven, each time having counted the components +the daemon *thinks* about rather than the processes that actually exist. The +fixed set is this: | Start order | Linked process | Where it comes from | Optional? | | --- | --- | --- | --- | @@ -782,8 +785,20 @@ per session or on demand — and it is this: | 5 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | | 6 | The local executor | `start_edge(Local, …)` | no | | 7 | The runtime root | `start_edge(Loopex, …)` | no | -| 8 | The lease owner | The daemon's own, under ADR 0033 — **one process for the daemon**, holding one lease record per session | no | -| 9 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | +| 8 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | + +**Beside them, one lease owner per activated session**, which ADR 0033 +requires and the maintainer confirmed on 2026-09-20 in preference to one +process holding a record per session. That population is dynamic, and every +question a dynamic population raises is answered here rather than left to the +implementation: + +| Question | Answer | +| --- | --- | +| When does one start? | When the session is **activated in this daemon lifetime** — by `session.create` or by `session.resume` — started and linked by the daemon's owner process, like every other linked process | +| When does one stop? | At daemon exit, and in the stop sequence below. There is no deactivation in M5, so there is no retirement rule to invent | +| How many can exist? | At most **64**, because activation is one-way and the activation ceiling is 64 per daemon lifetime; the 65th activation refuses with `activation_ceiling_reached` before any owner could be started. The population bound is the ceiling, not a second number | +| What does its death mean? | That **session's** collaboration state, not the daemon's — the one exception to fail-stop uniformity, below | **The registry and the custody process are first, and that is forced rather than chosen.** ADR 0034 makes the *host* own both, and for a daemon the host @@ -798,8 +813,14 @@ first, then the artifact placement and the executor's own edges, and the runtime last within that chain, because it depends on all of them. **The stop order is the reverse, with one deliberate exception.** Reversed: -listener, lease owner, runtime, executor, workspace lease, transfers, custody, -registry — and then **the Store, last of all**, out of reverse order. The +listener, then **every lease owner**, then runtime, executor, workspace lease, +transfers, custody, registry — and then **the Store, last of all**, out of +reverse order. The lease owners are stopped **in sequence, not concurrently**, +and they share one grace between them rather than each taking one: each stop +is a process with no `terminate/2` and nothing to release, so the sequence +costs no measurable time, while a concurrent stop would need a second wait +rule and a way to attribute a timeout to one of sixty-four pids. Sequence is +the smaller mechanism for the same result. The Store is moved to the end because its `terminate/2` releases the writer marker, and the marker must outlive every operation the owner can end; custody and registry hold nothing durable, so stopping them before it costs @@ -833,8 +854,8 @@ withdrawn design and are gone. earlier draft said "any linked exit, whatever the reason, is fatal", which is right for an exit the owner did not cause and wrong for every exit it does: an orderly stop terminates them all deliberately, so that rule would classify -step 1 as `listener_lost`, step 2 as `supervision_fault`, step 3's clean -return as `runtime_lost` — a daemon that could never exit `0`, and an +step 1 as `listener_lost`, every lease owner's stop as a lost controller, +step 3's clean return as `runtime_lost` — a daemon that could never exit `0`, and an idle-shutdown witness that could never pass. So the owner carries a `stopping` field naming **the one component it is @@ -1126,9 +1147,12 @@ chooses. *first*, before anything else is torn down, which is the right order for the one party that cannot see inside the daemon. -2. **The lease owner stops.** Every lease vanishes with it. Nothing durable is - involved, and no client is left holding one, because no connection survived - step 1. +2. **Every lease owner stops**, in sequence, sharing one grace. Every lease + vanishes with them. Nothing durable is involved, and no client is left + holding one, because no connection survived step 1. Their exits are + consumed like any other the owner asks for — a lease owner stopped here + closes no controller attachment and produces no `control_owner_lost`, + because there is no attachment left to close. 3. **The runtime stops, and this is where admitted work ends.** The helper for this step calls `Supervisor.stop(runtime_supervisor, :normal, grace)` on the pid the composition function handed it, with `grace` the **composed @@ -1355,14 +1379,14 @@ to write. the daemon still holds the marker this is unconditional. On the two store classes the marker is already gone, so the owner applies the identity rule above: stat the path, unlink on an equal device and inode, leave it alone - on anything else. **The runtime root, the lease owner, the registry, the + on anything else. **The runtime root, the lease owners, the registry, the custody process and the transfers owner are not stopped on this path**, and that is deliberate rather than an omission. A fail-stop is not a drain, and none of them owns anything that outlives the VM: the executor does, which is why step 3 exists, and the Store holds the marker, which is why step 4 does, while the transfers owner's open descriptors are closed by the operating system when the VM - goes. Stopping the lease owner would buy less here than on the ordered + goes. Stopping the lease owners would buy less here than on the ordered path, where the point was to stop the executor before it — on `executor_lost` there is no executor left to read the lease holder's `DOWN` at all. @@ -1395,9 +1419,9 @@ performs itself, then a halt that cannot hang. Store's marker release does not happen at the halt. On the ordered path that is fine — the Store was already stopped in step 4, and its `terminate/2` ran then. On the **fatal** path it was not fine, and an earlier draft left a real -hole: for the six classes where the Store is still alive (`runtime_lost`, -`transfers_lost`, `workspace_lease_lost`, `executor_lost`, -`supervision_fault`, `listener_lost`), nothing stopped the Store, so the halt +hole: for the seven classes where the Store is still alive (`runtime_lost`, +`transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, +`custody_lost`, `listener_lost`), nothing stopped the Store, so the halt left the marker file behind on a daemon that had shut down deliberately. The fail-stop path above therefore stops the Store on every fatal class **except** the two store classes, where it is already gone. @@ -1432,9 +1456,20 @@ die without a name for it. | `registry_lost` | The credential routing registry exited | `fatal:registry_lost` | | `custody_lost` | The credential custody process exited | `fatal:custody_lost` | | `runtime_lost` | The runtime root exited | `fatal:runtime_lost` | -| `supervision_fault` | The lease owner exited — ADR 0033's daemon-fatal rule | `fatal:supervision_fault` | | `listener_lost` | The listener exited | `fatal:listener_lost` | +**A lease owner's exit is the one that is not in this table**, and its absence +is the rule rather than an omission. The owner's clause maps that pid to the +session it belonged to and handles it per session: the daemon closes that +session's controller attachment with `control_owner_lost`, leaves every +observer attached, and keeps serving every other session. The next +`session.acquire_control` for it starts a fresh owner with a fresh epoch, on +ADR 0033's ordinary takeover mechanics. The reason is stated there and it is +proportionality: one session's collaboration state is not grounds to end every +other session's, and the daemon-wide rows above are all components whose loss +leaves *nothing* working. `supervision_fault` is therefore gone from the class +set; a lease owner produces no daemon exit class at all. + The rows are named rather than numbered, because a number is a fact about the start order and this table is a fact about which pid died; the two drifted apart in an earlier revision and the numbers are gone for that reason. There @@ -1477,8 +1512,9 @@ vocabulary of what an exit may say. step unwinds what that step and its predecessors did, in reverse — and "predecessors" means **every process the startup started**, not the three an earlier revision named. A bound socket is closed and its path unlinked, a -`daemon/` subdirectory the owner created is removed, the lease owner is -stopped, **every pid the composition function returned is stopped in reverse +`daemon/` subdirectory the owner created is removed — no lease owner can exist +yet, since none is started before a session is activated — and **every pid the +composition function returned is stopped in reverse start order** — runtime, executor, workspace lease, transfers where it exists — then custody and the registry, and the Store last, so its `terminate/2` releases the marker. @@ -1548,16 +1584,17 @@ the cause and try again without a recovery step. was stopped — and that the stop *returned* rather than timing out into a kill — before the halt, so its cleanup ran and no operating-system child is left behind. -- **One class per linked component.** Each linked process is +- **One class per linked component of the fixed set.** Each is killed in turn, in its own case, and the daemon is asserted to exit with that component's class, to send that component's `fatal:` on the wire - where a socket still exists, and — for the six classes where the Store is + where a socket still exists, and — for the seven classes where the Store is still alive — **to leave no stale marker**, proved by the next daemon opening that root with nothing to recover — `runtime_lost`, `transfers_lost`, - `workspace_lease_lost`, `executor_lost`, `supervision_fault`, - `listener_lost`, beside the two store classes. The set is closed, so a - linked process dying without a class is a failing case rather than a silent - `:shutdown`. + `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, + `listener_lost`, beside the two store classes. The set is closed for the + fixed set, so one of those dying without a class is a failing case rather + than a silent `:shutdown`. A lease owner is deliberately not in this case: + its own witness is below, and it asserts the daemon **keeps running**. - **A successor's socket survives its predecessor's exit.** Two daemons on one root. The first is paused between the Store's marker release and its unlink — the fail-stop window, reached by making the Store terminate and @@ -1584,6 +1621,20 @@ the cause and try again without a recovery step. - **`owner_lost`.** The owner is killed while the daemon is otherwise healthy, then `SIGTERM` is delivered. The process halts with `fatal:owner_lost` on `stderr` rather than sitting with a handler and no owner. +- **A lease owner's death is session-scoped.** A session is activated, a + controller acquires it and an observer attaches; that session's lease owner + is killed. The case asserts the **daemon keeps running** — every other + session still serves, and the process does not exit — that the controller's + attachment closes with `control_owner_lost` while the observer stays + attached and keeps receiving events, that a following + `session.acquire_control` succeeds and returns an epoch **different** from + the dead owner's, and that the activation count is **unchanged**, because a + fresh owner is not a fresh activation. +- **The lease-owner population is bounded by the activation ceiling.** A + daemon driven to its 64th activation holds 64 owners; the 65th activation + refuses with `activation_ceiling_reached` and the case asserts **no + sixty-fifth owner was started**, so the population bound is the ceiling + rather than a second limit that could drift from it. - **The credential processes are fatal like every other component.** The registry and the custody process are each killed in their own case; the daemon exits `registry_lost` and `custody_lost` respectively, sends that @@ -1634,7 +1685,7 @@ plan names as new. It is the thing to check a change against. | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | The lease owner dies, taking the in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause. The lease owner is not the component named in `stopping`, so the exit is classified rather than consumed, and the pid maps to `supervision_fault` — ADR 0033's daemon-fatal rule, obtained from one clause rather than from a strategy | `daemon.stopping` with `fatal:supervision_fault`, then every connection closes; the daemon restarts uncontrolled | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched | +| **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies, taking that session's in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller attachment closes with `control_owner_lost`; observers stay attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index c1cf46513..8c7fcf84b 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -202,14 +202,15 @@ a fresh epoch before the successor's first command. The lease lives in the daemo for the daemon process's lifetime, never in the session journal or any durable record; every writer epoch is minted fresh and never reused, so a daemon restart leaves every session uncontrolled with every earlier epoch stale, and -the core keeps mandating no lease. One process holds every session's record -and in-flight set, serializing each session's transitions against its own -admissions; the lease is data, and the process count is topology. That -owner's failure is fatal to the daemon instance rather than survivable: it -holds the in-flight admission sets a takeover waits on, so losing it silently -could let a successor be granted while a forgotten admission could still -settle. -Every connection closes and the daemon restarts. Cancellation +the core keeps mandating no lease. One owner process per session serializes that +session's transitions against its own admissions. Its failure is scoped to +that session rather than to the daemon, on the maintainer's decision of +2026-09-20: the controller attachment closes with `control_owner_lost`, every +observer stays, and the next acquisition starts a fresh owner with a fresh +epoch — the takeover mechanics that already exist for a released lease. What +the daemon does not claim is that it knows whether an admission the dead owner +passed into core is still settling; the fresh epoch is what keeps the old +tenure from adding another. Cancellation crosses processes because the core owns dispatch: the current controller's `session.abort` cancels work an earlier controller started, with the truthful two-phase outcome the core already commits. @@ -470,7 +471,7 @@ implementation that depends on it, not before unrelated work. | --- | --- | --- | | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | The daemon's store for `0.2.0` is the existing local adapter, with its 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence and the operator root-retirement procedure documented; a daemon-grade adapter and any migration are left open for a separate decision and prescribed nowhere | 1, 5 | | [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2 and its methods, refusal of a generation-1-only client, owner-only peer access, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment, idle eviction and bounded session pages | 1, 2, 4 | -| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease **record** per session, held by one lease-owner process for the daemon, with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | +| [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session, held by its own lease-owner process, with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is named by an opaque token bound at composition and **resolved per invocation**, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | **Two design decisions are settled here rather than in an ADR**, because both @@ -482,10 +483,13 @@ supervisor.** Its top-level component is one `GenServer` that traps exits and `start_link`s a **fixed set** of them: the five the composition function assembles in its caller's process — the Store adapter, the runtime root, the artifact transfers owner where enabled, the workspace lease and the local -executor — plus four of the daemon's own, the credential routing registry and -custody process ADR 0034 gives the host, one lease owner, and the listener. -Nine where transfers are enabled, eight where they are not; nothing here is -started per session or on demand. It keeps every pid, because +executor — plus three of the daemon's own, the credential routing registry and +custody process ADR 0034 gives the host, and the listener. Eight where +transfers are enabled, seven where they are not. **Beside them it links one +lease owner per activated session**, a population bounded by the 64-activation +ceiling, and that one class is session-scoped rather than daemon-fatal: its +death closes that session's controller attachment and leaves every other +session serving. It keeps every pid, because each one is a component it must be able to name when that component dies. An exit the owner did not ask for is fatal, by that process's own clause, and that clause is what reads a dying Store's reason and turns it into the class From d129dc53f81206a5acbdae119a09dd6c77667d23 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 00:01:56 -0700 Subject: [PATCH 069/585] plan(M5): give the drain a mechanism, core's quiesce/2 Reverses this round's earlier P1-B edit on the maintainer's decision of 2026-09-20. The Concept's drain promise stays and gains a mechanism: a fourth core change, `Loopex.Runtime.quiesce(runtime, deadline_ms)`, returning the sessions that settled and those that did not. It is defined only in terms of what exists. Every active coordinator refuses new commands; what is in flight is driven through the cancellation a coordinator already runs for an abort, under the bounds `Loopex.Executor.cancellation_bounds/1` derives from the session's committed cleanup grace (executor.ex:456-474, used at session_coordinator.ex:3614 and :5366); `Loopex.Runtime.Control` already holds every active session and its coordinator pid. No new bound, no new callback, no durable command, and plain data at the boundary. The limit is stated from the numbers: `cancellation_bounds/1` derives an executor observation bound of `max(10_000, grace_ms + 2_000)` (executor.ex:458), so a daemon composed with a grace under about ten seconds reaches its deadline while an effect is still inside the executor's bound. That effect is reported unsettled and ended crash-equivalently -- the deadline is the daemon's, not the executor's. Outcome 1 now states both halves: settled work carries its ordinary terminal facts, including `cancelled` where a cancellation truly produced one, and unsettled work claims no terminal at all and reconciles at the next activation. The orderly sequence becomes six steps with the drain second and the stop record after it, as the Concept always promised. The rejected smaller design -- refuse, tell, close, tear down -- is recorded with its date. The minimalism budget says what quiesce unifies: nothing today, and the app server does not drain by hand (host.ex:76-79); it earns its place because no other component may own it. --- docs/plans/M5-technical.md | 192 ++++++++++++++++++++++++++----------- docs/plans/M5.md | 65 +++++++------ 2 files changed, 175 insertions(+), 82 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 6ddc1db7a..52da577cb 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -37,7 +37,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace`'s excluded-MFA list, which keeps a named function out of a trace session before any message is delivered**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace`'s excluded-MFA list, which keeps a named function out of a trace session before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -130,7 +130,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, a dispatched tool effect and an unresolved mutation ended crash-equivalently once the cleanup grace elapses with **no terminal claimed for either** — no `cancelled`, no `outcome_unknown`, no abort record — the ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` driving every active coordinator to settle within the composed cleanup grace and naming the sessions that did and did not — **both halves asserted**: a dispatched tool effect that settles inside the grace carries its ordinary terminal fact in the journal, and one held past the deadline is ended crash-equivalently with **no terminal claimed for it** — no `cancelled`, no `outcome_unknown`, no abort record — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -1131,30 +1131,37 @@ running with a handler and no owner. That class is in the exit list above and in the fatal-class map's note, and it is the one class no linked component produces. -**Daemon-initiated shutdown is the owner stopping its children, in reverse -order.** `SIGTERM` or `SIGINT` reaches the owner, which performs these four +**Daemon-initiated shutdown is a drain and then a teardown, in reverse +order.** `SIGTERM` or `SIGINT` reaches the owner, which performs these six steps itself. They are the owner's code, not a supervisor's behaviour, which -is what lets each one carry a reason and lets step 3 use a bound the owner -chooses. - -1. **The listener stops first, and the socket path is unlinked with it.** It - stops accepting, so a new connection is refused rather than queued; it - attempts one `daemon.stopping` naming `operator_stop` per open connection, - bounded best-effort as ADR 0032 fixes — one write attempt into the existing - 4 MiB output buffer — and closes it. **Then the owner unlinks the socket - path, here and not at the end**, because this is the last moment at which - the daemon is certainly still the marker holder. Clients therefore learn - *first*, before anything else is torn - down, which is the right order for the one party that cannot see inside the - daemon. -2. **Every lease owner stops**, in sequence, sharing one grace. Every lease +is what lets each one carry a reason and lets the teardown use a bound the +owner chooses. + +1. **The listener stops accepting, and the daemon refuses new admissions.** + A new connection is refused rather than queued, and a command arriving on + an open connection is refused from that instant. Nothing is written to + clients yet and nothing is closed: the connections stay open across the + drain, because a client that is about to be told something true is better + served by being told it than by an early close. +2. **The runtime is quiesced within the composed cleanup grace.** The owner + calls core's `quiesce/2` and waits for its answer, which names the sessions + that settled and the sessions that did not. This is the drain, and it is + the step that makes the Concept's promise true rather than aspirational; + what it does, and what it cannot do, is set out below. +3. **Clients are told, and the socket path is unlinked.** Each open connection + gets one `daemon.stopping` naming `operator_stop`, bounded best-effort as + ADR 0032 fixes — one write attempt into the existing 4 MiB output buffer — + and is closed. **Then the owner unlinks the socket path, here and not at + the end**, because this is the last moment at which the daemon is certainly + still the marker holder. +4. **Every lease owner stops**, in sequence, sharing one grace. Every lease vanishes with them. Nothing durable is involved, and no client is left - holding one, because no connection survived step 1. Their exits are + holding one, because no connection survived step 3. Their exits are consumed like any other the owner asks for — a lease owner stopped here closes no controller attachment and produces no `control_owner_lost`, because there is no attachment left to close. -3. **The runtime stops, and this is where admitted work ends.** The helper - for this step calls `Supervisor.stop(runtime_supervisor, :normal, grace)` +5. **The runtime stops, and this is where whatever did not settle ends.** The + helper for this step calls `Supervisor.stop(runtime_supervisor, :normal, grace)` on the pid the composition function handed it, with `grace` the **composed cleanup grace** — the same value the sessions were composed with, so no number is introduced. It does **not** call `Loopex.Runtime.stop/1`: that is @@ -1197,14 +1204,14 @@ chooses. supervision subtree without racing its own teardown, and a loop that walked `which_children` would be reading a tree that is already dissolving. -4. **The remaining composed edges stop, then the Store last.** Reverse start +6. **The remaining composed edges stop, then the Store last.** Reverse start order puts the executor, the workspace lease and the transfers owner between the runtime and the Store, and each is stopped in turn — the executor first, since it is the one with OS effects to clean up and it traps exits to do so. Then custody and the registry, which hold nothing durable. Then the Store, whose `terminate/2` releases the writer marker — see the marker invariant in ADR 0031. The socket path is already gone, - unlinked in step 1, so the last act is the halt: **`0`**, or the class, + unlinked in step 3, so the last act is the halt: **`0`**, or the class, in the case above where something failed on the way out. **The executor is stopped before the lease, and that order is load-bearing** @@ -1217,7 +1224,7 @@ chooses. **Each of these four is a helper calling `GenServer.stop(pid, :normal, bound)`, with the owner waiting on its own - link** — the same rule as step 3, and all four are `GenServer`s + link** — the same rule as step 5, and all four are `GenServer`s (`executor.ex:22`, `workspace_lease.ex:15`, `transfers.ex:26`, `local.ex:55`), so the same call fits all four. The bounds: @@ -1229,7 +1236,7 @@ chooses. | The Store | The same grace | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | No new number enters: every bound here is the composed cleanup grace, - which is what step 3 uses and what the sessions carry. Splitting it into + which is what step 5 uses and what the sessions carry. Splitting it into fractions would mean inventing ratios, and the minimalism budget takes every number from an accepted or proposed decision. Three of the four are ceilings rather than expected waits; only the executor is expected to spend @@ -1288,11 +1295,70 @@ chooses. is why recovery rather than release is what lets a successor open the path. -One ordering consequence is worth stating because it reverses an earlier -draft: clients are told *before* the teardown, not after. That is deliberate. -The teardown does not need connections to exist, and a client that must -reconnect elsewhere is better served by learning immediately than by waiting -out a cleanup grace it cannot see. +**What quiesce is, and why it is core's.** The Concept promises that an +orderly stop drains admitted work within the cleanup grace. A revision of this +file withdrew that promise for want of a mechanism; the maintainer restored it +on 2026-09-20 and gave it one. The mechanism is a **fourth core change**, +beside concurrent attachment, the existence query and the trace exclusion: + +```elixir +Loopex.Runtime.quiesce(runtime, deadline_ms) :: + {:ok, %{settled: [session_id], unsettled: [session_id]}} +``` + +It is defined entirely in terms of mechanisms that already exist: + +- **Refusal comes first.** Every active coordinator stops admitting new + commands for the duration. Nothing new can be started while the drain runs, + and no client command can arrive anyway, because step 1 has already refused + admissions at the daemon. +- **What is in flight is driven through the cancellation that exists**, not + through a new one. That is the sequence a coordinator already runs for an + abort: `Loopex.Executor.cancel/4` under the bounds + `Loopex.Executor.cancellation_bounds/1` derives from the session's committed + cleanup grace (`executor.ex:456-474`), which the coordinator already uses at + `session_coordinator.ex:3614` and `:5366`. Quiesce adds no bound, no + callback and no durable command. +- **It returns when every coordinator has settled or the deadline passes**, + naming both sets. `Loopex.Runtime.Control` already holds every active + session and its coordinator pid, so there is nowhere else this could live + and nothing to enumerate that core does not already have. + +**Why core rather than the daemon.** The daemon cannot do this without +reaching into coordinator internals, which the dependency direction forbids, +or running a cancellation loop of its own, which is precisely the second loop +this milestone forbids. Core owns coordinator lifetime and cancellation, so +core is where a bounded settle belongs. It returns **plain data** — session +IDs and two lists — so nothing about a coordinator crosses the boundary. + +**What it does not promise, stated because the numbers say so.** +`cancellation_bounds/1` derives an executor observation bound of +`max(10_000, grace_ms + 2_000)` (`executor.ex:458`). A daemon composed with a +cleanup grace below about ten seconds will therefore reach its own deadline +while an effect's cancellation is still within *its* bound. That effect is +reported **unsettled**, and the teardown ends it crash-equivalently: the +deadline is the daemon's, not the executor's, and quiesce does not extend one +to satisfy the other. + +So the outcome has two halves and both are said: **work that settled within +the grace has its ordinary terminal facts in the journal** — including +`cancelled` where a cancellation produced one, which is a true statement about +work that was actually cancelled — and **work that did not settle is left +unclaimed**, its ambiguous mutation `commit_unknown`, reconciled to exactly +one outcome at the next activation. The negative an earlier revision asserted +without qualification — that no terminal is ever claimed — is now the precise +one: no terminal is claimed for work that did not settle. + +The rejected option is recorded: the smaller design with no drain at all — +refuse, tell, close, tear down — which this file carried for one revision. The +maintainer rejected it on 2026-09-20. It was smaller, and it was also a +daemon that told an operator nothing about whether its work had finished. + +One ordering consequence follows from the drain and reverses an earlier +revision of this file: clients are told **after** it, not before. A client +that waits a few seconds and then learns the true reason is better served than +one told early about work whose fate was not yet decided, and the connections +stay open across the drain so that the record can still be written. **And "told" is an attempt, not a guarantee.** The write is one attempt into the existing 4 MiB output buffer, on a transport the client may already have @@ -1311,14 +1377,12 @@ have the daemon issuing mutations on nobody's authority, at the moment it is least able to see them through. An unbounded natural drain would make `SIGTERM` unbounded, which is not a stop. -**Nor does the daemon drain.** No step waits for admitted work to finish: the -runtime stop is bounded by the composed cleanup grace and ends what has not -finished crash-equivalently, and the grace bounds the teardown rather than the -work. An earlier revision of the Concept file promised a drain and a -settlement through cancellation bounds; neither had a mechanism here — -coordinators are temporary children with no drain callback -(`session_coordinator.ex:133-142`) — and both are withdrawn rather than -restated. +**The drain is core's, not the daemon's**, and that is the same rule seen from +the other side. The daemon asks for a bounded settle and waits for the answer; +every decision inside it — which effect to cancel, under what bound, what to +record — is the coordinator's, running the paths it already has. The daemon +neither issues a cancellation nor interprets one, and a coordinator that +cannot settle in time is reported rather than overridden. **Store loss, a fail-stop path.** The owner holds the Store's link and its pid, so the adapter's termination arrives as `{:EXIT, store_pid, reason}` at @@ -1350,7 +1414,7 @@ to write. the component that already died — under the same discipline as every other stop: a monitored helper calling `GenServer.stop(pid, :normal, grace)`, the owner waiting on its own link with `after grace` and killing on expiry, and - the composed cleanup grace the ordered path's step 4 uses. This is not tidiness: the executor is + the composed cleanup grace the ordered path's step 6 uses. This is not tidiness: the executor is the one linked process that owns effects outside the VM, and it traps exits precisely so it can clean them up. Halting without stopping it would end that cleanup where it stood. The residual is the one stated there and is @@ -1383,8 +1447,8 @@ to write. custody process and the transfers owner are not stopped on this path**, and that is deliberate rather than an omission. A fail-stop is not a drain, and none of them owns anything that outlives the VM: the executor does, which - is why step 3 exists, and - the Store holds the marker, which is why step 4 does, while the transfers + is why step 3 of this path exists, and + the Store holds the marker, which is why step 4 of it does, while the transfers owner's open descriptors are closed by the operating system when the VM goes. Stopping the lease owners would buy less here than on the ordered path, where the point was to stop the executor before it — on @@ -1417,7 +1481,7 @@ performs itself, then a halt that cannot hang. **One consequence this had to fix.** `terminate/2` not running means the Store's marker release does not happen at the halt. On the ordered path that -is fine — the Store was already stopped in step 4, and its `terminate/2` ran +is fine — the Store was already stopped in step 6, and its `terminate/2` ran then. On the **fatal** path it was not fine, and an earlier draft left a real hole: for the seven classes where the Store is still alive (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, @@ -1562,17 +1626,26 @@ the cause and try again without a recovery step. Store still stopped, the socket still unlinked — and that the exit class is `transfers_lost` rather than `operator_stop`, because the component died of its own reason and not because the owner asked. -- **In-flight shutdown.** A daemon with a dispatched tool effect and an - unresolved mutation receives `SIGTERM`. What has not settled within the - cleanup grace is ended crash-equivalently, and the case asserts the negative - that matters: **no terminal mutation is claimed** for it — no `cancelled`, - no `outcome_unknown`, no abort record appears in the journal on the way - down. The ambiguous mutation stays `commit_unknown`, each client is sent the - stop reason on a transport that accepts it and sees the close either way, - and the exit is still `0`. Activating that session again - afterwards resolves the transaction to exactly one outcome through the - existing reconciliation, and the journal is byte-identical to what an - abrupt death at the same instant would have left. +- **In-flight shutdown, both halves of it.** Two cases, because the drain + has two outcomes and proving one would hide the other. + + *It settles.* A daemon with a dispatched tool effect that **can** be + cancelled inside the composed cleanup grace receives `SIGTERM`. The case + asserts the effect settles during `quiesce/2`, that its session is in the + returned `settled` list, that the journal carries its ordinary terminal + fact, and that the `daemon.stopping` record is written **after** the drain + rather than before it. + + *It does not.* A daemon with an effect held past the deadline and an + unresolved mutation receives `SIGTERM`. The case asserts the session is in + the `unsettled` list, and then the negative that matters: **no terminal + mutation is claimed** for it — no `cancelled`, no `outcome_unknown`, no + abort record appears in the journal on the way down. The ambiguous mutation + stays `commit_unknown`, each client is sent the stop reason on a transport + that accepts it and sees the close either way, and the exit is still `0`. + Activating that session again afterwards resolves the transaction to exactly + one outcome through the existing reconciliation, and the journal is + byte-identical to what an abrupt death at the same instant would have left. - **Store-loss fail-stop.** The Store is made to terminate under a live listener. The case asserts the daemon observed it, closed the listener and every connection with `store_lost`, unlinked the socket, and exited non-zero @@ -1734,7 +1807,18 @@ has to happen where the patterns are installed; redaction at the sink is too late, the raw call having already reached the tracer. It is the smallest form of the requirement: a list of `{module, function, arity}` identities cleared after the module pattern, using `:trace.function/4` exactly as it already -does. One read-only core existence query — which +does. **One bounded `quiesce/2`** — which unifies nothing today and says so: +its only caller is the daemon's orderly stop, and the app-server host does not +drain by hand, because `LoopexComposition.with_runtime/2` brackets a runtime +that lives and dies with one client's stdin and has nothing to drain +(`host.ex:76-79`). It earns its place another way: an outcome of this +milestone promises a bounded drain, and there is no other place the mechanism +can live. Core owns coordinator lifetime and cancellation; a daemon-side drain +would read coordinator internals, which the dependency direction forbids, or +run its own cancellation loop, which is the second loop this milestone +forbids. It adds no bound and no durable command — it drives the cancellation +sequence and the bounds core already has — and it returns plain data. One +read-only core existence query — which unifies the three daemon paths that must know whether an ID exists before doing anything with it (acquire, activation of a session the index does not hold, and the crash-cut recovery), and which direct code cannot supply, diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 8c7fcf84b..b97d2261b 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -48,7 +48,7 @@ transport, no second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, attempts one stop record per client, closes every connection, unlinks the socket while the marker is still held, and then ends admitted work crash-equivalently within the composed cleanup grace, claiming **no terminal outcome** for it and leaving the ambiguous mutation as fenced `commit_unknown` for the reconciliation that already exists, stopping the Store last and exiting `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, **drains admitted work within the composed cleanup grace** through core's `quiesce/2` — every active coordinator refusing new commands while what is in flight is driven through the cancellation sequence that already exists, to the bounds it already derives — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -93,8 +93,8 @@ serves generation `loopex.experimental/2` only, which adds `session.list`, `daemon.status`, the two control methods and the writer-epoch field, and lifts the one-attachment-per-process rule to residency limits. It adds no durable method: core owns durable session truth and its M5 changes are concurrent -attachment, one read-only existence query and `Loopex.Trace`'s excluded-MFA -list, none of which is a durable command, so a daemon method that ended a session durably would have to add +attachment, one read-only existence query, `Loopex.Trace`'s excluded-MFA list +and the bounded `quiesce/2`, none of which is a durable command, so a daemon method that ended a session durably would have to add one, which M5 does not do. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by @@ -109,9 +109,9 @@ effect dispatched, an interaction awaiting an answer, a recovery running, an unresolved `commit_unknown` or an admission executing inside core, so "idle" is not "quiescent" and stopping on idleness would destroy exactly what Outcome 1 exists to prove. And there is nothing to stop it with: core owns -coordinator lifetime, and M5's three core changes — concurrent attachment, a -read-only existence query, and `Loopex.Trace`'s excluded-MFA list — none of -them stops a coordinator. +coordinator lifetime, and M5's four core changes — concurrent attachment, a +read-only existence query, `Loopex.Trace`'s excluded-MFA list and the bounded +`quiesce/2` — none of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation @@ -344,26 +344,34 @@ offline `loopex sessions`, `run` and `resume` are unchanged, and each live form is a separate explicit `--daemon` form of them. A daemon ends in one of two ways and the plan keeps them apart, because the -code does. **A daemon-initiated stop** is a short sequence, and it is short -deliberately: refuse new connections and new admissions; attempt **one** -best-effort stop record per open connection and close it; unlink the socket -while the marker is still held; end admitted work by stopping the runtime -within the composed cleanup grace, which is crash-equivalent by construction -and therefore **claims no terminal outcome** for that work, leaving -`commit_unknown` fenced for the reconciliation that already exists; stop the -remaining edges; and stop the Store last, which is when its `terminate/2` -releases the marker. - -**There is no drain, and no settlement, and the plan says so where it used to -promise both.** An earlier revision described admitted work draining within -the grace and the rest settling through cancellation bounds. Neither has a -mechanism: coordinators are temporary children with no drain callback, the -daemon runs no cancellation of its own — cancellation is a session's own -durable command, and a daemon-side path for it would be the second loop this -milestone forbids — and nothing in the sequence waits for work to finish. -What the grace bounds is the teardown, not the work. What survives is what the -journal already proves, and the ambiguous transaction resolves to exactly one -outcome at the next activation. +code does. **A daemon-initiated stop** is a drain and then a teardown: refuse +new connections and new admissions; **quiesce the runtime within the composed +cleanup grace**; attempt one best-effort stop record per open connection and +close it; unlink the socket while the marker is still held; stop the lease +owners and then the runtime, which ends crash-equivalently whatever the drain +did not settle; stop the remaining edges; and stop the Store last, which is +when its `terminate/2` releases the marker. + +**The drain has a mechanism, and it is core's.** M5 adds `quiesce/2` to +`Loopex.Runtime`: every active coordinator refuses new commands, what is in +flight is driven through the cancellation sequence a coordinator already runs +for an abort — under the bounds core already derives from the session's +committed cleanup grace — and the call returns when every coordinator has +settled or the deadline passes, naming which sessions did and which did not. +It belongs in core because core owns coordinator lifetime and cancellation; a +daemon-side drain would have to reach into coordinator internals, which the +dependency direction forbids, or run a cancellation loop of its own, which is +the second loop this milestone forbids. + +**Both halves of the outcome are stated.** Work that settles within the grace +has its ordinary terminal facts in the journal, `cancelled` among them where a +cancellation truly produced one. Work that does not settle is left claiming no +terminal outcome at all, its ambiguous mutation fenced as `commit_unknown` and +resolved to exactly one outcome at the next activation. A revision of this +plan withdrew the drain entirely for want of a mechanism; the maintainer +rejected that smaller design on 2026-09-20, and it is recorded here as the +option not taken — smaller, and a daemon that could tell an operator nothing +about whether its work had finished. **A client learns by the record or by the close.** The stop record is one bounded write attempt into a buffer that may be full, on a transport that may @@ -423,8 +431,9 @@ Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan No controller lease, transport, socket or collaboration rule inside core. Its only M5 changes are independent concurrent attachment support, one read-only -session-existence query, and the excluded-MFA list in `Loopex.Trace` that -accepted ADR 0030 already requires — none of which is a durable command. No daemon-grade +session-existence query, the excluded-MFA list in `Loopex.Trace` that accepted +ADR 0030 already requires, and the bounded `quiesce/2` an orderly stop drains +through — none of which is a durable command. No daemon-grade store adapter, journal format version, migration, backup tooling, compaction, retention cutoff or NIF dependency; no daemon-served generation 1; no durable lease record; no exactly-once delivery promise beyond the founding From 8c8a4cdab453c3e918d50f0d0385424aecf139a0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 00:04:07 -0700 Subject: [PATCH 070/585] plan(M5): correct the executor trap claim and five material items (4) The local executor does **not** trap exits and defines no `terminate/2`: `init/1` sets no flag, and the only `Process.flag(:trap_exit, true)` in that module is at executor.ex:2603, inside `lease_guarded_work/6`, which runs in a per-job guardian process. Two claims rested on the mistake and are re-derived. Stopping the executor is fast rather than slow -- it is the step that *starts* the cleanup, not the one that spends the grace -- so all four bounds in step 6 are ceilings. And the operating-system residual is not confined to a killed executor: the cleanup runs in per-job monitored workers that own the Ports (executor.ex:3703-3724), which the daemon does not hold and cannot wait for, so the halt can cut them short on the ordinary path too. The plan states that rather than adding a wait it has no handle for, and the store-loss witness no longer asserts that no OS child is left behind. (1) `loopex run --daemon` takes no `--policy`: policy is the host's, named when the daemon starts, and the flag is refused as unrecognised. (2) "Explicit release on every exit path" becomes an attempted release while the transport is still writable -- a killed client sends nothing -- and the reconnecting controller is defined: retry acquisition with backoff until its own lease can have expired, then hold a fresh lease with a fresh epoch, or exit `control_held` where another client took over meanwhile. (5) "Dormant sessions cost nothing" becomes what they do cost: an index row under the 4,096-entry cap, a journal and a directory entry, no process, no attachment, no window, and none of the 64 activations until a client reaches for one. (6) ADR 0034's "four atoms" becomes the seven-class breakdown -- six produced below the guardian and the guardian's own `:timeout`. --- ...andoff-over-bootstrap-channel-technical.md | 7 +- docs/plans/M5-technical.md | 152 ++++++++++++------ docs/plans/M5.md | 8 +- 3 files changed, 114 insertions(+), 53 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 49fa531e8..4a3c2ce57 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -409,8 +409,11 @@ an accepted port, which this decision explicitly does not make. set, never a bare `:error`. The guardian has to distinguish a custody process that refused from one that never answered — they are different operational faults and ADR 0029's bounded status has to say which happened — and it can, -because a refusal arrives as one of the four atoms while a silence is the -guardian's own `:timeout`. The reported reason is never the resolved value, +because a refusal arrives as one of the six atoms produced below the guardian +— `:no_token` and `:invalid_token` from the adapter, `:missing` and +`:expired` from a custody process, `:oversized` from the sender, and +`:unavailable` from the registry or custody — while a silence is the +guardian's own `:timeout`, the seventh. The reported reason is never the resolved value, the token, or a host-authored string. **Failures.** Each is a refusal with a bounded non-secret reason, and each diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 52da577cb..83b763e8a 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -134,7 +134,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease releasing it explicitly on every exit path; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller acquiring again and receiving a fresh epoch before any mutation. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in three tiers, against `Loopex.Trace` including the excluded-MFA list M5 adds to it: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec`, the tracer is asserted to receive **no raw trace message at all** for any excluded identity — read from the tracer process, which is where a pre-delivery claim is decidable — while a non-excluded function of the same module is asserted to produce one, so the case cannot pass by tracing nothing; and the keyed-shape tier, defence in depth if an exclusion were ever lost, calls each of the three bridge functions with a **one-byte** credential and asserts no captured entry contains that byte. The shape tier matters because size alone does not protect: running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim, and only a credential-keyed value placeholdered at every size. A fourth case asserts the three identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a module pattern installed and one `{module, function, arity}` cleared after it, with the tracer receiving the non-excluded call and nothing for the excluded one, at both toolchain pairs The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every @@ -560,8 +560,12 @@ in full, and this list is derived from it rather than summarising it: resumed before anything can be sent to it. The daemon forms of the two released commands are what reach the socket: -- **`loopex run --daemon --policy … ""`** — creates a session - and sends its first prompt. Its sequence is `session.create`, +- **`loopex run --daemon ""`** — creates a session and sends + its first prompt. It takes **no `--policy`**, and an earlier draft that + showed one was wrong on the plan's own rule: policy is the host's, named + when the daemon starts, and a connection that could name it would be a + client replacing host authority. A `--policy` flag on a `--daemon` form is + refused as an unrecognised option for that command. Its sequence is `session.create`, `session.acquire_control`, **`session.attach`**, then the prompt under the granted writer epoch, then stream. Attach comes *before* the prompt because ADR 0033 admits an existing-session mutation only from a connection that @@ -652,13 +656,17 @@ resumes, and only then attaches, by which time the session is active. `loopex attach --take-over` against a dormant session therefore acquires successfully and is refused at attach, holding a lease it no longer wants. That is exactly why the general rule matters: **a CLI that holds a lease -releases it explicitly before exiting**, by sending `session.release_control`, -because ADR 0033 binds early release to that call alone and treats every -transport loss — including a clean client exit — as a wait for expiry. On this -path the client releases, exits non-zero, and names `loopex resume --daemon` -as the remedy. Without that release it would strand the operator: the command -the refusal recommends begins by acquiring the same lease, and would refuse -`control_held` for the rest of the term. +attempts an explicit release while its transport is still writable**, by +sending `session.release_control`, because ADR 0033 binds early release to +that call alone and treats every transport loss — including a clean client +exit — as a wait for expiry. The qualification is not a hedge but the honest +scope of the promise: a client whose socket has already failed, or which is +killed, sends nothing, and there is no exit path on which a dead process can +write a frame. On this path the socket is live, so the client releases, exits +non-zero, and names `loopex resume --daemon` as the remedy. Without that +attempt it would strand the operator: the command the refusal recommends +begins by acquiring the same lease, and would refuse `control_held` for the +rest of the term. **Cursor, reconnection and re-acquisition.** The client remembers the last event cursor it emitted and, on transport loss, reconnects at it, @@ -666,9 +674,21 @@ deduplicating by session ID, event sequence and event ID; delivery is contiguous and at least once, so a duplicate at the seam is expected and a gap is a defect. A reconnecting **controller** does not resume its old authority: the lease it held is expiring or expired, and it must acquire again and -receive a **fresh writer epoch** before any further mutation. If the session -went dormant in between — because the daemon restarted — it must resume -first, with a fresh resume command ID under that new epoch. That is the same +receive a **fresh writer epoch** before any further mutation. + +What that looks like in the CLI is written out, because "must acquire again" +leaves the interesting case unsaid. On reconnect the client **retries +`session.acquire_control` with backoff** until its own previous lease can have +expired — the lease term, at most 30 seconds — because until then the daemon +still records the old tenure as the holder and refuses. Once the lease is +gone, one of two things is true and the client says which: it acquires, and +holds a **fresh** lease with a fresh epoch, and continues; or another client +took over in the meantime, and it exits `control_held`, reporting that it no +longer controls the session rather than retrying indefinitely against a live +holder. An observer needs none of this and simply reattaches. + +If the session went dormant in between — because the daemon restarted — it +must resume first, with a fresh resume command ID under that new epoch. That is the same acquire → resume → attach → drive sequence ADR 0033 fixes, reached from a different starting point, and the CLI contract and that ADR say it the same way on purpose. @@ -686,7 +706,7 @@ repair, with the reason class on `stderr`. | `loopex run --daemon`, `loopex resume --daemon` and the create-and-drive sequence | `docs/operator/daemon.md`, driving section | | `loopex sessions --daemon`, `--limit`, `--after`, `--status`, `index_full` | `docs/operator/daemon.md`, listing section | | `loopex daemon` composition inputs, readiness record, signals, exit classes | `docs/operator/daemon.md`, running section | -| `loopex attach` roles, one-shot control, `--after`, renewal loss, `session_dormant` at attach, explicit release on every exit path, reconnect and re-acquisition | `docs/operator/daemon.md`, attaching section | +| `loopex attach` roles, one-shot control, `--after`, renewal loss, `session_dormant` at attach, the attempted release while the transport is writable, reconnect and re-acquisition with its backoff and its `control_held` ending | `docs/operator/daemon.md`, attaching section | ### Daemon Lifecycle and Orderly Shutdown @@ -988,12 +1008,38 @@ all. Both sequences below rely on it, and the idle-shutdown witness asserts the consequence directly: **no fatal class is recorded during an orderly stop**. -Two of them trap exits, and the plan states that as contract rather than -relying on it as luck: the **Store adapter** traps, so an owner that crashes -still runs its `terminate/2` and returns the marker; the **local executor** -traps, so an owner exit lets it complete its own cleanup rather than leaving -OS effects behind. Neither is a property M5 adds; both are properties M5 -depends on, and a change to either is a change to this plan. +**One of them traps exits, and it is not the one an earlier draft named.** +The **Store adapter** traps (`local.ex:150`), so an owner that crashes rather +than stopping still runs its `terminate/2` and returns the marker; that is a +property M5 depends on and a change to it is a change to this plan. + +The **local executor does not trap**, and the correction matters because two +claims rested on the mistake. Its `init/1` sets no `trap_exit` +(`executor.ex:858-…`; the only `Process.flag(:trap_exit, true)` in that module +is at `:2603`, inside `lease_guarded_work/6`, which runs in a **guardian +process** spawned per bounded job), and the module defines **no +`terminate/2`** at all. Two consequences, re-derived: + +- **Stopping the executor is fast, not slow.** With no trap and no + `terminate/2`, `GenServer.stop(executor, :normal, grace)` returns about as + quickly as the mailbox allows. It is not the step that spends the grace; it + is the step that *starts* the cleanup. +- **The cleanup happens elsewhere, in processes the daemon does not hold.** + A per-job monitored worker owns the Port, watches the executor, and performs + the bounded group termination when that authority disappears + (`executor.ex:3703-3724`). Those workers are not linked to the daemon's + owner, so the owner cannot wait for them, and the halt that follows ends + them. + +So the residual stated at the executor's step is not confined to a *killed* +executor: **an orderly stop has it too**, because the daemon halts without any +guarantee that the workers finished. The plan does not add a wait for them — +it holds no handle on them, and inventing one would mean an executor API M5 +does not have and does not propose. What bounds the exposure is that the +workers begin immediately, that the steps after the executor's stop take real +time, and that nothing durable is at stake: an unreaped process group is an +operator-visible fact, while the journal records `commit_unknown` and +reconciles at the next activation. The rejected option is recorded with its reasons, because it was tried in an earlier draft of this pair and looked plausible: **a `Supervisor` with @@ -1207,9 +1253,9 @@ owner chooses. 6. **The remaining composed edges stop, then the Store last.** Reverse start order puts the executor, the workspace lease and the transfers owner between the runtime and the Store, and each is stopped in turn — the - executor first, since it is the one with OS effects to clean up and it - traps exits to do so. Then custody and the registry, which hold nothing - durable. Then the Store, whose `terminate/2` releases the writer marker — + executor first, since stopping it is what sets its Port-owning workers + terminating the captured process groups. Then custody and the registry, + which hold nothing durable. Then the Store, whose `terminate/2` releases the writer marker — see the marker invariant in ADR 0031. The socket path is already gone, unlinked in step 3, so the last act is the halt: **`0`**, or the class, in the case above where something failed on the way out. @@ -1230,7 +1276,7 @@ owner chooses. | Process | Bound | What it is waiting for | | --- | --- | --- | - | The executor | The **composed cleanup grace** | Its own cleanup of operating-system effects — the one stop here that can actually use the time, given the value the sessions were composed with, for the purpose that value names | + | The executor | The **composed cleanup grace** | Nothing, in the executor itself: it neither traps exits nor defines `terminate/2`, so this stop returns quickly and the bound is a ceiling. What takes the time is the Port-owning workers it sets going, which the owner does not hold and cannot wait for | | The workspace lease | The same grace | Nothing: it has no `terminate/2` and holds no file — the lease *is* the live process, so stopping it revokes it. The bound is a ceiling it will not reach | | The transfers owner | The same grace | Closing the open transfer descriptors its `terminate/2` holds (`transfers.ex:146-149`) | | The Store | The same grace | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | @@ -1238,9 +1284,12 @@ owner chooses. No new number enters: every bound here is the composed cleanup grace, which is what step 5 uses and what the sessions carry. Splitting it into fractions would mean inventing ratios, and the minimalism budget takes - every number from an accepted or proposed decision. Three of the four are - ceilings rather than expected waits; only the executor is expected to spend - real time here. **The transfers owner exists only when artifact transfers + every number from an accepted or proposed decision. **All four are + ceilings rather than expected waits**, which is the corrected reading: an + earlier revision expected the executor to spend real time here, on the + mistaken belief that it traps exits and cleans up in its own process. Only + the transfers owner and the Store run a `terminate/2` at all, and both are + short. **The transfers owner exists only when artifact transfers were enabled**, as the composed set above says (`transfers` is listed there as absent when disabled); where it is absent its row is not a stop the owner skips at runtime so much as a pid it never held, and the step for it @@ -1252,21 +1301,24 @@ owner chooses. `after`, for the reason the general rule gives — it waits for a signal that already exists. - **A killed executor is the residual, and the plan states it rather than - explaining it away.** The kill by itself is not the leak. The executor - `GenServer` does not own the Port: a monitored worker owns it, watches the - executor, and *performs the same bounded group termination if that - authority disappears* (`executor.ex:3703-3724`, and `effect_owner/0` at - `executor.ex:4166-4173`) — the executor's own contract for exactly this - case, written after a kill once left a descendant running. - - But that worker is a process **in this VM**, and the halt a few steps later - ends it too. Whatever bounded termination it has not finished when the VM - goes does not finish. So the residual of an unresponsive executor is - honest and stated: **operating-system children may survive the daemon**, as - an orphaned process group an operator can see and reap. The plan does not - add a wait for that worker — an unbounded wait at the end of a sequence - whose purpose is to be bounded is the thing being avoided. + **The operating-system residual, stated for the ordinary path and not only + for a killed executor.** Whether the executor stops cleanly or is killed, + the cleanup of captured process groups happens in the per-job monitored + workers that own the Ports and watch the executor + (`executor.ex:3703-3724`, `effect_owner/0` at `:4166-4173`) — the + executor's own contract, written after a kill once left a descendant + running. + + Those workers are processes **in this VM**, and the halt at the end of this + sequence ends them. Whatever bounded termination they have not finished by + then does not finish. So the residual is the same on both paths: + **operating-system children may survive the daemon**, as an orphaned + process group an operator can see and reap. The plan does not add a wait — + the owner holds no handle on those workers, and acquiring one would mean an + executor API M5 does not have and does not propose, while an unbounded wait + at the end of a bounded sequence is the thing being avoided. What limits + the exposure in practice is that the workers start at once and the steps + after this one take real time. What is *not* at risk is durable truth. The effect that was in flight is `commit_unknown` in the journal and resolves to exactly one outcome at the @@ -1415,9 +1467,10 @@ to write. stop: a monitored helper calling `GenServer.stop(pid, :normal, grace)`, the owner waiting on its own link with `after grace` and killing on expiry, and the composed cleanup grace the ordered path's step 6 uses. This is not tidiness: the executor is - the one linked process that owns effects outside the VM, and it traps exits - precisely so it can clean them up. Halting without stopping it would end - that cleanup where it stood. The residual is the one stated there and is + the one linked process whose work reaches outside the VM, and stopping it + is what tells its Port-owning workers to terminate the captured process + groups. Halting without stopping it would never start that cleanup at + all. The residual is the one stated there and is the same here: if the stop times out and the executor is killed, the halt that follows also ends the Port-owning worker that would have terminated the captured process group, so operating-system children may survive the @@ -1654,9 +1707,10 @@ the cause and try again without a recovery step. `terminate/2` before the daemon could act. A second daemon starts on that root immediately with no stale marker to recover. The capacity variant reports `store_capacity_exceeded` instead, and the case asserts the executor - was stopped — and that the stop *returned* rather than timing out into a - kill — before the halt, so its cleanup ran and no operating-system child is - left behind. + was stopped before the halt, and that its stop *returned* rather than timing + out into a kill. It does **not** assert that no operating-system child is + left behind: that is the residual this plan states, since the cleanup runs + in workers the daemon cannot wait for. - **One class per linked component of the fixed set.** Each is killed in turn, in its own case, and the daemon is asserted to exit with that component's class, to send that component's `fatal:` on the wire @@ -1761,7 +1815,7 @@ plan names as new. It is the thing to check a change against. | **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies, taking that session's in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller attachment closes with `control_owner_lost`; observers stay attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | -| **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; custody answers one of the four atoms; the **guardian** enforces the deadline and kills the sender | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | +| **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | | **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT`, delivered to the handler the daemon installs before it takes the marker | The owner stops its linked processes in reverse order itself, each stop driven by a monitored helper calling `GenServer.stop(pid, :normal, grace)` while the owner waits on its own link with `after grace` and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index b97d2261b..b06e755bb 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -243,8 +243,12 @@ tooling enters M5. A daemon activates a session when a client creates or resumes it, not at startup — those are the two operations that start a coordinator, and acquiring control or attaching is neither. Sessions the root records are dormant until then, and the daemon holds at most -a bounded number of active ones at a time; the rest stay dormant and cost -nothing. One root is one host composition, so a recorded session the daemon's +a bounded number of active ones at a time. A dormant session costs what a +recorded session costs and no more: a row in the daemon's bounded index, +itself capped at 4,096 entries, plus its journal and directory entry on disk. +It runs no process, holds no attachment, no lease owner, no window and no +buffer, and it spends none of the 64 activations until a client reaches for +it — which is the sense in which it is cheap, rather than free. One root is one host composition, so a recorded session the daemon's current composition cannot serve is reported at activation, by session, rather than failing a startup that never reads it. From d21f3fa4c4507395b9014128c8df4384eb392c4f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 00:06:49 -0700 Subject: [PATCH 071/585] plan(M5): add the process inventory and what my pass found The adversarial pass this round had four added checks. What they produced: (a) A process inventory table, reconciled across ADRs 0031-0034 and both plan files: every process any document names, who starts it, who holds its link, who stops it, what its death means. It has nineteen rows -- eight fixed daemon-linked processes, the dynamic per-session lease owners with their 64-activation bound, connections, stop helpers, five core-internal kinds, and the adapter's and executor's per-invocation and per-job processes, including the Port workers the daemon cannot wait for at a halt. (b) Accepted ADRs the set cites, checked for a sentence it contradicts. ADR 0019's 1-to-65,536-byte credential range and ADR 0023's framing hold as cited; the 4 MiB output buffer is ADR 0032's, correctly attributed. ADR 0024 produced a real omission, now fixed: an answer to a durable interaction is a session command, and step 1 has already refused admissions, so a session waiting on one cannot settle during the drain. It is reported unsettled and its interaction stays durable and answerable after a restart -- quiesce never answers, expires or abandons one. (c) Counts re-derived. "Seven classes where the Store is still alive" is seven only where transfers are enabled and six otherwise, so the two statements that leaned on the number now say which. (d) Concept promises paired with mechanisms: the workstream list still said core had two changes and named neither the trace exclusion nor quiesce, and gave no landing order for them. It now carries four, each with the workstream it lands beside and why. --- docs/plans/M5-technical.md | 41 +++++++++++++++++++++++++++++++++++--- docs/plans/M5.md | 22 ++++++++++++-------- 2 files changed, 52 insertions(+), 11 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 83b763e8a..902141a5e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1392,6 +1392,13 @@ reported **unsettled**, and the teardown ends it crash-equivalently: the deadline is the daemon's, not the executor's, and quiesce does not extend one to satisfy the other. +**A session waiting on an interaction cannot settle, and that is correct.** +An answer to a durable interaction is a session command under ADR 0024, and +step 1 has already refused admissions, so no answer can arrive during the +drain. Such a session is reported **unsettled**, its interaction stays durable +and unanswered, and the next daemon can answer it — which is exactly what a +durable interaction is for. Quiesce does not answer, expire or abandon one. + So the outcome has two halves and both are said: **work that settled within the grace has its ordinary terminal facts in the journal** — including `cancelled` where a cancellation produced one, which is a true statement about @@ -1536,7 +1543,7 @@ performs itself, then a halt that cannot hang. Store's marker release does not happen at the halt. On the ordered path that is fine — the Store was already stopped in step 6, and its `terminate/2` ran then. On the **fatal** path it was not fine, and an earlier draft left a real -hole: for the seven classes where the Store is still alive (`runtime_lost`, +hole: for the classes where the Store is still alive (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`), nothing stopped the Store, so the halt left the marker file behind on a daemon that had shut down deliberately. The @@ -1714,9 +1721,10 @@ the cause and try again without a recovery step. - **One class per linked component of the fixed set.** Each is killed in turn, in its own case, and the daemon is asserted to exit with that component's class, to send that component's `fatal:` on the wire - where a socket still exists, and — for the seven classes where the Store is + where a socket still exists, and — for the classes where the Store is still alive — **to leave no stale marker**, proved by the next daemon - opening that root with nothing to recover — `runtime_lost`, `transfers_lost`, + opening that root with nothing to recover; seven of them in a daemon with + transfers enabled and six without — `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`, beside the two store classes. The set is closed for the fixed set, so one of those dying without a class is a failing case rather @@ -1804,6 +1812,33 @@ do. This table is the answer to both: one row per boundary M5 touches, and every cell resting on a code line that exists today or on a component this plan names as new. It is the thing to check a change against. +**First, the process inventory**, because more than one review found two +documents counting the same processes differently. Every process any document +in this set names appears here once, with who starts it, who holds its link, +who stops it and what its death means. + +| Process | Started by | Linked to | Stopped by | Its death | +| --- | --- | --- | --- | --- | +| **Daemon owner** | The `loopex daemon` escript | — | Itself; it halts the VM | There is nothing above it; the signal handler's backstop halts with `owner_lost` if a signal finds it gone | +| Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | +| Credential **custody process** (ADR 0034) | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal | +| **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last of all** | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal — both fail-stop | +| **Artifact transfers owner** | The composition function | Daemon owner | Orderly step 6 | `transfers_lost`, daemon-fatal. **Absent** where transfers are disabled | +| **Workspace lease** | The composition function | Daemon owner | Orderly step 6 | `workspace_lease_lost`, daemon-fatal | +| **Local executor** | The composition function | Daemon owner | Orderly step 6, before the lease | `executor_lost`, daemon-fatal | +| **Runtime root** (a supervisor) | The composition function | Daemon owner | Orderly step 5 | `runtime_lost`, daemon-fatal | +| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Orderly step 1 stops it accepting; step 3 closes and unlinks | `listener_lost`, daemon-fatal, and the one fatal class no client can be told | +| **Lease owner, one per activated session** (ADR 0033) | Daemon owner, on activation | Daemon owner | Orderly step 4, in sequence | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the next acquisition starts a fresh owner with a fresh epoch. Population bounded by the 64-activation ceiling | +| **Connection**, one per accepted client | The listener | The listener | Orderly step 3, or the client | That client's connection closes. Nothing else | +| **Stop helper**, one per stop | Daemon owner, `spawn_monitor` | Monitored, never linked | Its own call returning or raising | Nothing: it is monitored so that whatever `GenServer.stop/3` does to it cannot reach the owner | +| **Session coordinator** | Core, under a `DynamicSupervisor` (`restart: :temporary`) | Core | Core, when the runtime stops | Core's own refusal on the next command for that session; **no signal reaches the daemon and none is owed** | +| **Owner group and workers** | Core, beneath a coordinator | Core | Core | Core's; a trapping owner group unwinds on its own clock and the daemon does not wait for it | +| **Attachment dispatcher** | Core, per attachment | Core | Core | That attachment's, and core's existing detachment rules | +| **Trace tracer** | Core, per trace session | Core | Core | The trace session's; it carries no daemon meaning | +| **Provider sender and guardian** (ADR 0034) | The adapter, per invocation, inside the calling process | Neither is linked to the daemon owner | The guardian kills the sender at the deadline; both end with the invocation | That invocation's refusal, as one of the seven atoms. No daemon class | +| **Provider child**, its Port and OS process (ADR 0019) | The adapter's launcher, per invocation | The Port's owner | The invocation | That invocation's refusal | +| **Per-job Port worker, carrier and guard** (ADR 0022) | The local executor, per job | The worker is monitored by the executor; the carrier and guard are OS processes | The worker terminates the captured group when the executor goes | The job's outcome, reconciled through `commit_unknown`. **These are the processes the daemon cannot wait for at a halt** | + | Boundary | Owner | What fails | Who observes it, and how | What the client sees | Durable / not durable | | --- | --- | --- | --- | --- | --- | | **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the **daemon owner process** holds the Store's link and pid | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:166`). The owner's `{:EXIT, store_pid, reason}` clause receives it **with the store's real reason**, which is what distinguishes `store_capacity_exceeded` from `store_lost` | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index b06e755bb..63ffd4ac8 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -641,18 +641,23 @@ Technical depth: [Packaging mechanics](M5-technical.md#technical-plan-packaging) Six workstreams, listed in the order the technical companion's rejoin order puts them in, which is the order of what each needs to exist before it can be -proved. Core concurrent attachment comes first, because the daemon's attach -path cannot be proved without it; the fifth is independent of all of them; the +proved. Core's changes come first, because the daemon's attach +path cannot be proved without them; the fifth is independent of all of them; the sixth runs last because it describes what the others built. Workstream 1 lands in two parts — the core change first, its daemon-side residency after the lease — and the companion's rejoin order says where each part goes. -1. **Core's two changes, and the residency above them.** The narrow core +1. **Core's four changes, and the residency above them.** The narrow core change that lets distinct attachments to one session coexist without - implicit replacement, and the read-only session-existence query the - daemon's acquire and activation paths need — both land first, because - nothing about the daemon can be proved without them — and then, once the lease - exists, the daemon-side residency over it: the resident window as a + implicit replacement; the read-only session-existence query the daemon's + acquire and activation paths need; the excluded-MFA list in `Loopex.Trace` + that accepted ADR 0030 already requires, which lands with workstream 5's + credential work because that is what it protects; and the bounded + `quiesce/2` the orderly stop drains through, which lands before workstream + 2's shutdown sequence because that sequence cannot be proved without it. + The first two land first, because nothing about the daemon can be proved + without them — and then, once the lease exists, the daemon-side residency + over it: the resident window as a droppable cache, per-connection output buffers, detachment at the last emitted cursor, idle eviction, dormancy and the aggregate byte ceiling with its deterministic reclamation. @@ -680,7 +685,8 @@ lease — and the companion's rejoin order says where each part goes. refusal, and the differential conformance that the facade, the foreground server and the socket produce the same durable identities. 4. **The collaboration lease.** The in-memory lease record, the per-session - owner that serializes lease transitions with admission handoff, the + owner that serializes lease transitions with admission handoff and whose + own failure is scoped to its session, the combined holder, epoch, state and term check, explicit takeover with a fresh epoch and the expiry linearization, fencing after a real kill, and cross-process abort through the core's existing durable command. From bb391335fadc93c5a15138684c8e2782cbbd56e5 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 00:07:20 -0700 Subject: [PATCH 072/585] plan(M5): finish the sweep for the reversed decisions --- docs/plans/M5-technical.md | 2 +- docs/plans/M5.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 902141a5e..4ba974265 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1852,7 +1852,7 @@ who stops it and what its death means. | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT`, delivered to the handler the daemon installs before it takes the marker | The owner stops its linked processes in reverse order itself, each stop driven by a monitored helper calling `GenServer.stop(pid, :normal, grace)` while the owner waits on its own link with `after grace` and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT`, delivered to the handler the daemon installs before it takes the marker | The owner drains through core's `quiesce/2` within the composed cleanup grace, tells clients, unlinks the socket while it still holds the marker, and then stops its linked processes in reverse order — lease owners, runtime, edges, Store last — each stop driven by a monitored helper calling `GenServer.stop(pid, :normal, grace)` while the owner waits on its own link with `after grace` and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 63ffd4ac8..a4020778c 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -294,7 +294,7 @@ store, policy and executor spans an embedded caller emits, with the same bounded identity metadata. That, and nothing more, is M5's observability claim. -Daemon-internal functions — the listener, the connection, the lease owner, the +Daemon-internal functions — the listener, the connection, the lease owners, the residency stages — are proved by the daemon's own tests and its own logs, not by a trace session. An earlier draft said a daemon-scoped trace session would observe them, which ADR 0030 does not permit: a `Loopex.Trace` session traces From 790f8e2aec0cce23a9a40a5986d7e6cf9ea395fc Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 00:19:51 -0700 Subject: [PATCH 073/585] plan(M5): give the Store's stop a floor, restate core's four changes H2: `--cleanup-grace-ms` had no admitted domain, and at a small value the owner's `after grace` fires before the Store can release the marker; the kill that follows runs no `terminate/2`, so a deliberate operator stop would leak the marker -- contradicting the plan's own claim in three places. Two fixes, both from numbers that already exist. The domain is an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, matching core's `cancellation_bounds/1` (apps/loopex/lib/loopex/executor.ex:456), which the local executor's own `>= 0` validation would otherwise have admitted. And the Store's wait alone gets a floor of `max(grace, 30_000)` -- the Store's own `@call_timeout` (apps/loopex_store_local/lib/loopex/store/local.ex:65), the bound it already puts on its synced call path, which is the same class of work as the release's `File.read`, `File.rm` and parent sync (writer_lock.ex:105-115). It is a ceiling, not a wait: a healthy Store releases in milliseconds, and it bites only when the filesystem is wedged, which is when killing mid-release is worst. No other component gets a floor, because no other releases a durable exclusion. The residual is stated, and the 1 ms witness now asserts the marker: the next daemon opens that root with nothing to recover. A second case proves `0` refuses at startup with no marker held. H1: the Concept still said core gains exactly two. It gains four -- concurrent attachment, the existence query, the excluded-MFA trace list and `quiesce/2` -- restated at M5.md:41, with :70 "second of four" and :128 and ADR 0032's ordinal both becoming "a further core change". M1: "every one of the nine" is the fixed eight, seven without transfers, with the lease owners dynamic beside them. M2: five places still had the daemon handling `SIGINT`. It cannot: `:os.set_signal/2` refuses the name. Each now says `SIGTERM`, or `SIGINT` through the launcher that forwards it as `SIGTERM`. L1: `executor.ex` citations are prefixed with their application, core's `apps/loopex/lib/loopex/executor.ex` distinguished from the local adapter's. L2: the inventory's custody row says one per configured provider token. --- ...tachment-residency-and-replay-technical.md | 4 +- docs/plans/M5-technical.md | 121 +++++++++++++----- docs/plans/M5.md | 22 ++-- 3 files changed, 102 insertions(+), 45 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 8d7666ff6..644f811b5 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -269,8 +269,8 @@ daemon activated the session, which remains true. The activation ceiling still counts activations per daemon lifetime, for the same reason — it counts what the daemon did. -Two alternatives were rejected, and both are **third core changes** this -milestone does not make. A lifecycle notification from core to the daemon +Two alternatives were rejected, and both would be **a further core change** +beyond the four this milestone makes. A lifecycle notification from core to the daemon would be a new core-to-host signal, with its own delivery and ordering questions, added for a listing field. A monitorable coordinator handle handed out to the daemon would export core's supervision topology across the boundary diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 4ba974265..381dfb967 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,7 +130,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` and on `SIGINT`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` driving every active coordinator to settle within the composed cleanup grace and naming the sessions that did and did not — **both halves asserted**: a dispatched tool effect that settles inside the grace carries its ordinary terminal fact in the journal, and one held past the deadline is ended crash-equivalently with **no terminal claimed for it** — no `cancelled`, no `outcome_unknown`, no abort record — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` driving every active coordinator to settle within the composed cleanup grace and naming the sessions that did and did not — **both halves asserted**: a dispatched tool effect that settles inside the grace carries its ordinary terminal fact in the journal, and one held past the deadline is ended crash-equivalently with **no terminal claimed for it** — no `cancelled`, no `outcome_unknown`, no abort record — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -485,9 +485,9 @@ and its refusal class: | Provider launch | `--provider-launch` / `LOOPEX_PROVIDER_LAUNCH` | none | `provider_launch_required`, `provider_launch_invalid` | | Policy | `--policy` / `LOOPEX_POLICY` | **none, deliberately** — authority is the operator's to name, as the app-server host already insists | `policy_required`, `policy_unknown` | | Provider credential | `LOOPEX_PROVIDER_API_KEY` | none | `provider_credential_required`, checked at start so an unattended launch refuses in a second rather than at the first dispatch. The daemon reads it once, deletes it from its environment and holds it in custody under ADR 0034 | -| Cleanup grace | `--cleanup-grace-ms` | the composition default | `cleanup_grace_invalid` | +| Cleanup grace | `--cleanup-grace-ms` | the composition default | `cleanup_grace_invalid`, and the admitted domain is **an integer of 1 or more**. Zero is refused, which the local executor's own validation would admit (`apps/loopex_executor_local/lib/executor.ex:897`, `>= 0`) but core's `cancellation_bounds/1` refuses (`apps/loopex/lib/loopex/executor.ex:456`, `grace_ms >= 1`): a daemon composed with zero would carry a grace core cannot derive bounds from | | Project resources | as the host already takes them | as today | as today | -| Socket path | `--socket` | `/daemon/daemon.sock` | `socket_path_too_long`, `socket_permission_unverified` | +| Socket path | `--socket` | `/daemon/daemon.sock` | `socket_path_too_long`, `socket_permission_unverified`, `invalid_socket_path` for a path outside the root's `daemon/` directory | Every one of these is refused **before** the marker is acquired where that is possible, so the common operator mistake costs nothing and leaves nothing @@ -528,7 +528,11 @@ a client to connect to a socket the daemon has not finished checking. Every diagnostic, warning and failure goes to `stderr`, so `stdout` carries the readiness line alone and stays machine-readable. -**Stopping.** `SIGTERM` and `SIGINT` both begin the orderly shutdown below. +**Stopping.** **`SIGTERM`** begins the orderly shutdown below — or `SIGINT` +through the launcher, `apps/loopex_cli/bin/loopex`, which forwards it as +`SIGTERM`. The daemon itself installs no `SIGINT` handler and cannot: the +emulator reserves that signal and `:os.set_signal/2` refuses the name, as the +signal section below sets out. There is no `daemon.stop` method on the wire: stopping is an operator act against the process, and a client-issued stop would let one connection end every other client's session residency, which is authority the socket does not @@ -862,7 +866,8 @@ runs no dialyzer, and `RuntimeOwner` itself already destructures the field, at not, and the real argument is the simpler one above. **There is no restart strategy, because there are no restarts.** Every one of -the nine is `start_link`ed by the owner, and the owner's +the fixed eight — seven without transfers — is `start_link`ed by the owner, +as is each lease owner beside them, and the owner's `handle_info({:EXIT, pid, reason}, state)` clause is the failure rule. That clause is also the **reader** the fatal-class map needs — it matches the pid against the set it holds, maps it to a component, classifies `reason`, and @@ -900,7 +905,7 @@ admits the call does not raise an *exit* at all. **The probe.** A trapping `GenServer` whose `terminate/2` takes longer than the grace, stopped with the grace the executor admits at its lower end — the local executor validates it as `is_integer(cleanup_grace_ms) and -cleanup_grace_ms >= 0` (`executor.ex:897`), so `1` is a composable value, not +cleanup_grace_ms >= 0` (`apps/loopex_executor_local/lib/executor.ex:897`), so `1` is a composable value, not a contrived one — run at both toolchain pairs: | grace | `terminate/2` | what `GenServer.stop/3` did | `Process.alive?` right after | the link exit the owner then got | @@ -1015,7 +1020,7 @@ property M5 depends on and a change to it is a change to this plan. The **local executor does not trap**, and the correction matters because two claims rested on the mistake. Its `init/1` sets no `trap_exit` -(`executor.ex:858-…`; the only `Process.flag(:trap_exit, true)` in that module +(`apps/loopex_executor_local/lib/executor.ex:858-…`; the only `Process.flag(:trap_exit, true)` in that module is at `:2603`, inside `lease_guarded_work/6`, which runs in a **guardian process** spawned per bounded job), and the module defines **no `terminate/2`** at all. Two consequences, re-derived: @@ -1027,7 +1032,7 @@ process** spawned per bounded job), and the module defines **no - **The cleanup happens elsewhere, in processes the daemon does not hold.** A per-job monitored worker owns the Port, watches the executor, and performs the bounded group termination when that authority disappears - (`executor.ex:3703-3724`). Those workers are not linked to the daemon's + (`apps/loopex_executor_local/lib/executor.ex:3703-3724`). Those workers are not linked to the daemon's owner, so the owner cannot wait for them, and the halt that follows ends them. @@ -1178,7 +1183,8 @@ in the fatal-class map's note, and it is the one class no linked component produces. **Daemon-initiated shutdown is a drain and then a teardown, in reverse -order.** `SIGTERM` or `SIGINT` reaches the owner, which performs these six +order.** `SIGTERM` reaches the owner — sent directly, or forwarded by the +launcher from a terminal `SIGINT` — and it performs these six steps itself. They are the owner's code, not a supervisor's behaviour, which is what lets each one carry a reason and lets the teardown use a bound the owner chooses. @@ -1271,7 +1277,7 @@ owner chooses. **Each of these four is a helper calling `GenServer.stop(pid, :normal, bound)`, with the owner waiting on its own link** — the same rule as step 5, and all four are `GenServer`s - (`executor.ex:22`, `workspace_lease.ex:15`, `transfers.ex:26`, + (`apps/loopex_executor_local/lib/executor.ex:22`, `workspace_lease.ex:15`, `transfers.ex:26`, `local.ex:55`), so the same call fits all four. The bounds: | Process | Bound | What it is waiting for | @@ -1279,12 +1285,14 @@ owner chooses. | The executor | The **composed cleanup grace** | Nothing, in the executor itself: it neither traps exits nor defines `terminate/2`, so this stop returns quickly and the bound is a ceiling. What takes the time is the Port-owning workers it sets going, which the owner does not hold and cannot wait for | | The workspace lease | The same grace | Nothing: it has no `terminate/2` and holds no file — the lease *is* the live process, so stopping it revokes it. The bound is a ceiling it will not reach | | The transfers owner | The same grace | Closing the open transfer descriptors its `terminate/2` holds (`transfers.ex:146-149`) | - | The Store | The same grace | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | - - No new number enters: every bound here is the composed cleanup grace, - which is what step 5 uses and what the sessions carry. Splitting it into - fractions would mean inventing ratios, and the minimalism budget takes - every number from an accepted or proposed decision. **All four are + | The Store | `max(grace, 30_000)` — the one exception, below | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | + + No number is invented here: three of the four bounds are the composed + cleanup grace, which is what step 5 uses and what the sessions carry, and + the Store's floor is the Store's own existing call bound. Splitting the + grace into fractions would mean inventing ratios, and the minimalism budget + takes every number from an accepted or proposed decision or from the code + it already governs. **All four are ceilings rather than expected waits**, which is the corrected reading: an earlier revision expected the executor to spend real time here, on the mistaken belief that it traps exits and cleans up in its own process. Only @@ -1301,11 +1309,41 @@ owner chooses. `after`, for the reason the general rule gives — it waits for a signal that already exists. + **The Store's wait has a floor, and the reason is a defect this plan would + otherwise have shipped.** The kill after a wait is `Process.exit(pid, + :kill)`, which runs no `terminate/2`. So at a small grace — and `1` is a + composable value — the owner's `after grace` fires before the Store can + finish releasing the marker, and the kill leaves the marker **on a + deliberate operator stop**, which is exactly what this plan promises never + happens. An operator flag would have quietly broken a durability claim. + + The Store's wait is therefore `max(grace, 30_000)`. The number is not + invented: `30_000` is the Store's own `@call_timeout` + (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), the bound it + already puts on its synchronous, synced call path — and releasing the + marker is the same class of work against the same root, `File.read`, + `File.rm` and a parent-directory sync (`writer_lock.ex:105-115`). Using the + Store's own bound for the Store's own file I/O introduces no number and + asks no one to pick one. + + This is a **ceiling, not a wait**: a healthy Store releases in + milliseconds, so an ordinary stop is not lengthened at all. It bites only + when the filesystem is wedged, which is precisely when killing the Store + mid-release is the wrong thing to do. No other component gets a floor, + because no other component's `terminate/2` releases a durable exclusion. + + **The residual is stated.** A Store that has not released within + `max(grace, 30_000)` is killed, and the marker survives. That is the same + stale marker ADR 0031's recovery rule already answers: the next daemon + probes the marker's recorded holder and reclaims it where that holder is + proved dead, refuses `store_writer_unverifiable` where it cannot be + decided, and refuses `store_writer_active` where it is alive. + **The operating-system residual, stated for the ordinary path and not only for a killed executor.** Whether the executor stops cleanly or is killed, the cleanup of captured process groups happens in the per-job monitored workers that own the Ports and watch the executor - (`executor.ex:3703-3724`, `effect_owner/0` at `:4166-4173`) — the + (`apps/loopex_executor_local/lib/executor.ex:3703-3724`, `effect_owner/0` at `:4166-4173`) — the executor's own contract, written after a kill once left a descendant running. @@ -1366,9 +1404,9 @@ It is defined entirely in terms of mechanisms that already exist: admissions at the daemon. - **What is in flight is driven through the cancellation that exists**, not through a new one. That is the sequence a coordinator already runs for an - abort: `Loopex.Executor.cancel/4` under the bounds + abort: `Loopex.Executor.cancel/4` (core) under the bounds `Loopex.Executor.cancellation_bounds/1` derives from the session's committed - cleanup grace (`executor.ex:456-474`), which the coordinator already uses at + cleanup grace (`apps/loopex/lib/loopex/executor.ex:456-474`), which the coordinator already uses at `session_coordinator.ex:3614` and `:5366`. Quiesce adds no bound, no callback and no durable command. - **It returns when every coordinator has settled or the deadline passes**, @@ -1385,7 +1423,7 @@ IDs and two lists — so nothing about a coordinator crosses the boundary. **What it does not promise, stated because the numbers say so.** `cancellation_bounds/1` derives an executor observation bound of -`max(10_000, grace_ms + 2_000)` (`executor.ex:458`). A daemon composed with a +`max(10_000, grace_ms + 2_000)` (`apps/loopex/lib/loopex/executor.ex:458`). A daemon composed with a cleanup grace below about ten seconds will therefore reach its own deadline while an effect's cancellation is still within *its* bound. That effect is reported **unsettled**, and the teardown ends it crash-equivalently: the @@ -1489,7 +1527,9 @@ to write. is nothing to stop. On the other six, the Store is **still alive**, and because `System.halt/1` runs no `terminate/2`, halting past it would leave the marker file behind on a daemon that shut down deliberately. So the - owner stops it here, under the same bounded treatment as every other stop. + owner stops it here, under the same bounded treatment as every other stop + and under the same floor: the Store's wait is `max(grace, 30_000)`, so a + deliberate fail-stop cannot kill it mid-release either. **If that stop times out and the Store is killed, the marker survives.** That is the one residual on this path and the plan states it rather than @@ -1779,18 +1819,27 @@ the cause and try again without a recovery step. owner **survives** rather than dying of whatever the stop did to the helper, that it then kills the runtime supervisor, and that it still reaches the Store stop and the socket unlink — the step a stop called inline would skip. -- **Cleanup grace 1 ms: the owner survives and classifies from the exit.** The - same daemon is composed with `cleanup_grace_ms: 1`, a value the local - executor's own validation admits (`executor.ex:897`), and stopped with a - component whose teardown takes longer than that. This is the case that broke - every inline design: at that grace `GenServer.stop/3` raises - `ErlangError`/`:timeout_value` rather than exiting, so no `catch :exit` - clause would have run. The case asserts the owner survives, that it kills - and reads the exit, that the class follows the **exit reason** and not the - stop's outcome — `operator_stop` and exit `0` where the component still - managed to exit `:normal`, its own class where it did not — and that the - sequence still reaches the Store stop and the socket unlink. It runs at both - toolchain pairs, because the result was observed at both. +- **Cleanup grace 1 ms: the owner survives, classifies from the exit, and + still releases the marker.** The same daemon is composed with + `cleanup_grace_ms: 1` — the smallest admitted value, since `0` is refused + with `cleanup_grace_invalid` — and stopped with a component whose teardown + takes longer than that. This is the case that broke every inline design: at + that grace `GenServer.stop/3` raises `ErlangError`/`:timeout_value` rather + than exiting, so no `catch :exit` clause would have run. The case asserts + the owner survives, that it kills and reads the exit, that the class follows + the **exit reason** and not the stop's outcome — `operator_stop` and exit + `0` where the component still managed to exit `:normal`, its own class where + it did not — and that the sequence still reaches the Store stop and the + socket unlink. + + It also asserts the thing a grace of 1 ms would otherwise have broken: + **the next daemon opens that root with no stale marker to recover.** That is + the Store's floor doing its work — the Store is waited on for + `max(grace, 30_000)`, not for 1 ms — and without it this case would have + left a marker behind on a deliberate operator stop. A second case composes + `cleanup_grace_ms: 0` and asserts the daemon refuses at startup with + `cleanup_grace_invalid`, holding no marker and binding no socket. Both run + at both toolchain pairs, because the timeout result was observed at both. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting @@ -1821,7 +1870,7 @@ who stops it and what its death means. | --- | --- | --- | --- | --- | | **Daemon owner** | The `loopex daemon` escript | — | Itself; it halts the VM | There is nothing above it; the signal handler's backstop halts with `owner_lost` if a signal finds it gone | | Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | -| Credential **custody process** (ADR 0034) | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal | +| Credential **custody process** (ADR 0034), **one per configured provider token** | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal. M5 composes one provider, so one process; a host configuring two carries two, each with its own registry row (`0034-…-technical.md:95-98`) | | **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last of all** | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal — both fail-stop | | **Artifact transfers owner** | The composition function | Daemon owner | Orderly step 6 | `transfers_lost`, daemon-fatal. **Absent** where transfers are disabled | | **Workspace lease** | The composition function | Daemon owner | Orderly step 6 | `workspace_lease_lost`, daemon-fatal | @@ -1852,7 +1901,7 @@ who stops it and what its death means. | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM` / `SIGINT`, delivered to the handler the daemon installs before it takes the marker | The owner drains through core's `quiesce/2` within the composed cleanup grace, tells clients, unlinks the socket while it still holds the marker, and then stops its linked processes in reverse order — lease owners, runtime, edges, Store last — each stop driven by a monitored helper calling `GenServer.stop(pid, :normal, grace)` while the owner waits on its own link with `after grace` and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the composed cleanup grace, tells clients, unlinks the socket while it still holds the marker, and then stops its linked processes in reverse order — lease owners, runtime, edges, Store last — each stop driven by a monitored helper calling `GenServer.stop(pid, :normal, grace)` while the owner waits on its own link with `after grace` and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | @@ -1959,6 +2008,8 @@ decision named above; M5 introduces none of its own. | `session.list` page | at most 256 entries, `limit` in 1 to 256 | ADR 0032 | | Socket path bound, over `/daemon/daemon.sock` | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | +| Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | +| Floor on the Store's stop | `max(grace, 30_000)`, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), so a small grace cannot kill it before `terminate/2` releases the marker | This plan, against the Store's existing bound | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | | Takeover grace beyond expiry | none; takeover is eligible at expiry and granted once the session's in-flight admission set is empty | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index a4020778c..31bf08c96 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -38,17 +38,20 @@ channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above -the core. Core gains exactly two narrow things: support for several -independent attachments to one session, and one read-only query that answers -whether a session ID exists durably in the root. It gains no lease, no -transport, no second loop and no new durable command. +the core. Core gains exactly four narrow things: support for several independent +attachments to one session; one read-only query that answers whether a session +ID exists durably in the root; an excluded-MFA list in `Loopex.Trace`, which +keeps a named function out of a trace session before any message is delivered +and which accepted ADR 0030 already requires; and `quiesce/2`, the bounded +settle an orderly stop drains through. It gains no lease, no transport, no +second loop and no new durable command. ### Outcomes | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` and `SIGINT` begin an orderly shutdown that refuses new work, **drains admitted work within the composed cleanup grace** through core's `quiesce/2` — every active coordinator refusing new commands while what is in flight is driven through the cancellation sequence that already exists, to the bounds it already derives — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within the composed cleanup grace** through core's `quiesce/2` — every active coordinator refusing new commands while what is in flight is driven through the cancellation sequence that already exists, to the bounds it already derives — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -67,7 +70,7 @@ independent attachments to one session through its existing race-free attach barrier and dispatcher, and answers one read-only question about it: given a session ID, does this root hold that session durably. -That query is the second and last of core's M5 changes, and it exists because +That query is the second of core's four M5 changes, and it exists because the alternative was worse. The daemon has to validate durable existence before it grants a lease, and before it records a session its index does not hold, and it may not read Store internals to do it. Learning existence by *calling* @@ -125,7 +128,8 @@ coordinator exists*. A coordinator is core's `restart: :temporary` child and its loss is core's to supervise; it reaches a client as core's existing refusal on the next command for that session, which the daemon forwards unchanged. Making the daemon track it would need a core notification or a -monitorable handle — a third core change M5 does not make. Lifting it needs a core operation that can tell quiescent from idle, +monitorable handle — a **further** core change M5 does not make, beyond the +four it does. Lifting it needs a core operation that can tell quiescent from idle, which is its own decision and not M5's. `session.list` is a daemon convenience, not an enumeration of durable truth. @@ -324,7 +328,9 @@ makes its operator contracts part of the milestone rather than an afterthought, so M5 fixes them. `loopex daemon` selects a root and a socket, prints exactly one readiness line on standard output — and only once the marker is held and the socket is bound and permission-checked — sends everything else to standard -error, stops on `SIGTERM` or `SIGINT`, and exits `0` for an operator stop or +error, stops on `SIGTERM` — or on a terminal `SIGINT`, which the launcher +forwards as `SIGTERM`, since the emulator reserves that signal — and exits `0` +for an operator stop or non-zero with a named reason class for a fatal one. There is no stop method on the wire, because ending every client's session residency is not authority a connection carries. A daemon takes the same composition inputs the app-server host takes — state From 4476bb9a8712c62bebde4cad6e70a680d8b2742c Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 00:23:30 -0700 Subject: [PATCH 074/585] plan(M5): state core's four changes in ADR 0032, source bounds to code ADR 0032's technical companion still said core's M5 changes stay at two in two passages, five lines after a sentence that said four. Both now name the four and call a deactivation call a further change beyond them. The limits-table preamble claimed every number came from a decision, while the two rows added for the cleanup grace and the Store's stop floor are sourced to constants in the code they bound. The preamble now admits that source, named with its line. --- ...aemon-attachment-residency-and-replay-technical.md | 11 ++++++----- docs/plans/M5-technical.md | 3 ++- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 644f811b5..53182e67f 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -274,8 +274,8 @@ beyond the four this milestone makes. A lifecycle notification from core to the would be a new core-to-host signal, with its own delivery and ordering questions, added for a listing field. A monitorable coordinator handle handed out to the daemon would export core's supervision topology across the boundary -and invite the daemon to reason about it. M5's core changes stay at two: -concurrent attachment, and the read-only existence query. +and invite the daemon to reason about it. M5's core changes stay at four, and +neither of these is among them. The lease-owner fatal rule in ADR 0033 is untouched by this and stays. The difference is ownership: a lease owner is a **daemon** process holding @@ -470,9 +470,10 @@ awaiting an answer, a recovery in progress, an unresolved `commit_unknown`, or an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and -M5's core changes are concurrent attachment and a read-only existence query, -neither of which stops anything, so a deactivation call would -be a second core change this milestone does not make. +none of M5's four core changes (concurrent attachment, the read-only existence +query, the excluded-function trace list, and `quiesce/2`) stops a coordinator, +so a deactivation call would be a further core change this milestone does not +make. - **What dormancy applies to.** Attachments, resident windows and socket output buffers, and nothing else. An idle attachment is evicted, its window diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 381dfb967..0e3d3dc0c 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1989,7 +1989,8 @@ Implement lifetime, transport and collaboration once, against the local adapter. **The numbers M5 commits to.** Every one comes from an accepted or proposed -decision named above; M5 introduces none of its own. +decision named above, or from a constant in the code it bounds, named with its +line; M5 introduces none of its own. | Ceiling | Value | Source | | --- | --- | --- | From 81081c8cf685df99d24445ada3a06550792ad167 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:35:49 -0700 Subject: [PATCH 075/585] plan(M5): three shutdown clocks, a durable drain cause, sliced waits Finding 1, the auditor's contract adopted as given. A session's `cleanup_grace_ms` is an input to cancellation only. The drain budget is derived from core -- `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, the field being real and documented as "the sum a process-liveness backstop must cover" (apps/loopex/lib/loopex/executor.ex:447, :470). Every non-Store stop shares ONE absolute deadline rather than a grace each, so the worst case is a bound and not a sum. The Store gets its own fixed 30 s phase from `@call_timeout` (local.ex:65), not `max(g, 30_000)`, and the same fixed phase applies in failed-start reverse cleanup. The operator-facing maximum is stated once -- drain + teardown + 30 s -- with the consequence of a shorter service-manager timeout and the note that the usual Store release is milliseconds. `quiesce/2` is redefined in three parts. It durably admits an abort carrying `"cause" => "operator_shutdown"` for every active session before cancelling anything, because ADR 0023 fixes that only a durable `session.abort` cancels and cancellation is never inferred (0023-technical:365, :169); the existing path is `propose_new/3` for `%{type: :abort}` (session_state.ex:1684-1700), whose `rejected_no_active_run` answer (:1750-1761) is the right one for an idle session. The `"cause"` field is called out as a durable record change. It then drives each session's cancellation under that session's own grace, and at the deadline it synchronously fences and terminates every unsettled coordinator and waits for its DOWN before returning -- closing the window where an "unsettled" coordinator could still commit after being reported. Cancelling with no durable command is recorded as rejected. Finding 7, probed at both pairs: `receive ... after 4_294_967_295` waits, `after 4_294_967_296` and `after 18_446_744_073_709_551_615` exit `:timeout_value` at once -- while core admits a grace up to 2^64-1 (@max_cleanup_grace_ms, executor.ex:75). Nothing in this repository slices a wait today, so the rule is stated: absolute monotonic deadlines, compared rather than subtracted, waited in 60_000 ms slices. A huge grace is accepted rather than refused, and the input table says so. The witnesses follow the mechanism: the abort record is asserted before any cancellation; the unsettled coordinator is asserted dead at the instant it is reported; the old "journal byte-identical to an abrupt death" claim is withdrawn, since a drain that records why it cancelled writes exactly one more record, and the case now asserts that difference. A new case composes a grace above 2^32-1 and asserts an ordinary start and stop. --- docs/plans/M5-technical.md | 394 ++++++++++++++++++++++++------------- docs/plans/M5.md | 30 ++- 2 files changed, 278 insertions(+), 146 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0e3d3dc0c..06b71cf22 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -130,7 +130,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` driving every active coordinator to settle within the composed cleanup grace and naming the sessions that did and did not — **both halves asserted**: a dispatched tool effect that settles inside the grace carries its ordinary terminal fact in the journal, and one held past the deadline is ended crash-equivalently with **no terminal claimed for it** — no `cancelled`, no `outcome_unknown`, no abort record — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal byte-identical to what an abrupt death at the same instant would have left. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting an abort with `"cause" => "operator_shutdown"` for every active session **before** cancelling anything, driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -485,7 +485,7 @@ and its refusal class: | Provider launch | `--provider-launch` / `LOOPEX_PROVIDER_LAUNCH` | none | `provider_launch_required`, `provider_launch_invalid` | | Policy | `--policy` / `LOOPEX_POLICY` | **none, deliberately** — authority is the operator's to name, as the app-server host already insists | `policy_required`, `policy_unknown` | | Provider credential | `LOOPEX_PROVIDER_API_KEY` | none | `provider_credential_required`, checked at start so an unattended launch refuses in a second rather than at the first dispatch. The daemon reads it once, deletes it from its environment and holds it in custody under ADR 0034 | -| Cleanup grace | `--cleanup-grace-ms` | the composition default | `cleanup_grace_invalid`, and the admitted domain is **an integer of 1 or more**. Zero is refused, which the local executor's own validation would admit (`apps/loopex_executor_local/lib/executor.ex:897`, `>= 0`) but core's `cancellation_bounds/1` refuses (`apps/loopex/lib/loopex/executor.ex:456`, `grace_ms >= 1`): a daemon composed with zero would carry a grace core cannot derive bounds from | +| Cleanup grace | `--cleanup-grace-ms` | the composition default | `cleanup_grace_invalid`, and the admitted domain is **an integer from 1 to `18_446_744_073_709_551_615`**, exactly core's own (`@max_cleanup_grace_ms`, `apps/loopex/lib/loopex/executor.ex:75`, and `grace_ms >= 1` at `:456`). Zero is refused, which the local executor's own validation would admit (`apps/loopex_executor_local/lib/executor.ex:897`, `>= 0`): a daemon composed with zero would carry a grace core cannot derive bounds from. A very large value is **accepted, not refused** — the daemon never passes it to a `receive … after` unsliced, for the reason the wait rule below gives | | Project resources | as the host already takes them | as today | as today | | Socket path | `--socket` | `/daemon/daemon.sock` | `socket_path_too_long`, `socket_permission_unverified`, `invalid_socket_path` for a path outside the root's `daemon/` directory | @@ -1182,12 +1182,89 @@ running with a handler and no owner. That class is in the exit list above and in the fatal-class map's note, and it is the one class no linked component produces. +**Three clocks, and no component invents a fourth.** An earlier revision gave +every component "the composed cleanup grace" and gave the Store a floor over +it. That was wrong twice: a session's `cleanup_grace_ms` is an input to +*cancellation*, not a shutdown deadline, and a per-component budget makes the +worst-case stop the sum of the components rather than a bound anyone can +state. The contract is three clocks: + +| Clock | What it bounds | Where the number comes from | +| --- | --- | --- | +| **`g`**, each session's committed `cleanup_grace_ms` | The cancellation of that session's effects, and nothing else | The session's own composition; already used by `Loopex.Executor.cancellation_bounds/1` | +| **`drain_ms`** | The whole drain, across every session | Derived: `max` over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` (`apps/loopex/lib/loopex/executor.ex:456-474`, where `cli_backstop_ms` is defined as `observe + reserve + terminal` and documented as "the sum a process-liveness backstop must cover"). `g` itself is never a deadline | +| **`teardown_ms`** | **One absolute deadline shared by every non-Store stop** — lease owners, the relay, the runtime, executor, workspace lease, transfers, custody, registry | A single budget the owner fixes once, so the worst case is one bound rather than a sum over components | +| **The Store phase** | The Store's stop alone | A **fixed 30 s**, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of `g` and of `teardown_ms` | + +`drain_ms` is derived rather than chosen because the cancellation it waits on +is already bounded by core: `cli_backstop_ms` is the number core itself says a +liveness backstop must cover for a session with that grace, so a drain that +waits exactly that long waits neither less than the cancellation needs nor +longer than core can justify. Taking the maximum over the drained sessions — +not the sum — is what keeps the bound flat as sessions multiply. + +**The Store phase is fixed, not `max(g, 30_000)`.** The previous revision's +`max` made an operator's grace able to *lengthen* the Store phase, which is +the one phase whose length has nothing to do with any session. Thirty seconds +is the Store's own bound on its synced call path, and releasing the marker is +that same class of work — `File.read`, `File.rm`, a parent-directory sync +(`writer_lock.ex:105-115`). **The usual release takes milliseconds**; the 30 s +is a ceiling that matters only when the filesystem is wedged, which is exactly +when killing the Store mid-release is worst. The same fixed phase applies in +the failed-start reverse cleanup, for the same reason. + +**So the operator-facing bound is stated, once:** + +> **Maximum graceful stop = `drain_ms` + `teardown_ms` + 30 s.** + +A service manager that kills the daemon sooner than that turns the stop into a +forced shutdown — the journal is still crash-equivalent, but work that would +have settled does not, and the marker may be left for the next daemon's +verified stale-writer recovery. The operator documentation states the bound +and that consequence together, so a `TimeoutStopSec` shorter than it is a +choice rather than an accident. + +**Every wait is an absolute deadline, sliced — because the BEAM's `after` has +a domain the plan must respect.** Core admits a `cleanup_grace_ms` up to +`18_446_744_073_709_551_615` (`@max_cleanup_grace_ms`, +`apps/loopex/lib/loopex/executor.ex:75`), and the derived budgets above are +sums of such values. A `receive … after` does not accept numbers that large. +Probed at **both** toolchain pairs: + +| `receive … after` | 1.18.5-otp-27 | 1.20.3-otp-29 | +| --- | --- | --- | +| `4_294_967_295` | accepted (waits) | accepted (waits) | +| `4_294_967_296` | **exits `:timeout_value` at once** | **exits `:timeout_value` at once** | +| `18_446_744_073_709_551_615` | **exits `:timeout_value` at once** | **exits `:timeout_value` at once** | + +The limit is 2^32-1 milliseconds, about 49.7 days, and exceeding it is not a +long wait but an immediate exit in the waiting process — which for the owner +would be a shutdown that never runs. Nothing in this repository slices a wait +today, so the rule is stated here: + +- **Every phase is an absolute instant**, `System.monotonic_time(:millisecond) + + budget`, computed once. Deadlines compose by comparison, not by + subtracting one timeout from another, so no arithmetic can produce a + negative `after` — which is the other way `after` fails, as the 1 ms stop + probe showed. +- **Every wait is taken in slices of at most `@wait_slice_ms`, 60_000**, a + minute being long enough that slicing costs nothing measurable and short + enough to be far inside the domain. After each slice the owner compares the + clock with the deadline and either waits again or gives up. A budget of any + admitted size is therefore reachable, and no `after` argument is ever larger + than the slice. +- **The composition-input table says what a huge value does**: it is accepted, + not refused, because core accepts it; the daemon simply never passes it to + `after` unsliced. An operator who composes a grace of a year gets a daemon + that waits a year, in minute slices, rather than one that exits instantly at + the first stop. + **Daemon-initiated shutdown is a drain and then a teardown, in reverse order.** `SIGTERM` reaches the owner — sent directly, or forwarded by the launcher from a terminal `SIGINT` — and it performs these six steps itself. They are the owner's code, not a supervisor's behaviour, which -is what lets each one carry a reason and lets the teardown use a bound the -owner chooses. +is what lets each one carry a reason and lets the teardown use one deadline +the owner fixes. 1. **The listener stops accepting, and the daemon refuses new admissions.** A new connection is refused rather than queued, and a command arriving on @@ -1195,30 +1272,37 @@ owner chooses. clients yet and nothing is closed: the connections stay open across the drain, because a client that is about to be told something true is better served by being told it than by an early close. -2. **The runtime is quiesced within the composed cleanup grace.** The owner - calls core's `quiesce/2` and waits for its answer, which names the sessions - that settled and the sessions that did not. This is the drain, and it is - the step that makes the Concept's promise true rather than aspirational; - what it does, and what it cannot do, is set out below. +2. **The runtime is quiesced within `drain_ms`.** The owner calls core's + `quiesce/2` with that derived deadline and waits for its answer, which + names the sessions that settled and the sessions that did not — and, by the + time it answers, every session it could not settle has already been fenced + and terminated inside core. This is the drain; what it does, and what it + cannot do, is set out below. 3. **Clients are told, and the socket path is unlinked.** Each open connection gets one `daemon.stopping` naming `operator_stop`, bounded best-effort as ADR 0032 fixes — one write attempt into the existing 4 MiB output buffer — and is closed. **Then the owner unlinks the socket path, here and not at the end**, because this is the last moment at which the daemon is certainly still the marker holder. -4. **Every lease owner stops**, in sequence, sharing one grace. Every lease - vanishes with them. Nothing durable is involved, and no client is left - holding one, because no connection survived step 3. Their exits are +4. **Every lease owner stops, then the admission relay**, in sequence, + against the shared `teardown_ms` deadline. Every lease vanishes with the + owners; the relay goes after them because it is what holds their admission + tickets, and stopping it first would discard a ticket a lease owner could + still be waiting on. Nothing durable is involved, and no client is left + holding a lease, because no connection survived step 3. Their exits are consumed like any other the owner asks for — a lease owner stopped here closes no controller attachment and produces no `control_owner_lost`, because there is no attachment left to close. -5. **The runtime stops, and this is where whatever did not settle ends.** The - helper for this step calls `Supervisor.stop(runtime_supervisor, :normal, grace)` - on the pid the composition function handed it, with `grace` the **composed - cleanup grace** — the same value the sessions were composed with, so no - number is introduced. It does **not** call `Loopex.Runtime.stop/1`: that is - arity one and uses the default `:infinity` timeout, which is exactly the - bound this step exists to supply. +5. **The runtime stops.** After the drain there is little left to end — every + coordinator quiesce could not settle was fenced and terminated inside core + before `quiesce/2` returned — so this step ends the tree rather than the + work. The helper calls + `Supervisor.stop(runtime_supervisor, :normal, remaining)` on the pid the + composition function handed it, where `remaining` is what is left of the + **shared `teardown_ms` deadline**, not a per-component grace. It does + **not** call `Loopex.Runtime.stop/1`: that is arity one and uses the + default `:infinity` timeout, which is exactly the bound this step exists to + supply. `Supervisor.stop/3` is `GenServer.stop(supervisor, reason, timeout)` (supervisor.ex:1152-1154 at the floor pair, :1197-1199 at the current @@ -1226,7 +1310,7 @@ owner chooses. same place — the helper — and its outcome is read the same way, from the exit on the owner's link. What `:proc_lib.stop/3` does to *its* caller on expiry, whatever shape that takes, is the helper's business and dies with - it. The owner's `after grace` fires, it kills the runtime supervisor with + it. The owner's wait on the shared deadline expires, it kills the runtime supervisor with `Process.exit(runtime_supervisor, :kill)`, and it reads the exit that follows: `:normal` or `:shutdown` where the tree came down on its own, `:killed` where the kill ended it, anything else classified. @@ -1282,62 +1366,33 @@ owner chooses. | Process | Bound | What it is waiting for | | --- | --- | --- | - | The executor | The **composed cleanup grace** | Nothing, in the executor itself: it neither traps exits nor defines `terminate/2`, so this stop returns quickly and the bound is a ceiling. What takes the time is the Port-owning workers it sets going, which the owner does not hold and cannot wait for | - | The workspace lease | The same grace | Nothing: it has no `terminate/2` and holds no file — the lease *is* the live process, so stopping it revokes it. The bound is a ceiling it will not reach | - | The transfers owner | The same grace | Closing the open transfer descriptors its `terminate/2` holds (`transfers.ex:146-149`) | - | The Store | `max(grace, 30_000)` — the one exception, below | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | - - No number is invented here: three of the four bounds are the composed - cleanup grace, which is what step 5 uses and what the sessions carry, and - the Store's floor is the Store's own existing call bound. Splitting the - grace into fractions would mean inventing ratios, and the minimalism budget - takes every number from an accepted or proposed decision or from the code - it already governs. **All four are - ceilings rather than expected waits**, which is the corrected reading: an - earlier revision expected the executor to spend real time here, on the - mistaken belief that it traps exits and cleans up in its own process. Only - the transfers owner and the Store run a `terminate/2` at all, and both are - short. **The transfers owner exists only when artifact transfers - were enabled**, as the composed set above says (`transfers` is listed there - as absent when disabled); where it is absent its row is not a stop the - owner skips at runtime so much as a pid it never held, and the step for it - does not exist in that daemon's sequence at all. - - Each of these bounds is the `after grace` on the owner's own wait, not a - second clock: the helper passes the same number to `GenServer.stop/3`, so a - component is given the grace once. The wait after the kill carries no - `after`, for the reason the general rule gives — it waits for a signal that - already exists. - - **The Store's wait has a floor, and the reason is a defect this plan would - otherwise have shipped.** The kill after a wait is `Process.exit(pid, - :kill)`, which runs no `terminate/2`. So at a small grace — and `1` is a - composable value — the owner's `after grace` fires before the Store can - finish releasing the marker, and the kill leaves the marker **on a - deliberate operator stop**, which is exactly what this plan promises never - happens. An operator flag would have quietly broken a durability claim. - - The Store's wait is therefore `max(grace, 30_000)`. The number is not - invented: `30_000` is the Store's own `@call_timeout` - (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), the bound it - already puts on its synchronous, synced call path — and releasing the - marker is the same class of work against the same root, `File.read`, - `File.rm` and a parent-directory sync (`writer_lock.ex:105-115`). Using the - Store's own bound for the Store's own file I/O introduces no number and - asks no one to pick one. - - This is a **ceiling, not a wait**: a healthy Store releases in - milliseconds, so an ordinary stop is not lengthened at all. It bites only - when the filesystem is wedged, which is precisely when killing the Store - mid-release is the wrong thing to do. No other component gets a floor, - because no other component's `terminate/2` releases a durable exclusion. - - **The residual is stated.** A Store that has not released within - `max(grace, 30_000)` is killed, and the marker survives. That is the same - stale marker ADR 0031's recovery rule already answers: the next daemon - probes the marker's recorded holder and reclaims it where that holder is - proved dead, refuses `store_writer_unverifiable` where it cannot be - decided, and refuses `store_writer_active` where it is alive. + | The executor | What remains of **`teardown_ms`** | Nothing, in the executor itself: it neither traps exits nor defines `terminate/2`, so this stop returns quickly. What takes the time is the Port-owning workers it sets going, which the owner does not hold and cannot wait for | + | The workspace lease | What remains of `teardown_ms` | Nothing: it has no `terminate/2` and holds no file — the lease *is* the live process, so stopping it revokes it | + | The transfers owner | What remains of `teardown_ms` | Closing the open transfer descriptors its `terminate/2` holds (`transfers.ex:146-149`) | + | Custody, then the registry | What remains of `teardown_ms` | Nothing durable | + | **The Store** | A **fixed 30 s**, its own phase | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | + + **"What remains" is one deadline, not one budget each.** The owner computes + an absolute instant once — `System.monotonic_time(:millisecond) + + teardown_ms` — and every non-Store stop from step 4 through this one waits + until that instant or until its exit arrives, whichever comes first, then + kills. So a slow lease owner spends the same clock a slow executor would; + the worst case is `teardown_ms`, not `teardown_ms` multiplied by the number + of components. An earlier revision gave each component its own grace, which + made the worst-case stop a sum nobody had written down. + + **The Store's phase is separate and fixed**, for the reason the three + clocks give: it is the one stop whose `terminate/2` releases a durable + exclusion, and its length has nothing to do with any session's cancellation + grace. It begins when the teardown deadline is done with, runs for at most + 30 s, and usually finishes in milliseconds. + + **The residual is stated.** A Store that has not released within its 30 s + is killed, and the marker survives. That is the same stale marker ADR + 0031's recovery rule already answers: the next daemon probes the marker's + recorded holder and reclaims it where that holder is proved dead, refuses + `store_writer_unverifiable` where it cannot be decided, and refuses + `store_writer_active` where it is alive. **The operating-system residual, stated for the ordinary path and not only for a killed executor.** Whether the executor stops cleanly or is killed, @@ -1392,43 +1447,78 @@ on 2026-09-20 and gave it one. The mechanism is a **fourth core change**, beside concurrent attachment, the existence query and the trace exclusion: ```elixir -Loopex.Runtime.quiesce(runtime, deadline_ms) :: +Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: {:ok, %{settled: [session_id], unsettled: [session_id]}} ``` -It is defined entirely in terms of mechanisms that already exist: - -- **Refusal comes first.** Every active coordinator stops admitting new - commands for the duration. Nothing new can be started while the drain runs, - and no client command can arrive anyway, because step 1 has already refused - admissions at the daemon. -- **What is in flight is driven through the cancellation that exists**, not - through a new one. That is the sequence a coordinator already runs for an - abort: `Loopex.Executor.cancel/4` (core) under the bounds - `Loopex.Executor.cancellation_bounds/1` derives from the session's committed - cleanup grace (`apps/loopex/lib/loopex/executor.ex:456-474`), which the coordinator already uses at - `session_coordinator.ex:3614` and `:5366`. Quiesce adds no bound, no - callback and no durable command. -- **It returns when every coordinator has settled or the deadline passes**, - naming both sets. `Loopex.Runtime.Control` already holds every active - session and its coordinator pid, so there is nowhere else this could live - and nothing to enumerate that core does not already have. +**Three parts, and the first is the part an earlier revision got wrong.** + +1. **A durable cause, admitted before any cancellation.** ADR 0023 fixes that + *only* the durable `session.abort` command cancels, and that cancellation + is "never inferred from EOF or death" + (`0023-…-technical.md:365`, with the method table at `:169`). Quiesce + cancels, so quiesce must admit. For every active session it therefore + **admits an abort through the existing path, carrying the cause + `operator_shutdown`**, and only then runs that session's cancellation. The + path is the one that exists: `propose_new/3` for `%{type: :abort}` writes a + `command_admitted` record with `"command_type" => "abort"` and + `"admission" => "accepted"` (`session_state.ex:1684-1700`), resolving the + queued steer and follow-up as it goes, and answers with + `"admission" => "rejected_no_active_run"` where nothing is running + (`:1750-1761`) — the right answer for an idle session, needing no special + case. + + **That is a durable record field**, and the plan says so rather than + letting it look like a private detail: the admitted abort record gains a + bounded `"cause"` naming why the abort exists — `operator_shutdown` here, + absent for a client's own `session.abort` — so an operator reading a + journal can tell a shutdown from a cancellation somebody asked for. It is + additive to a record generation 1 already writes and changes no existing + field. + + The rejected option is recorded: cancelling **without** a durable command, + which the previous revision's "quiesce adds no durable command" amounted + to, contradicts ADR 0023 outright and would leave a journal saying a run + ended for a reason nobody recorded. + +2. **A derived budget.** `drain_deadline_ms` is `drain_ms`: the maximum over + the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` + (`apps/loopex/lib/loopex/executor.ex:456-474`). Inside it each session's + cancellation runs under its own `g`, through `Loopex.Executor.cancel/4` + (core) exactly as the coordinator already drives it at + `session_coordinator.ex:3614` and `:5366`. + +3. **A synchronous fence at the deadline.** When the budget is spent, core + does not merely report what did not settle: for each unsettled session it + **fences the coordinator, terminates it, and waits for its `DOWN` before + returning**. Without that, "unsettled" would name a coordinator still + running and free to commit a terminal fact after the daemon had reported it + unfinished and moved on to tell clients — a report false by the time it was + read. After `quiesce/2` returns, every session in `unsettled` has no live + coordinator, and nothing can be appended for it until the next activation. + +`Loopex.Runtime.Control` already holds every active session and its +coordinator pid, so there is nowhere else this could live and nothing to +enumerate that core does not already have. **Why core rather than the daemon.** The daemon cannot do this without reaching into coordinator internals, which the dependency direction forbids, or running a cancellation loop of its own, which is precisely the second loop -this milestone forbids. Core owns coordinator lifetime and cancellation, so -core is where a bounded settle belongs. It returns **plain data** — session +this milestone forbids — and it certainly cannot admit a durable command on +its own authority. Core owns coordinator lifetime, cancellation and admission, +so core is where a bounded settle belongs. It returns **plain data** — session IDs and two lists — so nothing about a coordinator crosses the boundary. -**What it does not promise, stated because the numbers say so.** -`cancellation_bounds/1` derives an executor observation bound of -`max(10_000, grace_ms + 2_000)` (`apps/loopex/lib/loopex/executor.ex:458`). A daemon composed with a -cleanup grace below about ten seconds will therefore reach its own deadline -while an effect's cancellation is still within *its* bound. That effect is -reported **unsettled**, and the teardown ends it crash-equivalently: the -deadline is the daemon's, not the executor's, and quiesce does not extend one -to satisfy the other. +**What it does not promise.** A session whose cancellation cannot finish +inside the derived budget is reported **unsettled**, and its coordinator is +fenced and terminated at the deadline. Because the budget is derived from the +same formula the cancellation uses, this is the case where an effect exceeds +even its own backstop — not the case where the daemon was impatient. An +earlier revision used the raw cleanup grace as the drain deadline, which +guaranteed the mismatch: `cancellation_bounds/1` derives an observation bound +of `max(10_000, grace_ms + 2_000)` from that same grace +(`apps/loopex/lib/loopex/executor.ex:458`), and `cli_backstop_ms` is larger +still. **A session waiting on an interaction cannot settle, and that is correct.** An answer to a durable interaction is a session command under ADR 0024, and @@ -1465,21 +1555,24 @@ learns the reason from the record where the write succeeds and from the close where it does not — that is the whole promise, and no part of this plan depends on a stronger one. -**Cancellation is not the daemon's to run**, which an earlier draft claimed. -It is the coordinator's, as part of a session's own durable command, and a -daemon-side cancellation path is precisely the second loop this milestone -forbids. Two alternatives were rejected with it. Host-authorized durable -aborts — the daemon admitting an abort per session on the way down — would -have the daemon issuing mutations on nobody's authority, at the moment it is -least able to see them through. An unbounded natural drain would make -`SIGTERM` unbounded, which is not a stop. +**Cancellation is not the daemon's to run**, and that rule survives the drain +rather than being softened by it. The abort quiesce admits is admitted **by +core, on the operator's signal, through core's own path** — not by the daemon +issuing a mutation over the socket, which stays forbidden and is why there is +no `daemon.stop` method on the wire. An earlier revision rejected +"host-authorized durable aborts" as the daemon issuing mutations on nobody's +authority; that was right about the daemon and wrong as a reason to cancel +with no record at all, which is what it left behind. An unbounded natural +drain was rejected with it and stays rejected: it would make `SIGTERM` +unbounded, which is not a stop. **The drain is core's, not the daemon's**, and that is the same rule seen from the other side. The daemon asks for a bounded settle and waits for the answer; -every decision inside it — which effect to cancel, under what bound, what to -record — is the coordinator's, running the paths it already has. The daemon -neither issues a cancellation nor interprets one, and a coordinator that -cannot settle in time is reported rather than overridden. +every decision inside it — which abort to admit, which effect to cancel, +under what bound, what to record — is core's, running the paths it already +has. The daemon neither admits a command nor interprets a cancellation, and a +session that cannot settle in time is fenced by core rather than left running +behind a report. **Store loss, a fail-stop path.** The owner holds the Store's link and its pid, so the adapter's termination arrives as `{:EXIT, store_pid, reason}` at @@ -1726,26 +1819,40 @@ the cause and try again without a recovery step. Store still stopped, the socket still unlinked — and that the exit class is `transfers_lost` rather than `operator_stop`, because the component died of its own reason and not because the owner asked. -- **In-flight shutdown, both halves of it.** Two cases, because the drain - has two outcomes and proving one would hide the other. +- **In-flight shutdown, both halves of it.** Two cases, because the drain has + two outcomes and proving one would hide the other. Both assert the durable + cause first: a `command_admitted` record with `"command_type" => "abort"` + and `"cause" => "operator_shutdown"` appears for the active session + **before** any cancellation, because ADR 0023 admits no cancellation that + was not commanded. *It settles.* A daemon with a dispatched tool effect that **can** be - cancelled inside the composed cleanup grace receives `SIGTERM`. The case + cancelled inside its session's own grace receives `SIGTERM`. The case asserts the effect settles during `quiesce/2`, that its session is in the - returned `settled` list, that the journal carries its ordinary terminal - fact, and that the `daemon.stopping` record is written **after** the drain - rather than before it. + returned `settled` list, that the journal carries its ordinary terminal fact + — `cancelled`, which is now a true statement about work that was truly + cancelled — and that the `daemon.stopping` record is written **after** the + drain rather than before it. - *It does not.* A daemon with an effect held past the deadline and an + *It does not.* A daemon with an effect held past the drain budget and an unresolved mutation receives `SIGTERM`. The case asserts the session is in - the `unsettled` list, and then the negative that matters: **no terminal - mutation is claimed** for it — no `cancelled`, no `outcome_unknown`, no - abort record appears in the journal on the way down. The ambiguous mutation - stays `commit_unknown`, each client is sent the stop reason on a transport - that accepts it and sees the close either way, and the exit is still `0`. + the `unsettled` list; that its coordinator is **gone before `quiesce/2` + returned**, proved by the pid being dead at the instant the daemon reports + it, which is what the synchronous fence exists for; and then the negative + that matters: **no terminal is claimed for the work that did not settle** — + no `cancelled`, no `outcome_unknown` for it. The ambiguous mutation stays + `commit_unknown`, each client is sent the stop reason on a transport that + accepts it and sees the close either way, and the exit is still `0`. Activating that session again afterwards resolves the transaction to exactly - one outcome through the existing reconciliation, and the journal is - byte-identical to what an abrupt death at the same instant would have left. + one outcome through the existing reconciliation. + + The journal after this path is **not** byte-identical to an abrupt death at + the same instant, and the case asserts the difference rather than the old + equality: it holds exactly one more record, the admitted abort with its + cause. An earlier revision claimed byte-identity, which was true of a design + that cancelled nothing and is false of one that records why it cancelled. + What remains identical is what the abrupt-death case actually needs: the + unresolved transaction, its fence, and the outcome reconciliation produces. - **Store-loss fail-stop.** The Store is made to terminate under a live listener. The case asserts the daemon observed it, closed the listener and every connection with `store_lost`, unlinked the socket, and exited non-zero @@ -1815,7 +1922,7 @@ the cause and try again without a recovery step. daemon exits `registry_lost` and `custody_lost` respectively, sends that `fatal:` on the wire, and leaves no stale marker. - **The stop timeout is exercised, not assumed.** A session is made to hold - the runtime's teardown past the composed cleanup grace. The case asserts the + the runtime's teardown past the shared teardown deadline. The case asserts the owner **survives** rather than dying of whatever the stop did to the helper, that it then kills the runtime supervisor, and that it still reaches the Store stop and the socket unlink — the step a stop called inline would skip. @@ -1834,12 +1941,20 @@ the cause and try again without a recovery step. It also asserts the thing a grace of 1 ms would otherwise have broken: **the next daemon opens that root with no stale marker to recover.** That is - the Store's floor doing its work — the Store is waited on for - `max(grace, 30_000)`, not for 1 ms — and without it this case would have - left a marker behind on a deliberate operator stop. A second case composes - `cleanup_grace_ms: 0` and asserts the daemon refuses at startup with - `cleanup_grace_invalid`, holding no marker and binding no socket. Both run - at both toolchain pairs, because the timeout result was observed at both. + the Store's own phase doing its work — the Store is waited on for a fixed + 30 s that no grace can shorten — and without it this case would have left a + marker behind on a deliberate operator stop. + + Two more cases sit beside it. One composes `cleanup_grace_ms: 0` and asserts + the daemon refuses at startup with `cleanup_grace_invalid`, holding no + marker and binding no socket. One composes a grace **larger than 2^32-1 + milliseconds** — admitted, because core admits up to + `18_446_744_073_709_551_615` — and asserts the daemon starts, stops and + releases the marker normally: the value reaches no `receive … after` + unsliced, which is what the wait rule promises and what a direct `after` + would have turned into an immediate `:timeout_value` exit. All of them run + at both toolchain pairs, because both timeout results were observed at + both. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting @@ -2010,7 +2125,10 @@ line; M5 introduces none of its own. | Socket path bound, over `/daemon/daemon.sock` | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | -| Floor on the Store's stop | `max(grace, 30_000)`, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), so a small grace cannot kill it before `terminate/2` releases the marker | This plan, against the Store's existing bound | +| Drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | +| Non-Store teardown | one absolute deadline shared by every non-Store stop | This plan; one bound rather than a sum over components | +| Store shutdown phase | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | +| Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | | Takeover grace beyond expiry | none; takeover is eligible at expiry and granted once the session's in-flight admission set is empty | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 31bf08c96..5f01672a6 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -51,7 +51,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within the composed cleanup grace** through core's `quiesce/2` — every active coordinator refusing new commands while what is in flight is driven through the cancellation sequence that already exists, to the bounds it already derives — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits an abort with the cause `operator_shutdown` for every active session before cancelling anything, drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -363,15 +363,29 @@ did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. **The drain has a mechanism, and it is core's.** M5 adds `quiesce/2` to -`Loopex.Runtime`: every active coordinator refuses new commands, what is in -flight is driven through the cancellation sequence a coordinator already runs -for an abort — under the bounds core already derives from the session's -committed cleanup grace — and the call returns when every coordinator has -settled or the deadline passes, naming which sessions did and which did not. -It belongs in core because core owns coordinator lifetime and cancellation; a +`Loopex.Runtime`, and it has three parts. It **durably admits an abort** +carrying the cause `operator_shutdown` for every active session, because ADR +0023 fixes that only a durable `session.abort` cancels and nothing may infer +cancellation from a signal. It then drives what is in flight through the +cancellation sequence a coordinator already runs for an abort, under the +bounds core already derives from that session's committed cleanup grace. And +at the deadline it **fences and terminates** every coordinator that has not +settled, waiting for each to be gone before it answers — so "unsettled" names +a session with no live coordinator rather than one still free to commit +something after the daemon has reported it unfinished. It belongs in core +because core owns coordinator lifetime, cancellation and admission; a daemon-side drain would have to reach into coordinator internals, which the dependency direction forbids, or run a cancellation loop of its own, which is -the second loop this milestone forbids. +the second loop this milestone forbids, and it could not admit a durable +command on its own authority at all. + +**A graceful stop has a stated maximum**, because an operator configuring a +service manager needs one: the derived drain budget, plus one shared budget +for every non-Store teardown, plus a fixed thirty-second Store phase. A +service manager that kills the daemon sooner turns the stop into a forced +shutdown — the journal stays crash-equivalent, but work that would have +settled does not, and the writer marker may be left for the next daemon's +verified recovery. **Both halves of the outcome are stated.** Work that settles within the grace has its ordinary terminal facts in the journal, `cancelled` among them where a From 6b8e910ce360fa98934ce7ddd3cdffecc746c346 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:38:11 -0700 Subject: [PATCH 076/585] plan(M5): unlink only under proved marker ownership, never after Finding 2. A daemon's claim on the socket pathname is its writer marker, so the claim ends when the marker does -- and the Store releases it in its own `terminate/2` without asking. The rule is now a precondition rather than a comparison: immediately before the unlink, and nowhere else, the owner checks that the Store process is alive and still owns its marker, and unlinks only if both hold; the unlink precedes any Store stop. The fail-stop path never unlinks at all. The next verified marker holder removes the stale pathname before binding, which is a startup step with its own witness. Deleted with it: the `File.stat` inode guard, which tried to make unlinking safe after ownership had lapsed; the admitted stat-then-unlink race, a window this design does not have; and the "a successor whose socket was removed is simply restarted" assumption, which was a claim about an operator rather than about this system. The deferred-exit case is answered by the same check -- the owner asks the Store rather than trusting its own belief about it, at the moment of asking. The precondition needs something `WriterLock` does not expose (writer_lock.ex:92-105), so the plan names the addition instead of assuming it: one read-only call on the local adapter answering whether the marker file still holds this daemon's marker, written from state the adapter already carries. The ownership table stops calling that application unchanged. Reverse cleanup gets the same treatment it gained on the orderly path: one shared teardown deadline, and the Store's fixed 30 s phase, since a failed start that killed the Store mid-release would leave exactly the stale marker it is trying to avoid. ADR 0031's fail-stop sentence and ADR 0032's socket-exclusion rule follow. --- ...store-selection-and-migration-technical.md | 9 +- ...tachment-residency-and-replay-technical.md | 12 +- docs/plans/M5-technical.md | 171 +++++++++++------- 3 files changed, 119 insertions(+), 73 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 0e6af5e88..8605aebfd 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -57,9 +57,12 @@ reason to any callback. It does not compose through process `RuntimeOwner` spawns and which returns no adapter pid — a daemon on that bracket could not observe this failure at all. On the reported exit it refuses service, closes every connection with `store_lost`, or -`store_capacity_exceeded` where that was the store's own reason, unlinks the -socket and exits non-zero. The next daemon finds no marker to recover, because -the dying store already gave it back. +`store_capacity_exceeded` where that was the store's own reason, and exits +non-zero. It does **not** unlink the socket: the marker is already released, +so this daemon's claim on that pathname has ended, and ADR 0032 makes removing +it the next verified marker holder's job. The next daemon finds no marker to +recover, because the dying store already gave it back, and removes the stale +pathname before it binds. An abrupt kill of the daemon runs no `terminate/2` at all, which is why *that* leaves a marker behind and why the next daemon's verified stale-writer diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 53182e67f..0918f62c7 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -99,7 +99,17 @@ with `store_writer_active` where the holder is alive. All three are proved before the socket path is read, unlinked or bound. Only the marker holder may remove a stale `daemon.sock` left by a dead daemon and bind a new one, so two simultaneous starts on one root resolve at the marker, exactly one listener exists, and the loser exits -without touching the socket. If the daemon loses store ownership while +without touching the socket. + +**Removing the pathname is the successor's job, not the predecessor's**, and +that follows from the same rule read in the other direction. A daemon's claim +on the path is its marker, so the claim ends when the marker does — which can +happen without the daemon being asked, since the Store releases the marker in +its own `terminate/2`. A daemon therefore unlinks only while it can still show +it holds the marker, and one that has lost it, or cannot show it, leaves the +file. Nothing is lost by that: the next daemon to acquire and verify the +marker removes the stale pathname before binding, which is the one moment at +which removing a socket file is unambiguously correct. If the daemon loses store ownership while running, because its Store child exits or the marker can no longer be proved held, it closes the listener and every connection before anything else and then exits; no connection outlives the daemon's ownership of the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 06b71cf22..2af97f368 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -39,7 +39,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | --- | --- | --- | | `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace`'s excluded-MFA list, which keeps a named function out of a trace session before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | -| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | +| `loopex_store_local` | The local adapter, unchanged in behaviour and gaining exactly one read-only call — whether the marker file still holds this daemon's marker, which the socket-unlink precondition needs and `WriterLock` does not expose (`writer_lock.ex:92-105`) — its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_composition` | The edge-assembly sequence, and the one new public function that runs it in the caller's process and returns the edges — used by `RuntimeOwner` and by the daemon's owner | Daemon lifetime, ownership of what it assembles, or any knowledge of a daemon | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses, and its use of `with_runtime/2`, which M5 does not change | Daemon lifetime or residency | @@ -742,9 +742,12 @@ runtime — rather than against a staged one the plan would have to invent: never reads, unlinks or binds the socket path. 5. **Read the session directory and build the index**, refusing at the recorded-entry bound. -6. **Create the `0700` subdirectory and bind the `0600` socket**, read back - and verify ownership and mode, and **capture the bound path's device and - inode** — the identity the fail-stop unlink rule below compares against. +6. **Create the `0700` subdirectory, remove any stale socket pathname, and + bind the `0600` socket**, then read back and verify ownership and mode. + Removing the stale pathname is this daemon's right and only this daemon's: + it holds the verified marker, which is the only moment at which removing a + socket file is unambiguously correct. A predecessor that left one — every + fail-stop leaves one — is cleaned up here rather than by itself. 7. **Begin accepting**, then **print the readiness line**. No lease owner exists at this point, and none is started here: one is started @@ -1088,54 +1091,75 @@ than in taste: `Loopex.Store.Local` answers an append error with observes it, the store is gone and the marker is already released. A sequence that ends "then stop the Store" cannot run when the Store is what died. -**Who may unlink the socket, and when that stops being this daemon.** The -socket path is not the daemon's by possession; it is the daemon's *because it -holds the writer marker*, which is what ADR 0032 already says — only the -marker holder may unlink or bind. The consequence an earlier revision missed -is that the permission **ends when the marker does**, and the marker is -released by the Store's `terminate/2` (`local.ex:166`), which can happen -before the daemon is finished. - -Two paths, two rules: - -- **Orderly stop: unlink while still holding the marker.** Step 1 does it, - immediately after the listener stops and long before the Store. No successor - can have acquired the marker yet, so the path being unlinked is certainly - this daemon's. Leaving the unlink to the end — where earlier revisions had - it — meant unlinking after the marker was already released, and a successor - that acquired it in that window would have had *its* socket removed by a - daemon on its way out. -- **Fail-stop where the marker is already gone.** On `store_lost` and - `store_capacity_exceeded` the Store released the marker before the daemon - could act, so the daemon can no longer assume the path is its own. It - therefore compares identity rather than presence: at bind it captured the - path's `File.stat` device and inode, and at unlink it stats the path again. - **Equal device and inode: unlink. Anything else — a different inode, or - `{:error, :enoent}` — leave the path alone.** A successor's socket is a - different inode, which is what makes this decidable; verified by probe: a - bound path stats as `type: :other` with an inode, and a rebind of the same - path yields a different inode. - -**The residual is the window between the stat and the unlink**, and it is -stated rather than papered over: a successor that acquires the marker, removes -the stale path and binds entirely between our two syscalls would still lose -its socket file. Nothing narrows that further without a second lock, and a -second daemon-owned lock file is rejected — it would duplicate the marker's -stale-writer recovery machinery, including its own staleness question, to -guard a window one syscall pair wide. What is at stake is also bounded: the -socket is a path, never durable truth. A successor that loses its file serves -no client and is restarted; the marker it holds, which is the real exclusion, -is untouched, so nothing can write to the root behind it. +**Who may unlink the socket: only a daemon that still demonstrably holds the +marker, and nobody else ever.** The socket path is not the daemon's by +possession; it is the daemon's *because it holds the writer marker*, which is +what ADR 0032 already says. The consequence an earlier revision missed is that +the permission **ends when the marker does**, and the marker is released by +the Store's `terminate/2` (`local.ex:166`) — which can happen before the +daemon is finished, and without the daemon being asked. + +The rule is therefore one rule, not two, and it is a **precondition rather +than a comparison**: + +- **A daemon unlinks the path only while it can show it still holds the + marker.** Immediately before the unlink, and nowhere else, the owner checks + two things: that the Store **process is alive**, and that the Store still + **owns the marker it took**. Both must hold; either failing means this + daemon may no longer touch the path, and it does not. +- **The unlink precedes any Store stop**, so on the orderly path the check is + being made while the Store is still running normally and the answer is + ordinarily yes. +- **The fail-stop path never unlinks at all.** On `store_lost` and + `store_capacity_exceeded` the marker is already gone, so the precondition + can never hold. On the other classes the daemon *could* unlink, and still + does not: a fail-stop is a path where something the daemon depended on has + failed, and the pathname is not worth a check it might get wrong. It leaves + the file. +- **The successor removes what a predecessor left.** A daemon that has + acquired and verified the marker removes the stale pathname before binding — + that is its right, because it *is* the marker holder, and it is the only + moment at which removing a socket file is unambiguously correct. This is + the rule that makes the fail-stop path's litter harmless, and it is stated + as a startup step rather than as a hope. + +**The ownership check needs a narrow addition to the local adapter, and the +plan names it rather than assuming it.** `Loopex.Store.Local.WriterLock` +exposes `acquire/3` and `release/1` and nothing else (`writer_lock.ex:92-105`); +there is no way to ask "do I still hold this". M5 adds one read-only call on +the adapter — answered from the state it already carries, the `writer_lock` +term it was given at open — that reports whether the marker file still holds +this daemon's marker. It writes nothing, changes no behaviour, and exists so +that the unlink has a precondition it can actually evaluate. This is +`loopex_store_local` work, small and named, and the ownership table says so +rather than continuing to call that application unchanged. + +**What this deletes.** The inode guard is gone: comparing a `File.stat` device +and inode against a pair captured at bind was an attempt to make unlinking +safe *after* ownership had lapsed, and the honest answer is that it is never +safe then. Gone with it is the admitted stat-then-unlink race — a window this +design does not have, because it never unlinks without ownership — and the +assumption that a successor whose socket file was removed would simply be +restarted, which was a claim about an operator's behaviour rather than about +this system. + +**One ordering consequence, and the reason the check is a liveness check and +not a flag.** During an orderly stop the owner defers the exits it is not +currently waiting for, so a Store that dies *during* the sequence is not +classified until its own step. The unlink must not rely on the owner's belief +about the Store; it asks the Store, at the moment of asking. A Store that has +died leaves the check failing, the path untouched, and the successor's startup +to remove it. **`--socket` is constrained to the selected root.** An override must resolve inside that root's `daemon/` directory — the same directory the default path sits in, under the same owner and symbolic-link rules — and a path outside it is refused at startup with `invalid_socket_path`, before the marker is acquired. Without that constraint two daemons on *different* roots could be -pointed at one path, and neither's marker would say anything about the other's -socket: the identity rule above would be comparing inodes between daemons that -have no exclusion between them at all. Inside one root, the marker is the -exclusion and there is exactly one holder. +pointed at one path, and neither's marker would say anything about the +other's: the precondition above would be satisfied by a daemon that holds a +marker for a different root entirely, which says nothing about this path. +Inside one root, the marker is the exclusion and there is exactly one holder. **How a signal reaches the owner, and when the handler is installed.** The daemon does not inherit a usable signal disposition; it installs one, and the @@ -1278,12 +1302,14 @@ the owner fixes. time it answers, every session it could not settle has already been fenced and terminated inside core. This is the drain; what it does, and what it cannot do, is set out below. -3. **Clients are told, and the socket path is unlinked.** Each open connection - gets one `daemon.stopping` naming `operator_stop`, bounded best-effort as - ADR 0032 fixes — one write attempt into the existing 4 MiB output buffer — - and is closed. **Then the owner unlinks the socket path, here and not at - the end**, because this is the last moment at which the daemon is certainly - still the marker holder. +3. **Clients are told, and the socket path is unlinked — if it is still + ours.** Each open connection gets one `daemon.stopping` naming + `operator_stop`, bounded best-effort as ADR 0032 fixes — one write attempt + into the existing 4 MiB output buffer — and is closed. **Then the owner + checks that the Store process is alive and still owns its marker, and + unlinks only if both hold.** This is before any Store stop, so on an + ordinary stop both hold and the path goes. Where they do not, the path is + left for the next verified marker holder to remove at its own startup. 4. **Every lease owner stops, then the admission relay**, in sequence, against the shared `teardown_ms` deadline. Every lease vanishes with the owners; the relay goes after them because it is what holds their admission @@ -1632,11 +1658,11 @@ to write. and found dead, refuses with `store_writer_unverifiable` where it cannot be decided, and refuses with `store_writer_active` where it is alive. A surviving marker is a case with a defined answer, not a corruption. -5. Unlink the socket **only if it is still ours**. On the six classes where - the daemon still holds the marker this is unconditional. On the two store - classes the marker is already gone, so the owner applies the identity rule - above: stat the path, unlink on an equal device and inode, leave it alone - on anything else. **The runtime root, the lease owners, the registry, the +5. **The socket path is left alone.** The fail-stop never unlinks: on the two + store classes the marker is already gone and the precondition can never + hold, and on the rest the daemon declines to spend a check it might get + wrong on a path whose litter the next verified marker holder removes before + binding anyway. **The runtime root, the lease owners, the registry, the custody process and the transfers owner are not stopped on this path**, and that is deliberate rather than an omission. A fail-stop is not a drain, and none of them owns anything that outlives the VM: the executor does, which @@ -1777,9 +1803,12 @@ start order** — runtime, executor, workspace lease, transfers where it exists releases the marker. Each of those stops is the same call and the same discipline as a shutdown -stop: a monitored helper running `GenServer.stop(pid, :normal, grace)` with -the composed cleanup grace, the owner waiting on its own link with `after -grace`, and a kill on expiry. Startup introduces no second teardown +stop: a monitored helper running `GenServer.stop(pid, :normal, …)`, the owner +waiting on its own link against **one shared teardown deadline** and killing +on expiry, and — for the Store — **the same fixed 30 s phase** the orderly +path gives it, for the same reason: this is the stop that releases the marker, +and a failed start that killed the Store mid-release would leave exactly the +stale marker it is trying not to leave. Startup introduces no second teardown mechanism; it reuses the one the shutdown sequence defines, against the pid map it already holds. @@ -1878,15 +1907,19 @@ the cause and try again without a recovery step. than a silent `:shutdown`. A lease owner is deliberately not in this case: its own witness is below, and it asserts the daemon **keeps running**. - **A successor's socket survives its predecessor's exit.** Two daemons on - one root. The first is paused between the Store's marker release and its - unlink — the fail-stop window, reached by making the Store terminate and - holding the owner at that point. The second acquires the marker, removes the - stale path, binds its own socket, and prints readiness. The first is then - released. The case asserts that it **does not unlink** the path, because the - inode it stats is not the one it captured at bind, and that the second - daemon's socket is still bound and still serving a client afterwards. The - orderly variant asserts the other half: the unlink happens in step 1, while - the marker is still held, so a successor cannot even reach that window. + one root. The first loses its Store, so the marker is released before it can + act, and it is held at the point where an earlier design would have + unlinked. The second acquires the marker, removes the stale path as the + verified holder, binds its own socket and prints readiness. The first is + then released. The case asserts it **unlinks nothing** — a fail-stop never + does — and that the second daemon's socket is still bound and still serving + a client afterwards. + + The orderly variant asserts the precondition rather than a comparison: the + unlink happens only after the owner has confirmed the Store process alive + and still holding its marker, and a variant that kills the Store immediately + before that check asserts the path is **left alone** and that the next + daemon removes it at startup and serves normally. - **A `--socket` path outside the root is refused.** A path in a directory that is otherwise perfectly valid — right owner, right mode — but outside the selected root's `daemon/` directory exits `invalid_socket_path` with no From c2a8e77cf33abb6804ec3b79e16e64549b5ab65c Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:41:28 -0700 Subject: [PATCH 077/585] adr(0033): add the admission relay, fix the owner lifecycle Finding 3, maintainer 2026-09-20: keep per-session owners and add a fence. Core has no writer epoch, so a lease owner that dies with an admission inside core takes the only record of it; a replacement owner could then grant a successor whose call overtakes the older one. A fresh epoch does not prevent that -- it stops a later command from the old tenure, which is a different thing from ordering -- and core orders what it receives, not what is in flight. One fixed daemon-owned process, the admission relay, now routes every core call the daemon makes, issues a ticket per call naming the session, survives lease-owner death, and blocks a replacement owner's first grant for a session until that session's tickets settle. A ticket settles when the relay observes the call's outcome: its task returning core's result, or that task dying, which the relay treats as settled-unknown -- the fact `commit_unknown` already carries. A connection disappearing settles nothing, because the call it made is still running. Daemon-fatal owner failure is recorded as the smaller design the maintainer declined. The relay joins the fixed set (nine, eight without transfers), the start and stop orders -- after the runtime, before the listener; stopped after the lease owners, since it holds their tickets -- the fatal map as `relay_lost`, and the witnesses. Finding 4: owners were created at activation, which is wrong in both directions, since dormant recovery acquires before it resumes and `attach --take-over` may acquire and release a session it never activates. An owner now starts on the first lease operation after successful existence validation and retires when the lease is free, no acquisition waits and the relay holds no ticket for that session. The population is capped at 512, ADR 0032's per-daemon ceiling (0032-technical:617), refusing with `control_capacity_reached`; it is independent of the activation ceiling, which counts a different set. --- ...tachment-residency-and-replay-technical.md | 2 +- ...controller-lease-and-takeover-technical.md | 72 ++++---- docs/plans/M5-technical.md | 157 +++++++++++++----- 3 files changed, 162 insertions(+), 69 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 0918f62c7..def976445 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -166,7 +166,7 @@ which no client requests and every client may receive: | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:listener_lost`. A lease owner's death is not among them: it closes one session's controller attachment with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:relay_lost`, `fatal:listener_lost`. A lease owner's death is not among them: it closes one session's controller attachment with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index ab7e0b7c3..712853144 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -68,49 +68,65 @@ is gone by any other route: the same takeover mechanics this ADR already defines for a lease that has been released. -The fresh epoch is what makes the lost set harmless: a command admitted under -the dead owner's epoch cannot be accepted after the new grant, and a mutation -already inside core settles or refuses exactly once under the serial ownership -core enforces, which no lease transition can affect. What is *not* claimed is -that the daemon knows whether such a mutation is still settling; it does not, -and a successor's work is ordered after it by core rather than by the daemon. +The fresh epoch alone is **not** what makes the lost set harmless, and an +earlier revision of this section said it was. It stops a *later* command from +the old tenure, which is a different thing from ordering: a successor's first +call could still reach a coordinator ahead of an older call that was already +on its way, because core orders what it receives rather than what is in +flight, and core never sees the writer epoch at all. + +**The daemon closes that window with one fixed process, the admission relay**, +added on the maintainer's decision of 2026-09-20. Every core call the daemon +makes is routed through it; it issues a ticket per call, naming the session; +it survives lease-owner death, being fixed rather than per-session; and **a +replacement owner's first grant for a session blocks until that session's +outstanding tickets have settled**. A ticket settles when the relay has +observed the call's outcome — its own task returning core's result, or that +task dying and the relay treating the call as settled-unknown, the fact +`commit_unknown` already carries. A connection disappearing settles nothing, +because the call it made is still running. + +So the ordering claim rests on the relay, and the session-scoped rule gives +the rest: the successor is granted a fresh epoch, the dead controller's +connection is closed with `control_owner_lost`, and no command from the old +tenure can be admitted afterwards. The cost is still stated honestly: the +daemon does not tell a new controller what an earlier mutation did, only that +nothing of it is still unaccounted for. An earlier draft had the daemon restart the owner and carry on with its sockets intact, and a 2026-09-20 revision made the failure fatal to the whole -daemon instance. Both are superseded by the decision above: the restart was -wrong because a restarted owner would claim an admission set it cannot know, -and daemon-fatal was more than the fault requires — one session's -collaboration state is not grounds to end every other session's. +daemon instance. Both are superseded: the restart was wrong because a +restarted owner would claim an admission set it cannot know, and daemon-fatal +was the smaller design the maintainer declined on 2026-09-20 — it ends every +other session's work for one session's fault, where the relay ends none of it. So a lease owner's failure is **session-scoped**, and the daemon's own structure supplies that without special-case code: each lease owner is `start_link`ed by the daemon's owner process, which traps exits, and its `{:EXIT, pid, reason}` clause maps the pid to the session it belonged to rather than to a daemon-wide class. Every other linked process the daemon -holds is still daemon-fatal; the lease owners are the one class with a -session-scoped rule, and the reason is the one above. There are no restarts to -configure and no strategy to get wrong: nothing is restarted, and the next -acquisition starts a new owner from nothing. - -**What this does not claim, stated because an earlier draft claimed it.** -Core never sees the writer epoch, as the lease record above sets out, and the -fences core does have protect against a stale *coordinator owner* rather than -a stale *controller* — which is the gap this ADR exists to fill. So the daemon -is the only thing keeping a successor's grant from racing an admission the -dead owner had already passed into core. What the session-scoped rule gives is -not that the race cannot exist; it is that the successor is granted a **fresh -epoch** and the dead controller's connection is closed, so no command from the -old tenure can be admitted afterwards, and the one admission already inside -core settles or refuses exactly once under core's own serial ownership. The -cost is the honest one: the daemon cannot tell a new controller whether an -earlier mutation is still settling, and does not pretend to. +holds is still daemon-fatal — the relay included, because a daemon without it +can no longer honour the ordering rule for any session. The lease owners are +the one class with a session-scoped rule. There are no restarts to configure +and no strategy to get wrong: nothing is restarted, and the next acquisition +starts a new owner from nothing. + +**When an owner exists at all.** One starts on the **first lease operation for +that session after its existence has been validated**, not at activation: a +dormant session is acquired *before* it is resumed, and `attach --take-over` +may acquire and release a session it never activates, so an activation-scoped +owner would not exist when the lease it serves does. One retires when the +lease is free, no acquisition is waiting, and the relay holds no outstanding +ticket for that session — all three, since any one alone would retire an owner +something still depends on. Retaining the in-flight set in a survivor was the alternative and was rejected: whichever process held it would then be the process whose failure loses it, so the window moves up one level rather than closing, and a daemon that cannot lose the set is a daemon that has made the set durable — a durable lease record by another name, which this decision rejects for its own -reasons. +reasons. The relay is not that: it holds no lease and no authority, only the +fact that a call it made has not yet been accounted for. Expiry and admission use the daemon's monotonic clock: a deadline is set only by a diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 2af97f368..d197ca69b 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -131,7 +131,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting an abort with `"cause" => "operator_shutdown"` for every active session **before** cancelling anything, driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -550,8 +550,9 @@ in full, and this list is derived from it rather than summarising it: input; - **while running**, one per linked component in the fixed set: `store_lost`, `store_capacity_exceeded`, `runtime_lost`, `transfers_lost`, - `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost` - and `listener_lost`. A lease owner's death is **not** in this list: it is + `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, + `relay_lost` and `listener_lost`. A lease owner's death is **not** in this + list: it is session-scoped, closes that session's controller with `control_owner_lost`, and the daemon keeps running; - **from the signal handler**, `owner_lost`, the one class no component @@ -797,7 +798,7 @@ So `apps/loopex_daemon` has one top-level process, `Loopex.Daemon.Owner`, a `GenServer` that traps exits and holds the links itself — the same pattern `RuntimeOwner` already uses, for the same reason. -**It links a fixed set of eight processes — seven without artifact +**It links a fixed set of nine processes — eight without artifact transfers — and a bounded, dynamic population of lease owners beside them.** Earlier drafts said four, then seven, each time having counted the components the daemon *thinks* about rather than the processes that actually exist. The @@ -812,21 +813,72 @@ fixed set is this: | 5 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | | 6 | The local executor | `start_edge(Local, …)` | no | | 7 | The runtime root | `start_edge(Loopex, …)` | no | -| 8 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | - -**Beside them, one lease owner per activated session**, which ADR 0033 -requires and the maintainer confirmed on 2026-09-20 in preference to one -process holding a record per session. That population is dynamic, and every -question a dynamic population raises is answered here rather than left to the +| 8 | The **admission relay** | The daemon's own; every core call the daemon makes is routed through it | no | +| 9 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | + +**The admission relay is new in this revision, and it exists because of a +window nothing else closes.** Core has no writer epoch — the lease is the +daemon's, and core never sees it — so when a lease owner dies with an +admission still inside core, the daemon loses the only record that the +admission exists. A replacement owner starting from nothing could grant a +successor, whose call could then reach a coordinator *before* the dead +controller's earlier call, which is still in flight. Neither ADR 0033's fresh +epoch nor core's serial ownership prevents that reordering: the fresh epoch +stops a *later* command from the old tenure, and core orders what it receives, +not what is still on the way. + +So one fixed, daemon-owned process holds what the lease owners cannot: + +- **Every admitted core call goes through the relay**, which performs it in a + monitored task it owns and issues a **ticket** naming the session, the + admission and the connection it came from. +- **A ticket settles when the relay has observed that call's outcome**, and + that is defined precisely because "the call is finished" is exactly the + ambiguity this closes: either the task returns core's result — any result, + including a refusal — or the task dies and the relay observes its `DOWN` + and treats the call as settled-unknown, which is the same fact + `commit_unknown` already carries in the journal. A connection disappearing + does **not** settle a ticket, because the call it made is still running + inside core; the ticket outlives the connection exactly as the call does. +- **The relay survives lease-owner death**, being fixed rather than + per-session, so the tickets survive with it. +- **A replacement owner's first grant for a session blocks until that + session's outstanding tickets have settled.** Not the daemon's admissions + generally — just that session's, which is why the ticket names one. + +That is the ordering claim ADR 0033's owner-loss section now rests on: a +successor's first call cannot be issued while an older call for the same +session is unaccounted for, so it cannot overtake one. The relay grants no +authority, holds no lease and makes no decision about who may control what; it +is a bookkeeping process on the path core calls already take. + +Its own failure is **daemon-fatal**, class `relay_lost`, and for the plainest +reason in the fatal map: a daemon whose relay is gone has lost the record of +every in-flight admission and can no longer honour the ordering rule for any +session. + +**Beside the fixed set, one lease owner per session**, which ADR 0033 requires +and the maintainer confirmed on 2026-09-20 in preference to one process +holding a record per session. That population is dynamic, and every question a +dynamic population raises is answered here rather than left to the implementation: | Question | Answer | | --- | --- | -| When does one start? | When the session is **activated in this daemon lifetime** — by `session.create` or by `session.resume` — started and linked by the daemon's owner process, like every other linked process | -| When does one stop? | At daemon exit, and in the stop sequence below. There is no deactivation in M5, so there is no retirement rule to invent | -| How many can exist? | At most **64**, because activation is one-way and the activation ceiling is 64 per daemon lifetime; the 65th activation refuses with `activation_ceiling_reached` before any owner could be started. The population bound is the ceiling, not a second number | +| When does one start? | On the **first lease operation for that session after successful existence validation** — an `session.acquire_control`, whether or not the session is active. Not at activation: an earlier revision said activation, which was wrong twice over, since dormant recovery acquires *before* it resumes and `loopex attach --take-over` may acquire and release a session it never activates | +| When does one retire? | When the lease is free — released or expired — **and** no acquisition is waiting **and** the relay holds no outstanding ticket for that session. All three, because any one of them alone would retire an owner whose state something still depends on | +| When does one stop unconditionally? | At daemon exit, in the stop sequence below | +| How many can exist at once? | One per session under lease or acquisition, capped at **512, ADR 0032's per-daemon ceiling** (`0032-…-technical.md:617`), reusing that number rather than inventing one; a lease operation that would exceed it refuses with `control_capacity_reached`. The population is **independent of the activation ceiling**, which counts something else entirely | | What does its death mean? | That **session's** collaboration state, not the daemon's — the one exception to fail-stop uniformity, below | +**Why not the activation ceiling.** An earlier revision bounded the population +at 64 by pointing at the activation ceiling. That was wrong in both +directions: a dormant session can have a lease owner without ever being +activated, and an activated session whose lease was released and whose tickets +have settled has no owner at all. The two populations are not the same set, +and tying one to the other's number would have made the bound wrong the first +time an operator took control of a dormant session. + **The registry and the custody process are first, and that is forced rather than chosen.** ADR 0034 makes the *host* own both, and for a daemon the host is the daemon. The runtime's model configuration carries the registry handle @@ -840,14 +892,17 @@ first, then the artifact placement and the executor's own edges, and the runtime last within that chain, because it depends on all of them. **The stop order is the reverse, with one deliberate exception.** Reversed: -listener, then **every lease owner**, then runtime, executor, workspace lease, -transfers, custody, registry — and then **the Store, last of all**, out of -reverse order. The lease owners are stopped **in sequence, not concurrently**, -and they share one grace between them rather than each taking one: each stop -is a process with no `terminate/2` and nothing to release, so the sequence -costs no measurable time, while a concurrent stop would need a second wait -rule and a way to attribute a timeout to one of sixty-four pids. Sequence is -the smaller mechanism for the same result. The +listener, then **every lease owner**, then the **relay**, then runtime, +executor, workspace lease, transfers, custody, registry — and then **the +Store, last of all**, out of reverse order. The lease owners go before the +relay because the relay is what holds their tickets, and stopping it first +would discard a ticket an owner could still be waiting on. They are stopped +**in sequence, not concurrently**, against the shared teardown deadline rather +than a budget each: every one of them is a process with no `terminate/2` and +nothing to release, so the sequence costs no measurable time, while a +concurrent stop would need a second wait rule and a way to attribute one +timeout among several hundred pids. Sequence is the smaller mechanism for the +same result. The Store is moved to the end because its `terminate/2` releases the writer marker, and the marker must outlive every operation the owner can end; custody and registry hold nothing durable, so stopping them before it costs @@ -869,7 +924,7 @@ runs no dialyzer, and `RuntimeOwner` itself already destructures the field, at not, and the real argument is the simpler one above. **There is no restart strategy, because there are no restarts.** Every one of -the fixed eight — seven without transfers — is `start_link`ed by the owner, +the fixed nine — eight without transfers — is `start_link`ed by the owner, as is each lease owner beside them, and the owner's `handle_info({:EXIT, pid, reason}, state)` clause is the failure rule. That clause is also the **reader** the fatal-class map needs — it matches the pid @@ -1704,7 +1759,7 @@ is fine — the Store was already stopped in step 6, and its `terminate/2` ran then. On the **fatal** path it was not fine, and an earlier draft left a real hole: for the classes where the Store is still alive (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, -`custody_lost`, `listener_lost`), nothing stopped the Store, so the halt +`custody_lost`, `relay_lost`, `listener_lost`), nothing stopped the Store, so the halt left the marker file behind on a daemon that had shut down deliberately. The fail-stop path above therefore stops the Store on every fatal class **except** the two store classes, where it is already gone. @@ -1739,6 +1794,7 @@ die without a name for it. | `registry_lost` | The credential routing registry exited | `fatal:registry_lost` | | `custody_lost` | The credential custody process exited | `fatal:custody_lost` | | `runtime_lost` | The runtime root exited | `fatal:runtime_lost` | +| `relay_lost` | The admission relay exited, taking every outstanding admission ticket with it | `fatal:relay_lost` | | `listener_lost` | The listener exited | `fatal:listener_lost` | **A lease owner's exit is the one that is not in this table**, and its absence @@ -1899,10 +1955,10 @@ the cause and try again without a recovery step. that component's class, to send that component's `fatal:` on the wire where a socket still exists, and — for the classes where the Store is still alive — **to leave no stale marker**, proved by the next daemon - opening that root with nothing to recover; seven of them in a daemon with - transfers enabled and six without — `runtime_lost`, `transfers_lost`, + opening that root with nothing to recover; eight of them in a daemon with + transfers enabled and seven without — `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, - `listener_lost`, beside the two store classes. The set is closed for the + `relay_lost`, `listener_lost`, beside the two store classes. The set is closed for the fixed set, so one of those dying without a class is a failing case rather than a silent `:shutdown`. A lease owner is deliberately not in this case: its own witness is below, and it asserts the daemon **keeps running**. @@ -1936,20 +1992,41 @@ the cause and try again without a recovery step. - **`owner_lost`.** The owner is killed while the daemon is otherwise healthy, then `SIGTERM` is delivered. The process halts with `fatal:owner_lost` on `stderr` rather than sitting with a handler and no owner. -- **A lease owner's death is session-scoped.** A session is activated, a - controller acquires it and an observer attaches; that session's lease owner - is killed. The case asserts the **daemon keeps running** — every other - session still serves, and the process does not exit — that the controller's - attachment closes with `control_owner_lost` while the observer stays - attached and keeps receiving events, that a following - `session.acquire_control` succeeds and returns an epoch **different** from - the dead owner's, and that the activation count is **unchanged**, because a - fresh owner is not a fresh activation. -- **The lease-owner population is bounded by the activation ceiling.** A - daemon driven to its 64th activation holds 64 owners; the 65th activation - refuses with `activation_ceiling_reached` and the case asserts **no - sixty-fifth owner was started**, so the population bound is the ceiling - rather than a second limit that could drift from it. +- **A lease owner's death is session-scoped, and the relay is what makes it + safe.** A session is activated, a controller acquires it and an observer + attaches; that session's lease owner is killed **while one of its admissions + is still inside core**. The case asserts the **daemon keeps running** — every + other session still serves, and the process does not exit — that the + controller's attachment closes with `control_owner_lost` while the observer + stays attached and keeps receiving events, and that a following + `session.acquire_control` returns an epoch **different** from the dead + owner's. + + It also asserts the ordering the relay exists for: the replacement owner's + grant **does not complete** while the old admission's ticket is + outstanding, and the successor's first call reaches core only after that + ticket settles. A variant lets the old admission finish first and asserts + the grant proceeds without an observable wait, so the case cannot pass by + blocking unconditionally. A late command from the dead controller's tenure + is refused on the epoch check, as it would be for any released lease. +- **The relay's own death is daemon-fatal.** Killing it exits `relay_lost` + with that `fatal:` on the wire and leaves no stale marker, like every + other fixed component. +- **Owners exist for dormant sessions, and the population is not the + activation count.** A dormant session is acquired for recovery without being + resumed: the case asserts an owner exists for it, that the **activation + count is unchanged**, and that after `session.release_control` — with no + acquisition waiting and no ticket outstanding — the owner **retires**, + proved by the daemon reporting one fewer live owner while the session stays + reachable. A second case runs `loopex attach --take-over` against a dormant + session, which acquires, is refused at attach, releases and exits, and + asserts the owner that existed for the acquisition is gone afterwards and no + activation was spent. +- **The concurrent-owner cap is the attachment ceiling, not a new number.** A + daemon driven to 512 concurrent lease owners refuses the next lease + operation with `control_capacity_reached`, and the case asserts no + five-hundred-and-thirteenth owner was started and that releasing one lease + lets the next acquisition through. - **The credential processes are fatal like every other component.** The registry and the custody process are each killed in their own case; the daemon exits `registry_lost` and `custody_lost` respectively, sends that From b31ecd45bfcf43f40133cd53694a452e770e4c65 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:43:02 -0700 Subject: [PATCH 078/585] plan(M5): let core's create result say fresh or historical Finding 5. All three branches at control.ex:901-907 answer `{:ok, session_id}` -- already active, seen before, or fresh -- so the daemon can neither charge a fresh create against the activation ceiling nor repair a directory entry for a replayed one without activating. Core already computes what is missing: `create_command_absent?/2` binds `fresh?` at :895 and the branch discards it four lines later. Core's fifth M5 change is to stop discarding it: the **runtime-side** create result carries `disposition: :fresh | :historical` and `residency: :active | :dormant`. The released public protocol result is unchanged -- no wire schema, digest or vector moves -- and a host that ignores the fields behaves as today. Guessing from side effects is recorded as rejected, being a race by construction. The brief asked whether a fresh create can be refused before core starts the coordinator. It cannot from the daemon: `start_owner` runs inside the same call that would report freshness, and no API stops it afterwards. So the plan states the blunt rule instead of implying a neat one -- at the ceiling every `session.create` is refused, replayed or fresh -- and states its cost: recovery by `command_id` is unavailable until the restart the ceiling already prescribes. Below the ceiling, which is where recovery actually happens, the disposition does its work. Scope, ownership table, minimalism budget and the Concept's count follow (core's changes are five), with witnesses for a replayed create repairing without charging, a fresh create charging, an already-active replay repairing nothing, and the ceiling refusing both kinds. --- docs/plans/M5-technical.md | 73 ++++++++++++++++++++++++++++++++++++-- docs/plans/M5.md | 37 ++++++++++--------- 2 files changed, 92 insertions(+), 18 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d197ca69b..8472788a8 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -37,7 +37,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace`'s excluded-MFA list, which keeps a named function out of a trace session before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace`'s excluded-MFA list, which keeps a named function out of a trace session before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create result's `disposition` and `residency` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The local adapter, unchanged in behaviour and gaining exactly one read-only call — whether the marker file still holds this daemon's marker, which the socket-unlink precondition needs and `WriterLock` does not expose (`writer_lock.ex:92-105`) — its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -618,6 +618,55 @@ ends or the operator re-runs with `--take-over`. It does not race the deadline, because a mutation sent after the term elapsed will be refused anyway and a client that keeps trying only obscures when control was lost. + +**Core's create result tells the daemon which create it was, and that is core's +fifth M5 change.** The daemon has two duties that pull against each other: +charge a *fresh* create against the activation ceiling, because a fresh create +starts a coordinator; and repair a directory entry for a session whose create +is *replayed*, without activating anything. Today it cannot do either +reliably, because core answers both the same way. All three branches at +`control.ex:901-907` reply `{:ok, session_id}` — the session is already +active; the command was seen before, so no owner is started; or it is fresh +and an owner starts — and the value carries no trace of which. + +Core already computes what is missing: `create_command_absent?/2` binds +`fresh?` at `:895`, four lines above the branch that discards it. So the fifth +change is to stop discarding it. **Core's runtime-side create result — the +Elixir function the daemon calls, not the released public protocol result — +carries two plain fields beside the session ID:** + +| Field | Values | What the daemon does with it | +| --- | --- | --- | +| `disposition` | `:fresh` \| `:historical` | Charge an activation for `:fresh`; charge nothing for `:historical` | +| `residency` | `:active` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | + +**The public protocol result is unchanged.** Generation 1 and generation 2 +return what they return today; this is an in-VM API detail between core and +any host, and no wire schema, digest or vector moves. A host that ignores the +fields behaves exactly as it does now. + +**What happens at the ceiling, stated because the honest answer is not the +neat one.** The brief for this change asked whether a fresh create can be +refused *before* core starts the coordinator. It cannot, from the daemon: the +coordinator is started inside the same call that would tell the daemon the +create was fresh (`start_owner` in the `true` branch at `:908`), so by the +time the daemon could act, the coordinator exists and the daemon has no API to +stop it. So the rule at the ceiling is the blunt one: **at the activation +ceiling the daemon refuses every `session.create`, replayed or fresh**, with +`activation_ceiling_reached` and the restart remedy the ceiling already names. + +That costs something and the plan says what: recovery by `command_id` is +unavailable at the ceiling until the daemon is restarted. It is the right +trade because the alternative permits a sixty-fifth coordinator — breaking the +one-way activation bound this milestone proves — to save a recovery path whose +remedy is the restart the ceiling already prescribes. Below the ceiling, which +is where recovery is actually performed, `disposition` does its work. + +Guessing the disposition from side effects — comparing activation counts +before and after, or watching for a coordinator to appear — was the rejected +alternative: it is a race by construction, since another connection may create +a session between the two observations. + **A dormant session refuses `attach` in either role.** `loopex attach` against a session this daemon has not activated is refused with `session_dormant`, naming the remedy: `loopex resume --daemon`. Attaching does not activate. Activation is a @@ -2065,6 +2114,21 @@ the cause and try again without a recovery step. would have turned into an immediate `:timeout_value` exit. All of them run at both toolchain pairs, because both timeout results were observed at both. +- **A replayed create repairs, a fresh create charges.** Two cases on the + create disposition. A session whose directory entry was never written is + recovered by replaying `session.create` with the original `command_id`: the + case asserts core answers `disposition: :historical` with + `residency: :dormant`, that **no activation is charged**, that no + coordinator starts, and that the daemon repairs the directory entry and + index row from that answer alone. A genuinely fresh create asserts + `disposition: :fresh`, one activation charged, and a live coordinator. A + third asserts the pair for a session that is already active — + `:historical` with `residency: :active` — and that the daemon repairs + nothing, because an activated session already recorded both. +- **At the ceiling, every create is refused.** A daemon at its 64th activation + refuses `session.create` with `activation_ceiling_reached` **whether the + create is fresh or a replay**, and the case asserts the replay is refused + too — the stated cost — and that no coordinator was started by the attempt. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting @@ -2170,7 +2234,12 @@ has to happen where the patterns are installed; redaction at the sink is too late, the raw call having already reached the tracer. It is the smallest form of the requirement: a list of `{module, function, arity}` identities cleared after the module pattern, using `:trace.function/4` exactly as it already -does. **One bounded `quiesce/2`** — which unifies nothing today and says so: +does. **Two plain fields on the runtime-side create result** — which unify +nothing and add no wire surface: they exist because core computes `fresh?` at +`control.ex:895` and then throws it away four lines later, leaving every +caller unable to tell a fresh create from a replay. Direct code cannot supply +them, because the only alternative is inferring the answer from side effects, +which is a race. **One bounded `quiesce/2`** — which unifies nothing today and says so: its only caller is the daemon's orderly stop, and the app-server host does not drain by hand, because `LoopexComposition.with_runtime/2` brackets a runtime that lives and dies with one client's stdin and has nothing to drain diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 5f01672a6..4c165dc4b 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -38,12 +38,15 @@ channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above -the core. Core gains exactly four narrow things: support for several independent +the core. Core gains exactly five narrow things: support for several independent attachments to one session; one read-only query that answers whether a session -ID exists durably in the root; an excluded-MFA list in `Loopex.Trace`, which -keeps a named function out of a trace session before any message is delivered -and which accepted ADR 0030 already requires; and `quiesce/2`, the bounded -settle an orderly stop drains through. It gains no lease, no transport, no +ID exists durably in the root; trace exclusion, which keeps credential-bearing +work out of a trace session before any message is delivered and which accepted +ADR 0030 already requires; `quiesce/2`, the bounded settle an orderly stop +drains through; and two plain fields on the **runtime-side** create result, +telling a host whether the create it just made was fresh or a replay and +whether the session is active or dormant — the public protocol result is +unchanged. It gains no lease, no transport, no second loop and no new durable command. @@ -70,7 +73,7 @@ independent attachments to one session through its existing race-free attach barrier and dispatcher, and answers one read-only question about it: given a session ID, does this root hold that session durably. -That query is the second of core's four M5 changes, and it exists because +That query is the second of core's five M5 changes, and it exists because the alternative was worse. The daemon has to validate durable existence before it grants a lease, and before it records a session its index does not hold, and it may not read Store internals to do it. Learning existence by *calling* @@ -96,8 +99,9 @@ serves generation `loopex.experimental/2` only, which adds `session.list`, `daemon.status`, the two control methods and the writer-epoch field, and lifts the one-attachment-per-process rule to residency limits. It adds no durable method: core owns durable session truth and its M5 changes are concurrent -attachment, one read-only existence query, `Loopex.Trace`'s excluded-MFA list -and the bounded `quiesce/2`, none of which is a durable command, so a daemon method that ended a session durably would have to add +attachment, one read-only existence query, trace exclusion, the bounded +`quiesce/2` and two fields on the runtime-side create result, none of which is +a durable command, so a daemon method that ended a session durably would have to add one, which M5 does not do. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by @@ -112,9 +116,9 @@ effect dispatched, an interaction awaiting an answer, a recovery running, an unresolved `commit_unknown` or an admission executing inside core, so "idle" is not "quiescent" and stopping on idleness would destroy exactly what Outcome 1 exists to prove. And there is nothing to stop it with: core owns -coordinator lifetime, and M5's four core changes — concurrent attachment, a -read-only existence query, `Loopex.Trace`'s excluded-MFA list and the bounded -`quiesce/2` — none of them stops a coordinator. +coordinator lifetime, and M5's five core changes — concurrent attachment, a +read-only existence query, trace exclusion, the bounded `quiesce/2` and the +create result's two new fields — none of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation @@ -129,7 +133,7 @@ its loss is core's to supervise; it reaches a client as core's existing refusal on the next command for that session, which the daemon forwards unchanged. Making the daemon track it would need a core notification or a monitorable handle — a **further** core change M5 does not make, beyond the -four it does. Lifting it needs a core operation that can tell quiescent from idle, +five it does. Lifting it needs a core operation that can tell quiescent from idle, which is its own decision and not M5's. `session.list` is a daemon convenience, not an enumeration of durable truth. @@ -455,9 +459,10 @@ Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan No controller lease, transport, socket or collaboration rule inside core. Its only M5 changes are independent concurrent attachment support, one read-only -session-existence query, the excluded-MFA list in `Loopex.Trace` that accepted -ADR 0030 already requires, and the bounded `quiesce/2` an orderly stop drains -through — none of which is a durable command. No daemon-grade +session-existence query, the trace exclusion that accepted ADR 0030 already +requires, the bounded `quiesce/2` an orderly stop drains through, and two +plain fields on the runtime-side create result — none of which is a durable +command, and none of which changes a wire schema. No daemon-grade store adapter, journal format version, migration, backup tooling, compaction, retention cutoff or NIF dependency; no daemon-served generation 1; no durable lease record; no exactly-once delivery promise beyond the founding @@ -667,7 +672,7 @@ sixth runs last because it describes what the others built. Workstream 1 lands in two parts — the core change first, its daemon-side residency after the lease — and the companion's rejoin order says where each part goes. -1. **Core's four changes, and the residency above them.** The narrow core +1. **Core's five changes, and the residency above them.** The narrow core change that lets distinct attachments to one session coexist without implicit replacement; the read-only session-existence query the daemon's acquire and activation paths need; the excluded-MFA list in `Loopex.Trace` From 3664f5fd733e00d7177bd9ae1e04af27ea75ded1 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:43:44 -0700 Subject: [PATCH 079/585] plan(M5): make startup interruptible and monitor the owner Finding 6. Startup runs synchronously inside the owner, which is not reading its mailbox while it runs: a `SIGTERM` turned into a message by `:erl_signal_server`, and a linked component's EXIT, both wait. A daemon could therefore take the marker, bind the socket and print readiness after a stop it had already been told about, or on top of a component that had already died, and only then read either. Two narrow rules. Before every acquisition -- the marker, the composition call, each returned edge, the bind, the readiness line -- the owner drains its mailbox for a stop or an EXIT and checks that everything it has already started is alive, aborting into the reverse cleanup that already exists. And the escript command process that called `start_link` monitors the owner and halts non-zero with `owner_lost` on its DOWN, which is where that class is now observed: the previous design surfaced it only when a later signal found no owner, leaving a crashed daemon holding a marker and a bound socket until somebody thought to send one. The handler keeps its own check as the second route, for a signal arriving between the death and the monitor's DOWN. Witnesses: a mid-startup `SIGTERM` at two steps and a Store killed after composition, each asserting no readiness line, no marker and no socket left; and `owner_lost` observed with no signal sent at all. --- docs/plans/M5-technical.md | 69 ++++++++++++++++++++++++++++++++------ 1 file changed, 59 insertions(+), 10 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8472788a8..83ff8e1db 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -806,6 +806,42 @@ when a session is activated, which cannot happen before a client connects. A failure at any step exits non-zero with that step's reason class, after the reverse cleanup below, and touches nothing after it. + +**Startup is interruptible, and the owner is monitored — both because a +synchronous sequence inside one process is not, by itself, process-safe.** +The steps above run in the owner, and while they run the owner is not reading +its mailbox: a `SIGTERM` handled by `:erl_signal_server` becomes a message +that waits, and a linked component's `{:EXIT, …}` waits beside it. Left +alone, that means a daemon can take the marker, bind the socket and print +readiness *after* a stop it has already been told about, or after a component +it depends on has already died — and then read both and shut down, having +announced itself ready in between. + +Two rules, both narrow: + +- **Before every acquisition, the owner drains and checks.** Before taking the + marker, before calling the composition function, before each edge the + function returns to it, before binding the socket and before printing the + readiness line, the owner reads whatever is in its mailbox for a stop + message or an `{:EXIT, …}`, and checks that every component it has already + started is alive. Any of those aborts the start into the reverse cleanup + above, which unwinds exactly what exists. Nothing is acquired after a stop + is known, and nothing is announced on top of a component that is gone. +- **The process that started the owner monitors it.** The escript command + process — the one that called `start_link` — holds a monitor and, on `DOWN`, + halts non-zero with `owner_lost` on `stderr` immediately. That is where + `owner_lost` is actually observed: an earlier revision had it arriving only + when a *later signal* found no owner, which leaves a daemon whose owner has + crashed sitting with a bound socket, a held marker and nobody running it + until somebody happens to send `SIGTERM`. The signal handler's own backstop + stays as the second route, for the case where the owner dies in the instant + between the signal and the handler's send. + +Neither rule needs a new process or a supervisor: the drain is a receive with +a zero timeout and a liveness check, and the monitor is the command process +doing what it is already there to do — wait for the daemon to end and give the +operating system an exit status. + **One cost of matching the seam is stated rather than hidden.** The directory and index read is step 5, after the composition function has already taken the workspace lease and started the executor, so a root whose directory exceeds @@ -1302,13 +1338,14 @@ a signal arriving before startup completes ends a daemon that holds nothing. state and makes no decision; the owner's own code runs the sequence, from its own process, exactly as it does for every other path. -**The owner-loss backstop.** If the owner is not alive when the signal -arrives — it crashed, or the signal raced its own start — there is nobody to -run the sequence and nothing to wait for. The handler halts with -`fatal:owner_lost` on `stderr` rather than returning and leaving the process -running with a handler and no owner. That class is in the exit list above and -in the fatal-class map's note, and it is the one class no linked component -produces. +**The owner-loss backstop is the second route, not the first.** `owner_lost` +is normally observed by the **command process that started the owner and +monitors it**, which halts non-zero the moment its `DOWN` arrives — see the +startup rules above. The signal handler keeps its own version of the check for +the one case that monitor cannot cover: a signal arriving in the instant +between the owner's death and the monitor's `DOWN` being handled. In both +routes the class is `owner_lost` on `stderr`, and it is the one class no +linked component produces. **Three clocks, and no component invents a fourth.** An earlier revision gave every component "the composed cleanup grace" and gave the Store a floor over @@ -2038,9 +2075,21 @@ the cause and try again without a recovery step. delivered before startup completes ends a daemon that holds no marker and has bound no socket, proved by a following daemon starting with nothing to recover. -- **`owner_lost`.** The owner is killed while the daemon is otherwise healthy, - then `SIGTERM` is delivered. The process halts with `fatal:owner_lost` on - `stderr` rather than sitting with a handler and no owner. +- **`owner_lost`, by the monitor and not by a later signal.** The owner is + killed while the daemon is otherwise healthy and **nothing else happens**: + no signal is sent. The case asserts the process halts non-zero with + `fatal:owner_lost` on `stderr` within a bounded time of the kill, which is + the command process's monitor doing it. A second case kills the owner and + *then* sends `SIGTERM`, asserting the same class by whichever route wins, so + the two cannot both fail silently. +- **Startup is interruptible.** A `SIGTERM` is delivered mid-startup, at the + step before the marker is taken and again at the step before the socket is + bound. Each case asserts **no readiness line is printed**, that no marker is + held and no socket file exists afterwards, and that a following daemon + starts cleanly with nothing to recover. A third kills the Store immediately + after the composition call returns and asserts the start aborts into reverse + cleanup rather than binding a socket and announcing readiness on top of a + dead component. - **A lease owner's death is session-scoped, and the relay is what makes it safe.** A session is activated, a controller acquires it and an observer attaches; that session's lease owner is killed **while one of its admissions From 6f21e518b20ff51989f06342921f4a9fe8645769 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:47:46 -0700 Subject: [PATCH 080/585] adr(0034): exclude the credential-bearing process, narrow the token Finding 10, reproduced here before anything was written. `ProviderCodec. send/3` hands the encoded credential frame to `:gen_tcp.send/2`, and a trace session naming `:gen_tcp` shows it: `{:trace, #PID<...>, :call, {:gen_tcp, :send, [#Port<...>, "FRAMECANARY-SECRET-42"]}}`. No list of excluded module-function-arity identities can fix that, because an excluded function's *callees* are outside the list and always will be. The MFA list and the module-wide `ProviderCodec` exclusion are withdrawn. Core change 3 is now `Loopex.Trace.exclude_self/1`: the sender calls it before it resolves anything and it returns only once that process is excluded from every live session and recorded for every future one. Probed at both pairs: a process flagged by `:set_on_spawn` inheritance calls `:trace.process(session, self(), false, [:all])`, the call returns 1, and its subsequent `:gen_tcp.send/2` with a canary produces no trace message while a non-excluded control call produces one. The same probe shows a later enable re-tracing the pid, so the stickiness cannot come from the VM: `Loopex.Trace` holds an excluded-pid set in its own state, skips those pids when a session starts, and exposes no configuration that can clear it. Ordering is acknowledged rather than hoped for, the tracer being one serializing process. The sender reaches it through a tracer reference composition puts in the model `options`, the same class as the executor's `reference:`; where none is composed the call answers `:trace_unavailable` and the sender proceeds, since a tracer that is not running cannot trace. The keyed shape stays, labelled as defence in depth and not as the mechanism. The decisive witness names `:gen_tcp` on purpose. Finding 9: ADR 0034 is narrowed to one token per composed model configuration -- there is no token collection, no provider-selection seam and no per-call model options -- and the per-provider generalisation becomes a stated future amendment, which ADR 0035 now agrees with from its side instead of claiming none is needed. The inventory's custody row follows. ADR 0034's host-custody test paths (`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`) now appear in Outcome 6 and the closure matrix, which named only adapter trees. Material 4: a registry that does not answer is the guardian's `:timeout`, not `:unavailable`; a registry that is gone fails immediately and is `:unavailable`. Material 5: the token is composition-bound and its *resolution* is per invocation, in ADR 0034's decision sentence and in Outcome 6. --- ...andoff-over-bootstrap-channel-technical.md | 243 ++++++++++-------- ...edential-handoff-over-bootstrap-channel.md | 6 +- ...ision-models-as-policy-inputs-technical.md | 36 +-- ...-typed-decision-models-as-policy-inputs.md | 17 +- docs/plans/M5-technical.md | 26 +- docs/plans/M5.md | 15 +- 6 files changed, 196 insertions(+), 147 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 4a3c2ce57..b096c2162 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -93,10 +93,22 @@ credential bytes never arrive as `%CredentialToken{}`, so the refusal is a pattern match rather than a judgement, and a credential accidentally passed as a token is refused at composition instead of being routed. -**One token per configured provider, bound at composition.** A runtime that -names two providers carries two tokens, each with its own registry row and its -own custody process; it does not mint one per call. That is what makes ADR -0035's second credential a second row rather than a widened value. +**One token per composed model configuration, bound at composition.** That is +the whole of what this decision fixes, and it is narrower than an earlier +revision claimed. A runtime composes **one** model configuration, its +`options` carry **one** token and **one** registry handle, and one custody +process holds the bytes behind it. There is no token collection, no +provider-selection seam and no per-call model `options` — `complete/3` takes +the composition-time configuration unchanged — so a design for two providers +would be describing a seam that does not exist. + +**The per-provider generalisation is a stated future amendment**, not part of +this decision. When a second provider credential arrives, the registry's +routing-only contents make it a second row and a second token rather than a +widened value; that is the shape the generalisation will take, and it needs +its own amendment to this ADR because it needs the seam that would select +between them. ADR 0035, which is the decision that would bring one, says the +same thing from its side and is Proposed and deferred. **Every later use of "per-invocation" in this pair qualifies the resolution.** On each call the sender routes the token through the handle, receives the @@ -158,7 +170,7 @@ separate: already exists for exactly this: something the host decides once, per runtime, that every invocation needs. Composition puts the registry reference there, under its own key, beside the token — which composition - also puts there, once, per configured provider. An earlier sentence said + also puts there, once, for the one model configuration this runtime has. An earlier sentence said the caller supplies the token "per invocation"; that contradicted this pair's own binding rule and is corrected: what happens per invocation is the **resolution**, never the supply. @@ -190,9 +202,19 @@ separate: - **The lookup is one operation, and it is the host's.** `route(handle, token) -> {:ok, custody_ref} | {:error, :unavailable}`, a call to the registry process. It returns *where to ask*, never bytes; - `:unavailable` covers a token with no row, a registry that is gone, and a - registry that does not answer — from the sender's side those are one fact - and none is recoverable by asking again. + `:unavailable` covers a token with no row and a registry that is gone — + from the sender's side those are one fact, and neither is recoverable by + asking again. + + **A registry that is merely slow is not one of them**, and an earlier + revision blurred the two by putting "does not answer" in this list. Silence + is the guardian's business: the sender's lookup has no deadline of its own, + the **invocation deadline** bounds the whole resolution, and a registry that + has not answered when it expires produces the guardian's `:timeout` with the + sender killed — which the closed reason set already distinguishes from every + refusal, precisely so an operator can tell a refusal from a silence. A + registry that is *gone* answers immediately, because the call fails rather + than waits, and that is `:unavailable`. - **Its lifetime is the host supervisor's, and a restart invalidates the handle.** The host starts the registry under its own supervisor when it composes the runtime. If the registry dies, the handle a composed runtime @@ -243,104 +265,121 @@ boundary, not an absolute: already protects that process — the sender installs its own group-leader sink so no IO request can carry anything out of it, it is unregistered, and it reports only an atom or a `{:error, atom}` pair to the guardian. -- **What keeps credential bytes out of a trace: exclusion before delivery, - which M5 implements because ADR 0030 already requires it.** That accepted - companion says the key-bearing call "is excluded by match specification" - (`0030-…-technical.md:27`). An earlier revision of this pair found no such - mechanism in `Loopex.Trace` and substituted namespace omission plus - sink-time redaction. That substitution is withdrawn: redaction happens in - `Entry.render/2`, at the sink, while tracing delivers the **raw** call tuple - to the tracer process first (`trace.ex:331`, `:152`, `:219`). A host that - names the adapter module would therefore create another message carrying the - credential — one more place the bytes exist — which is precisely what the - "only permitted transfer" contract forbids. Redaction cannot satisfy a - pre-delivery requirement. - - **So M5 implements the requirement.** `Loopex.Trace` gains an excluded-MFA - list applied when a session's patterns are installed: the module pattern - first, then each excluded `{module, function, arity}` cleared. The mechanism - is the one `:trace.function/4` already supports, and it was verified by - probe at **both** toolchain pairs before being written here: +- **What keeps credential bytes out of a trace: the credential-bearing + *process* is excluded before it resolves anything.** ADR 0030 requires the + key-bearing call to be excluded by match specification *before* delivery + (`0030-…-technical.md:27`), and this pair has now twice failed to satisfy + it. The first attempt was sink-time redaction, which is too late because + tracing delivers the raw call tuple to the tracer first (`trace.ex:331`, + `:152`, `:219`). The second was an excluded-MFA list naming this adapter's + own functions — and that fails for a reason worth recording, because it is + the reason no function-level list can work here: + + **A function that carries the credential calls functions it does not own.** + `ProviderCodec.send/3` hands the encoded credential frame to + `:gen_tcp.send/2`. A trace session that names `:gen_tcp` explicitly sees the + frame, whatever this adapter's modules are excluded. Reproduced, with a + canary standing in for the credential: ``` - :trace.function(session, {Probe, :_, :_}, true, [:local]) # => 6 - :trace.function(session, {Probe, :secret, 1}, false, [:local]) # => 1 - # tracer then receives, for a process calling both: - # {:trace, #PID<…>, :call, {Probe, :visible, ~c"\n"}} - # and nothing at all for Probe.secret/1 + :trace.function(session, {:gen_tcp, :send, 2}, true, [:local]) + # tracer receives: + {:trace, #PID<0.97.0>, :call, {:gen_tcp, :send, [#Port<0.4>, "FRAMECANARY-SECRET-42"]}} ``` - A later, more specific pattern replaces the module-wide one for that MFA, so - the excluded function is not traced at all — no raw message, nothing for the - tracer to hold, nothing for the sink to redact. This is core's **third** M5 - change, recorded as such in the plan's ownership table and minimalism - budget. - - **The excluded inventory is complete, and completeness is why it is drawn - this way.** Credential bytes and the token reach exactly two places in the - parent: - - | Excluded | Why | - | --- | --- | - | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | The registry handle and the token | - | `Loopex.LLM.ReqLLM.ProviderBridge.receive_custody_reply/2` | The resolved credential | - | `Loopex.LLM.ReqLLM.ProviderBridge.write_credential_frame/2` | The resolved credential | - | **`Loopex.LLM.ReqLLM.ProviderCodec`, every function** | The credential frame is encoded by the same generic encoder as every other frame: `send/3` calls `encode/2` (`provider_codec.ex:127-131`, `:87-92`), which calls `valid_payload?/2` and `encode_value/4`, which recurse through `encode_members/5`, `encode_pairs/4` and `encode_key/2,3`. `[:local]` tracing covers private calls, so every one of those frames carries the bytes | - - The codec is excluded as a **module** rather than as a list of private - MFAs, and the rejected option is recorded: an MFA list of private helpers - would be a list that rots silently, since a refactor inside the codec could - add a private function carrying the payload and no test would notice. The - cost is stated too — codec calls are not traceable for any frame — and it is - small, because the encode path is shared, so excluding only the - credential-carrying calls was never possible: the same functions encode - every frame. - - **The keyed shape stays, as defence in depth rather than as the mechanism.** - The three bridge functions carry credential bytes only as a value under a - credential-named key — `receive_custody_reply/2` returns - `{:ok, %{credential: bytes}}` and never `{:ok, bytes}`; - `write_credential_frame/2` takes that keyed map, not a bare binary — so if - an exclusion were ever lost, `@credential_pattern` still placeholders the - value at any size. That matters because the size rule alone does not: an - earlier draft of this pair concluded a credential is "redacted by size even - as a bare positional argument", and running `Entry.render/2` says otherwise. - - | Credential size | Bare arg `[cred]` | Tuple `{:ok, cred}` | Keyed `%{credential: cred}` | - | --- | --- | --- | --- | - | 1 byte | **leaks** | **leaks** | placeholdered | - | 40 bytes | **leaks** | **leaks** | placeholdered | - | 51 bytes | **leaks** | **leaks** | placeholdered | - | 64 bytes | **leaks** | **leaks** | placeholdered | - | 65 bytes | placeholdered | placeholdered | placeholdered | - - ADR 0019 admits a credential of 1 to 65,536 bytes, so the leaking range is - real. The size reading is withdrawn with those numbers recorded, and the - shape is contract. - - **ADR 0030 is not edited.** Its prose is honoured once this change lands, - and not before; until then the requirement is real and the implementation is - missing, which is the finding an earlier revision recorded and this one - closes rather than reinterprets. The alternative — amending ADR 0030 down to - what the code did — is rejected: it would weaken an accepted security - contract to match an omission. - - **The proof is three cases.** Under the **default** configuration, a real - trace session at the `arguments` level over a real invocation produces no - entry naming any excluded function, no raw trace message for them, and no - credential bytes or token anywhere in the captured entries — the adapter is - not in the default traced set, because `modules/1` expands the `:loopex` and - `:loopex_protocol` namespaces through `:application.get_key(application, - :modules)` and `Loopex.LLM.ReqLLM.ProviderBridge` is in - `loopex_llm_reqllm`. Under a configuration that **explicitly names** - `ProviderBridge` and `ProviderCodec`, the tracer is asserted to receive **no - raw trace message** for any excluded MFA — the pre-delivery property itself, - read from the tracer rather than from the sink — while a non-excluded - function of the same module is asserted to produce one, so the case cannot - pass by tracing nothing. A third case calls each of the three bridge - functions with a **one-byte** credential and asserts no captured entry - contains that byte, which is the keyed-shape tier and would fail under a - size-based rule. + Excluding `:gen_tcp` would not close it either: the next callee down, or a + future one, is outside the list again. An enumeration of callees is not a + contract anyone can keep. + + **So the exclusion is by process, and it is mandatory.** The sender — the + short-lived process that resolves the credential and writes the frame — + calls a core API **before it resolves anything**: + + ```elixir + Loopex.Trace.exclude_self(tracer) # returns only once the exclusion is installed + ``` + + It returns `:ok` once this process is excluded from **every** live trace + session and recorded as excluded for every future one. Only then does the + sender route the token, receive the credential and write the frame. Nothing + the sender does after that point can appear in a trace, whatever modules or + functions a host names — including `:gen_tcp`, including modules nobody has + thought of. + + **The mechanism, probed at both toolchain pairs before it was written + down.** A process flagged by inheritance (`:set_on_spawn` from a traced + parent) calls `:trace.process(session, self(), false, [:all])`; the call + returns `1`, the flags are gone, and its subsequent `:gen_tcp.send/2` with + the canary produces **no trace message at all**, while a non-excluded + control process's identical call produces one. That is pre-delivery in the + strictest sense: there is no message for a sink to redact, and ADR 0030's + rule is satisfied by a stronger mechanism than the one its prose names. + + **The VM does not make it sticky, so core does.** The same probe shows a + later `:trace.process(session, pid, true, …)` re-enabling the process, so + the exclusion cannot be left to the BEAM. `Loopex.Trace` is a per-runtime + `GenServer` holding the session and its configuration; it gains an + **excluded-pid set** in that state, and three rules: + + 1. `exclude_self/1` adds the caller to the set and, if a session is live, + installs `false` for it before replying; + 2. when a session starts, every pid in the set is skipped where + `runtime_processes/1` would otherwise be flagged — the same place + `excluded?/3` already excludes the tracer and the dispatcher by role + (`trace.ex:411`); + 3. nothing in a trace **configuration** can clear the set. It is not part of + `modules`, `level`, `limits` or `sink`; a host can name any module it + likes and cannot name a process back in. + + **The ordering is acknowledged, not hoped for.** The tracer is one process + and serializes its mailbox, so by the time `exclude_self/1` returns, either + the session started first and the exclusion was installed over it, or the + exclusion was recorded first and the session skipped that pid. There is no + interleaving in which the sender resolves a credential while traced. + + **Reaching the tracer.** The sender has no runtime handle of its own, so + composition puts a **tracer reference in the model `options`**, beside the + registry handle and the credential token — the same class of composition + data as the executor's `reference:`, which `LoopexComposition` already fills + with a live pid. Where no tracer is composed, `exclude_self/1` answers + `{:error, :trace_unavailable}` and the sender **proceeds**: a tracer that is + not running has no session and cannot trace, and making credential delivery + depend on an observability process would be the wrong dependency entirely. + + **What is dropped.** The excluded-MFA list and the module-wide exclusion of + `ProviderCodec` are withdrawn — they cost this adapter's tracing and never + bought the property, for the callee reason above. Core change 3 is now the + process exclusion alone, which is smaller and total. + + **What is kept as defence in depth**, explicitly labelled so nobody mistakes + it for the mechanism: the **keyed shape**. The three bridge functions carry + credential bytes only as a value under a credential-named key — + `receive_custody_reply/2` returns `{:ok, %{credential: bytes}}` and never + `{:ok, bytes}`; `write_credential_frame/2` takes that keyed map — so a + credential that somehow reached `Entry.render/2` would be placeholdered at + any size. It protects nothing about callees, and it is not what satisfies + ADR 0030. + + **The proof is three cases, and the first one is the one that would have + caught the old design.** A trace session is configured to name + **`:gen_tcp`** explicitly, alongside `ProviderBridge` and `ProviderCodec`, + and a real invocation runs with a **one-byte canary** as the credential. The + case asserts the tracer receives **no raw trace message from the sender + process at all** — not for `:gen_tcp.send/2`, not for any function — while a + non-excluded control process performing the same `:gen_tcp.send/2` in the + same session **does** produce one, so the case cannot pass by tracing + nothing. The canary appears nowhere in any captured message or entry. + + The second is the default configuration: no module naming, and no entry, no + raw message and no credential byte anywhere — the adapter is in no namespace + wildcard, because `modules/1` expands `:loopex` and `:loopex_protocol` + through `:application.get_key(application, :modules)` and + `Loopex.LLM.ReqLLM.ProviderBridge` lives in `loopex_llm_reqllm`. + + The third is the ordering: `exclude_self/1` is asserted to return **before** + the token is routed, and a session started concurrently with it is asserted + to produce no message from the sender either way round, which is the + serialization claim made checkable rather than asserted. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 81bff143a..e7d64dd39 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -38,9 +38,9 @@ measured the result at M4 closure — that application is the critical path of the fast check, 96% of its time sits in those twelve modules, and no further test change shortens the check while the slot is shared. -**Decide that the credential is a per-invocation input, named by an opaque -token and resolved only inside the process that writes it to the child's -private channel.** The host gives the adapter a *credential token* where it +**Decide that the credential is named by an opaque token bound at +composition, whose resolution is per invocation and happens only inside the +process that writes it to the child's private channel.** The host gives the adapter a *credential token* where it composes the runtime: an opaque identifier that carries no credential, no routing and no authority of its own. **"Per-invocation" qualifies the resolution, not the token's arrival** — the token is bound once, per runtime, diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 43188e584..4aa8a8bda 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -82,22 +82,25 @@ place where this decision constrains an earlier one. [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept) fixes a credential **token** — a `%Loopex.LLM.ReqLLM.CredentialToken{}` struct, opaque to the adapter, routed by a host-owned registry to the custody -process that holds the bytes — as **one per configured provider, bound at -composition**, with resolution happening per invocation. An earlier revision -of this pair said ADR 0034 fixed "one token per call" and called the -generalisation a prerequisite amendment. That was a misreading of ADR 0034, -and it is withdrawn: a second provider is a second token, a second registry -row and a second custody process, composed the same way the first is, and -**no amendment to ADR 0034 is required**. +process that holds the bytes — as **one per composed model configuration, +bound at composition**, with resolution happening per invocation. That is +narrower than one per provider, deliberately: a runtime composes one model +configuration, and no provider-selection seam exists for a second to be chosen +through. So a second provider credential **does** need a prerequisite +amendment to ADR 0034 — one token per provider, selected per invocation — made +by its own amendment path and proposed with the milestone that accepts this +decision. An earlier revision of this pair said ADR 0034 fixed "one token per +call", which it never did, and a later one said no amendment was needed, which +over-read the narrowing in the other direction. What remains true is the shape of the consequence. The registry maps token to custody process, so a second provider costs a row rather than a wider value: -a runtime carries the token for each provider it is configured with, -resolution looks up the row for the token that invocation carries, and nothing -about the registry's routing-only contents, custody, rotation, the -guardian-enforced deadline or the closed reason set changes. Until ADR 0034 is -accepted and landed, this decision cannot be implemented, and nothing in M5 -anticipates it. +under the amendment a runtime would carry the token for each provider it is +configured with, resolution would look up the row for the token that +invocation carries, and nothing about the registry's routing-only contents, +custody, rotation, the guardian-enforced deadline or the closed reason set +would change. Until that amendment is accepted and landed, this decision +cannot be implemented, and nothing in M5 anticipates it. ### Seams, in the order they are worth doing @@ -184,9 +187,10 @@ Nothing public changes. The `Loopex.Policy` and `Loopex.Model` callbacks, the public protocol and its generations, public events, snapshots, artifacts, the executor protocol and every durable record are untouched. A runtime with no evaluation configured is byte-for-byte the runtime that exists today. The one -compatibility effect is on host composition and arrives with this pair: a host -that configures evaluation composes a second credential token, a second -registry row and a second custody process, exactly as it composes the first. +compatibility effect is on host composition and arrives with the prerequisite +amendment rather than with this pair: a host that configures evaluation +composes a second credential token, a second registry row and a second custody +process, and the adapter gains the seam that selects between them. Rollback is removing the evaluation. Every seam is an input, so a host that stops asking decides as it did before by the same path; a journaled answer diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md index b827aa4c2..60bddccc9 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -107,13 +107,16 @@ Three consequences are real costs rather than benefits, and are stated as such. It is a **second provider credential**, `TYPESAFE_API_KEY` alongside the model credential, which means [ADR 0034](0034-provider-credential-handoff-over-bootstrap-channel.md#concept)'s -credential **token** — already one per configured provider, bound at -composition, with resolution happening per invocation — is composed a second -time, with a second registry row and a second custody process. No amendment to -ADR 0034 is needed for that: it is the arrangement that pair already fixes, -and an earlier revision of this one described it as "one token per call", -which ADR 0034 never said. A second provider is a second row and a second -token rather than a wider value. The **state sent to the model** is bounded, redacted, provenance-typed +credential **token** — one per composed model configuration, bound at +composition, with resolution happening per invocation — has to become one per +provider, with a second registry row and a second custody process. ADR 0034 +deliberately fixes only the single-configuration case, because no +provider-selection seam exists today; the generalisation is **a stated +amendment to ADR 0034**, proposed with the milestone that accepts this +decision, and this one cannot be implemented before it lands. Because the +registry holds routing only, that amendment is a second row rather than a +widened value, which is what keeps it small. An earlier revision of this pair +called it "one token per call", which ADR 0034 never said. The **state sent to the model** is bounded, redacted, provenance-typed data the runtime already holds, under the same context-admission discipline that governs anything else staged for a provider; nothing new becomes sendable. And **latency and price are unmeasured** until the first real call; diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 83ff8e1db..a9beb7a0d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -37,7 +37,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace`'s excluded-MFA list, which keeps a named function out of a trace session before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create result's `disposition` and `residency` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace.exclude_self/1`, which keeps a credential-bearing process out of every trace session, live and future, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create result's `disposition` and `residency` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The local adapter, unchanged in behaviour and gaining exactly one read-only call — whether the marker file still holds this daemon's marker, which the socket-unlink precondition needs and `WriterLock` does not expose (`writer_lock.ex:92-105`) — its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -135,7 +135,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved in three tiers, against `Loopex.Trace` including the excluded-MFA list M5 adds to it: under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear in any entry — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module; under a configuration that **explicitly names** `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec`, the tracer is asserted to receive **no raw trace message at all** for any excluded identity — read from the tracer process, which is where a pre-delivery claim is decidable — while a non-excluded function of the same module is asserted to produce one, so the case cannot pass by tracing nothing; and the keyed-shape tier, defence in depth if an exclusion were ever lost, calls each of the three bridge functions with a **one-byte** credential and asserts no captured entry contains that byte. The shape tier matters because size alone does not protect: running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim, and only a credential-keyed value placeholdered at every size. A fourth case asserts the three identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a module pattern installed and one `{module, function, arity}` cleared after it, with the tracer receiving the non-excluded call and nothing for the excluded one, at both toolchain pairs The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-custody cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/1` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -2208,7 +2208,7 @@ who stops it and what its death means. | --- | --- | --- | --- | --- | | **Daemon owner** | The `loopex daemon` escript | — | Itself; it halts the VM | There is nothing above it; the signal handler's backstop halts with `owner_lost` if a signal finds it gone | | Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | -| Credential **custody process** (ADR 0034), **one per configured provider token** | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal. M5 composes one provider, so one process; a host configuring two carries two, each with its own registry row (`0034-…-technical.md:95-98`) | +| Credential **custody process** (ADR 0034), **one, for the one composed model configuration** | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal. ADR 0034 fixes one token per composed model configuration and no more; a second provider needs that ADR's stated amendment before a second custody process exists | | **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last of all** | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal — both fail-stop | | **Artifact transfers owner** | The composition function | Daemon owner | Orderly step 6 | `transfers_lost`, daemon-fatal. **Absent** where transfers are disabled | | **Workspace lease** | The composition function | Daemon owner | Orderly step 6 | `workspace_lease_lost`, daemon-fatal | @@ -2274,16 +2274,18 @@ daemon is a host and a host is an application. One daemon owner process, one new the two callers that need the edges assembled, `RuntimeOwner` and the daemon's owner, and which direct code cannot replace because the alternative is a second copy of the whole wiring layer. One socket listener, one narrow -core concurrent-attachment change, **one excluded-MFA list in `Loopex.Trace`** -— which unifies nothing and is not asked for by this milestone's features at -all: it exists because accepted ADR 0030 already requires that a key-bearing -call be excluded by match specification before delivery, and the +core concurrent-attachment change, **one process-level trace exclusion, +`Loopex.Trace.exclude_self/1`** — which unifies nothing and is not asked for +by this milestone's features at all: it exists because accepted ADR 0030 +already requires that a key-bearing call be excluded before delivery, and the implementation did not do it. Direct code cannot supply it, because exclusion -has to happen where the patterns are installed; redaction at the sink is too -late, the raw call having already reached the tracer. It is the smallest form -of the requirement: a list of `{module, function, arity}` identities cleared -after the module pattern, using `:trace.function/4` exactly as it already -does. **Two plain fields on the runtime-side create result** — which unify +has to happen inside the tracer that owns the session. Two smaller forms were +tried and dropped: redaction at the sink is too late, the raw call having +already reached the tracer, and a list of excluded `{module, function, arity}` +identities cannot cover what an excluded function *calls* — a traced +`:gen_tcp.send/2` shows the credential frame however this adapter's own +modules are patterned. One pid excluded from every session, live and future, +is both smaller and total. **Two plain fields on the runtime-side create result** — which unify nothing and add no wire surface: they exist because core computes `fresh?` at `control.ex:895` and then throws it away four lines later, leaving every caller unable to tell a fresh create from a replay. Direct code cannot supply diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 4c165dc4b..8ab2680af 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -40,9 +40,9 @@ v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above the core. Core gains exactly five narrow things: support for several independent attachments to one session; one read-only query that answers whether a session -ID exists durably in the root; trace exclusion, which keeps credential-bearing -work out of a trace session before any message is delivered and which accepted -ADR 0030 already requires; `quiesce/2`, the bounded settle an orderly stop +ID exists durably in the root; `Loopex.Trace.exclude_self/1`, which keeps a +credential-bearing process out of every trace session, live and future, before +any message is delivered, and which accepted ADR 0030 already requires; `quiesce/2`, the bounded settle an orderly stop drains through; and two plain fields on the **runtime-side** create result, telling a host whether the create it just made was fresh or a replay and whether the session is active or dormant — the public protocol result is @@ -59,7 +59,7 @@ second loop and no new durable command. | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the per-invocation input is an opaque token, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the credential is named by an opaque token bound at composition, whose **resolution** is what happens per invocation, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, ADR 0034's host-custody cases at `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -675,9 +675,10 @@ lease — and the companion's rejoin order says where each part goes. 1. **Core's five changes, and the residency above them.** The narrow core change that lets distinct attachments to one session coexist without implicit replacement; the read-only session-existence query the daemon's - acquire and activation paths need; the excluded-MFA list in `Loopex.Trace` - that accepted ADR 0030 already requires, which lands with workstream 5's - credential work because that is what it protects; and the bounded + acquire and activation paths need; `Loopex.Trace.exclude_self/1`, the + process-level trace exclusion that accepted ADR 0030 already requires, + which lands with workstream 5's credential work because that is what it + protects; and the bounded `quiesce/2` the orderly stop drains through, which lands before workstream 2's shutdown sequence because that sequence cannot be proved without it. The first two land first, because nothing about the daemon can be proved From c1c0db61fe6c1a41fc6a268a692d45eb649192ce Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:49:32 -0700 Subject: [PATCH 081/585] adr(0032): fix generation 2 at the precision vectors need Finding 8, all seven items, each written so a literal vector can be pinned. `control_not_held` is the non-holder `session.release_control` refusal, and it changes nothing about the current holder's lease. `control_pending`'s deadline is the daemon's, not the request's -- ADR 0023's request shape has no deadline field (0023-technical:131-133) and none is added -- starting when the acquisition is admitted and equal to ADR 0033's 30-second lease term, so no new number enters. A waiter whose connection disappears is cancelled: no grant, no epoch, since a lease granted to a gone connection would be held until it expired. `control_owner_lost` reuses the uncorrelated `error` family ADR 0023 already defines for post-admission writer loss rather than adding one, with `code`, `session_id` and `event_cursor`; it closes the controller attachment only, leaving the connection open and every observer attached. `session_index_too_large` leaves the wire error list: it is a startup exit class, raised before a socket exists, so no client can be told. A failed directory write becomes a notification rather than an error, since the activation it follows succeeded: generation 2 adds `daemon.notice` with `code` (closed, today `index_write_failed`), `session_id` and a bounded `message`, and the family enters the digest's record-families input. The existence query's `unexpected` maps to `existence_indeterminate`, because a result core did not recognise is exactly a case where existence could not be decided. `control_capacity_reached` from the lease-owner cap is registered here too, and the digest table now carries every one of them. --- ...tachment-residency-and-replay-technical.md | 91 ++++++++++++++++++- docs/plans/M5-technical.md | 2 +- 2 files changed, 90 insertions(+), 3 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index def976445..eaf9c290a 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -195,8 +195,8 @@ limits — five inputs, and generation 2 changes four of them: | --- | --- | | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | -| Record families | Adds `daemon.stopping` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_pending`, `control_owner_lost`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `session_index_too_large`, `composition_mismatch`) | +| Record families | Adds `daemon.stopping` and `daemon.notice` | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client | | Limits | Unchanged from ADR 0023's ceilings | **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 @@ -218,6 +218,12 @@ from `control_held` and deserves a different refusal. It enters the ordered error list, the digest above, and the generation-2 vectors alongside the others. +`control_capacity_reached` is the refusal for a lease operation that would +exceed the concurrent lease-owner cap — 512, the per-daemon ceiling this ADR +already fixes, reused rather than doubled by a second number. The plan's +companion states where that cap comes from and why the population it bounds is +not the activation count. + Listing the error codes matters because it is the input most easily forgotten: a refusal reason invented at implementation time and not entered in the ordered list would make the served contract differ from the digest the server @@ -227,6 +233,87 @@ generation-2 literal the conformance module pins is the digest of the contract different value and fails there. Generation 1's digest is untouched, since generation 1 gains no method, no record family and no error code. + +### Generation 2, at the precision literal vectors need + +Every code and record below has to be written as bytes before the conformance +module can pin a digest, so each is fixed here rather than left to the +implementation. Seven were underspecified in an earlier revision, and this is +the whole of what was missing. + +**`control_not_held`, the non-holder release.** `session.release_control` from +a connection that is not the current holder refuses with `control_not_held`. +It is distinct from `control_held`, which refuses an *acquisition* because +somebody else holds the lease, and from `control_owner_lost` below. The +refusal changes nothing: the current holder's lease, epoch and deadline are +untouched, which is the point — a release that could be issued by a non-holder +would be a way to take control away without taking it over. + +**`control_pending` and the deadline behind it.** A request carries exactly +`method`, `request_id` and its row's fields (ADR 0023's request shape, +`0023-…-technical.md:131-133`), so there is **no deadline field on the wire** +and none is added. The deadline is the **daemon's**, it starts when the +acquisition request is admitted — not when the client sent it, which the +daemon cannot know — and it equals the **lease term**, 30 seconds, so no +number enters that ADR 0033 has not already fixed. A waiter that reaches it +refuses `control_pending` and the client may acquire again. + +**A waiter whose connection disappears is cancelled**, and the lease owner +learns of it the same way it learns of any connection loss: the waiter is +bound to the connection that made the request, so when that connection is +gone the acquisition is abandoned, no grant is made, and no epoch is minted. +A grant to a connection that no longer exists would hold a lease nobody could +release until it expired. + +**`control_owner_lost`, exactly.** It reuses the record family ADR 0023 +already defines for post-admission writer loss rather than adding one: **one +uncorrelated `error`**, with + +| Field | Value | +| --- | --- | +| `code` | `control_owner_lost` | +| `session_id` | the session whose lease owner died | +| `event_cursor` | the last completely emitted durable cursor for that attachment, exactly as `detached` carries it | + +It is uncorrelated because no request caused it. **Close behaviour:** the +daemon emits it to the **controller's** attachment and then closes that +attachment only — the connection stays open, and observer attachments on it or +on any other connection are untouched, because an observer holds no lease and +loses nothing. A client that sees it may acquire again; the next acquisition +starts a fresh owner and mints a fresh epoch. + +**`session_index_too_large` is not a wire code**, and an earlier revision +listed it as one. It is a **startup** refusal: the daemon exits non-zero with +that class before any socket exists, so no client can be holding a connection +to be told. It is removed from the generation-2 error inventory and stays in +the daemon's exit classes, where it belongs. + +**A failed directory write is a notification, not an error.** Generation 2 +adds a **second notification record family**, `daemon.notice`, beside +`daemon.stopping`: + +| Field | Value | +| --- | --- | +| `code` | one of a closed set, today `index_write_failed` | +| `session_id` | the session the notice is about | +| `message` | a bounded non-secret sentence for an operator | + +The activation it follows **succeeded**: the session is usable and reachable +by ID, and only its directory entry and index row are missing, to be written +by the retry the plan already describes. Reporting that as an `error` would +tell a client its command failed when it did not, and saying nothing would +leave a session absent from `session.list` with no explanation. The family +enters the digest's record-families input beside `daemon.stopping`. + +**The existence query's `unexpected` maps to `existence_indeterminate`.** Core +answers one of five results; the daemon maps `store_unavailable` to the wire's +`store_unavailable` and **`unexpected` to `existence_indeterminate`**, because +a result core did not recognise is exactly a case where existence could not be +decided, and inventing a distinct wire code for "core said something we do not +understand" would expose an internal disagreement a client cannot act on. The +two refuse identically in effect — nothing created, nothing attached, no lease +— and differ only in the reason a client is given. + ### The session index, and what it may claim `session.list` reads a daemon-owned index, never the session directory or the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index a9beb7a0d..4b4e09b0e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -131,7 +131,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting an abort with `"cause" => "operator_shutdown"` for every active session **before** cancelling anything, driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping`, with literal vectors for each reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus `control_owner_lost`, which closes one session's controller attachment without ending the daemon — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | From e33ae721aa969ab4fc6153f433c541d9139fd957 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:50:55 -0700 Subject: [PATCH 082/585] plan(M5): sweep the material items across the set (1) The daemon-fatal owner-failure text that still coexisted with the session-scoped decision is gone from M5-technical's Concept-facing paragraph, which now states the session-scoped rule and names the relay as what keeps a successor's call from overtaking an older one. (2) ADR 0032's `controlled` index field is updated on lease-owner death as well as on grant, release and expiry -- a fourth way a lease stops being held, and one an earlier revision left out; a listing still saying `controlled: true` would name a holder that no longer exists. (3) ADR 0031 said the daemon does not compose through `LoopexComposition`. It does: what it does not use is `with_runtime/2`, whose bracket owns the runtime and returns no adapter pid. M5's caller-owned entry point runs the same sequence in the caller's process, so the adapter is started by the composition code as always and the link lands on the daemon's owner. Bypassing composition would have meant a second copy of the wiring layer. (7) ADR 0035's evidence asked that every evaluation result produce the same decision as no evaluation, which proves the evaluation is ignored -- the failure mode, not the property. It is replaced by a discriminating witness: two answers straddling a host threshold produce different decisions, the same two against a host whose threshold sits outside both produce the same decision, and a host with no evaluation is byte-identical to today. Its durable fact gains a name and fields, `evaluation_recorded`, in both files. --- ...store-selection-and-migration-technical.md | 14 +++++++---- ...tachment-residency-and-replay-technical.md | 7 +++++- ...ision-models-as-policy-inputs-technical.md | 23 +++++++++++++++---- ...-typed-decision-models-as-policy-inputs.md | 2 +- docs/plans/M5-technical.md | 16 +++++++------ 5 files changed, 44 insertions(+), 18 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 8605aebfd..49d4e8b96 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -52,10 +52,16 @@ exits and keeps the adapter's pid, so the termination arrives as `{:EXIT, store_pid, reason}` at a clause the daemon wrote — carrying the store's own reason, which is what separates `store_capacity_exceeded` from `store_lost`. An OTP supervisor would not do: it reports no child's exit -reason to any callback. It does not compose through -`LoopexComposition`, whose `start_edge/2` takes the `start_link` inside a -process `RuntimeOwner` spawns and which returns no adapter pid — a daemon on -that bracket could not observe this failure at all. On the reported exit it +reason to any callback. Nor does the daemon use +`LoopexComposition.with_runtime/2`, whose bracket takes the `start_link` +inside a process `RuntimeOwner` spawns and returns no adapter pid — a daemon +on that bracket could not observe this failure at all. It **does** compose +through `LoopexComposition`: M5 gives that application a caller-owned entry +point which runs the same edge-assembly sequence **in the caller's process** +and returns every pid it linked, so the adapter is started by the composition +code as it always was and the link lands on the daemon's owner. An earlier +revision of this paragraph said the daemon bypasses composition entirely, +which would have meant a second copy of the wiring layer. On the reported exit it refuses service, closes every connection with `store_lost`, or `store_capacity_exceeded` where that was the store's own reason, and exits non-zero. It does **not** unlink the socket: the marker is already released, diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index eaf9c290a..0b3f37409 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -335,7 +335,12 @@ the daemon itself owns or reads once: this lifetime*, set to `active` at activation and never set back, because activation is one-way. It is not a claim about a live coordinator; - `controlled`, a daemon fact, updated on every lease grant, release and - expiry by the same lease owner ADR 0033 gives those transitions. + expiry by the same lease owner ADR 0033 gives those transitions — **and on + that owner's death**, which is a fourth way a lease stops being held and + which an earlier revision left out. The daemon's owner process, which + observes the exit, clears `controlled` for that session as it closes the + controller attachment; a listing that still said `controlled: true` would be + naming a holder that no longer exists. **`residency` says what the daemon knows, not what core is doing.** Its two values mean exactly: diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 4aa8a8bda..850159e97 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -144,11 +144,24 @@ reachable. The negatives carry the decision and are written before the seams: -- for every seam, an answer at every extreme — probability 0, probability 1, - confidence 1.0, a `:choice` concentrated on one option — produces exactly the - decision the host would have made without an evaluation, proved by running - each case twice, with the evaluation stubbed at that extreme and with it - absent, and requiring identical decisions and identical durable records; +- **the evaluation changes the decision, and the host's thresholds are what + change it** — the discriminating witness, because the obvious one proves the + opposite of what it looks like. Requiring that every evaluation result + produces the same decision as no evaluation at all would prove the + evaluation is *ignored*, which is the failure mode, not the property. So for + every seam, two answers that straddle a host threshold are run against the + same host policy and asserted to produce **different** decisions; the same + two answers against a host whose threshold sits outside both produce the + **same** decision; and a host with no evaluation configured is asserted + byte-identical to today in decision and durable record. What is held + constant is that Loopex decides nothing: the difference is always the host's + threshold applied to a typed input, never a Loopex rule; +- **the journaled fact has a name and a shape**, and is asserted by both: + an `evaluation_recorded` record carrying the seam, the model identity, the + typed answer's plain projection, `usage`, and the durable command it + informed — and nothing else, in particular no prose and no provider payload. + A decision reached without an evaluation writes no such record, which is how + a later reader tells the two apart; - no evaluation result appears in a grant, a lease, an epoch, a fence, a receipt or any executor argument, proved by the same drift-style scan that pins other forbidden reaches; diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md index 60bddccc9..3aa9d71be 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -52,7 +52,7 @@ interactions, model output, context and metadata never grant authority, and ADR 0009 already makes every executor-backed tool call consult the host's policy with no exemption predicate. What this decision adds is that a *typed, calibrated* model answer is still model output, and gets no privilege for -being numeric. +being numeric. The record has a name, `evaluation_recorded`, and the companion fixes its fields; a decision reached without an evaluation writes none, which is how a later reader tells the two apart. The seams, in the order they are worth doing: diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 4b4e09b0e..1944b9389 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -104,13 +104,15 @@ session, which the holder may send before attaching. "Verified" means verified by core's read-only existence query, not by having attached or resumed already: acquire validates existence with that query and refuses an unknown ID with nothing created. The lease record lives -in the daemon's memory, keyed by session, for the daemon process's lifetime; one -owner process per session serializes its lease transitions with its admission -handoff, and that owner's failure is fatal to the daemon instance rather than -survivable — it holds the session's in-flight admission set, which a takeover -waits on, so a restart beneath live sockets could grant a successor while a -forgotten admission could still settle. ADR 0033 fixes the rule; the daemon -restarts with no lease, no connection and no activated session. For +in the daemon's memory, keyed by session, for as long as that session has a +lease or an acquisition; one owner process per session serializes its lease +transitions with its admission handoff, and that owner's failure is **scoped +to its session**: the controller attachment closes with `control_owner_lost`, +every observer stays, and the next acquisition starts a fresh owner with a +fresh epoch. What keeps a successor's call from overtaking an older one is the +**admission relay**, a fixed daemon process that holds a ticket for every core +call and blocks the replacement's first grant until that session's tickets +settle. ADR 0033 fixes both rules. For every existing-session mutation the daemon checks the requesting connection identity, the current epoch, the held state and the unexpired term together before forwarding to core; an epoch alone is not authority, and every epoch is From 8e12bf8f497a1ae736197f3976c3387afa03cc10 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:53:17 -0700 Subject: [PATCH 083/585] plan(M5): rebuild the inventory and apply my adversarial pass The inventory is rebuilt from scratch for this revision: twenty rows, nine fixed daemon-linked processes, the dynamic lease owners with their real lifecycle and 512 cap, connections, stop helpers, the relay's per-call tasks, five core-internal kinds and the adapter's and executor's per-invocation and per-job processes. The added pass classes produced four changes. (k) `resume` has the same ambiguity `create` had, which the finding did not name: a replayed resume answers `{:ok, session_id}` from the `{:completed, ...}` branch (control.ex:311-312) exactly as a fresh one does, and the daemon charges an activation for resume too, so a client retrying under its original `command_id` would be charged twice. Core already knows the difference and exposes it in one mode -- `completed_resume_reply/2` answers `{:ok, {:replayed, session_id}}` for the prepared mode at :526 and a bare `{:ok, session_id}` for the plain one at :527 -- so the plain resume result carries the same `disposition` and `residency` the create result does. (i) At the maximum admitted grace the stated stop bound is itself enormous, since `drain_ms` grows with `g`; the plan says the maximum is a statement about a configuration rather than a constant. (j) While the owner waits on `quiesce/2` it is not reading its mailbox. The wait is bounded, and when it returns the owner reads what queued before telling any client, so a Store that died during the drain switches to the fail-stop path with its real class; a second `SIGTERM` is discarded. (l) Every new correlated refusal is stated once as carrying its request's `request_id`, no cursor and no close, leaving `control_owner_lost`, `daemon.stopping` and `daemon.notice` as the only uncorrelated records -- which is what lets the vectors be written without guessing. Counts and the Concept's topology paragraph follow the relay and the owner lifecycle. --- ...tachment-residency-and-replay-technical.md | 11 ++++ docs/plans/M5-technical.md | 62 ++++++++++++++----- docs/plans/M5.md | 18 +++--- 3 files changed, 70 insertions(+), 21 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 0b3f37409..86c2da1f0 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -305,6 +305,17 @@ tell a client its command failed when it did not, and saying nothing would leave a session absent from `session.list` with no explanation. The family enters the digest's record-families input beside `daemon.stopping`. +**Correlation, for the refusals above.** `control_not_held`, +`control_pending`, `control_capacity_reached`, `control_held`, +`session_dormant` and the four existence-query refusals are ordinary +**correlated** errors: each answers one request and carries that request's +`request_id`, no `event_cursor` and no session state, and none closes +anything — the connection and every attachment on it are untouched. The two +uncorrelated cases in generation 2 are the ones named above, +`control_owner_lost` and the `daemon.stopping` and `daemon.notice` records, +and each states its own close behaviour where it is defined. Stating this once +is what lets the vectors be written without guessing. + **The existence query's `unexpected` maps to `existence_indeterminate`.** Core answers one of five results; the daemon maps `store_unavailable` to the wire's `store_unavailable` and **`unexpected` to `existence_indeterminate`**, because diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 1944b9389..1aa653cdc 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -642,6 +642,20 @@ carries two plain fields beside the session ID:** | `disposition` | `:fresh` \| `:historical` | Charge an activation for `:fresh`; charge nothing for `:historical` | | `residency` | `:active` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | +**The same two fields belong on the runtime-side `resume` result**, which my +own pass over this section found and the finding did not name. `resume` has +exactly the same ambiguity: a replayed resume takes the `{:completed, …}` +branch and answers `{:ok, session_id}` (`control.ex:311-312`), a fresh one +answers the same through `start_resume_owner`, and the daemon charges an +activation for resume as it does for create — so a client retrying a resume +under its original `command_id` would be charged twice. Core already knows the +difference and already exposes it in one mode: `completed_resume_reply/2` +answers `{:ok, {:replayed, session_id}}` for the **prepared** mode at +`control.ex:526` and a bare `{:ok, session_id}` for the plain one at `:527`. +Rather than make the daemon use a mode it does not otherwise want, the plain +resume result carries the same `disposition` and `residency` the create result +does. That is one shape for both, not two. + **The public protocol result is unchanged.** Generation 1 and generation 2 return what they return today; this is an in-VM API detail between core and any host, and no wire schema, digest or vector moves. A host that ignores the @@ -1384,8 +1398,13 @@ the failed-start reverse cleanup, for the same reason. > **Maximum graceful stop = `drain_ms` + `teardown_ms` + 30 s.** -A service manager that kills the daemon sooner than that turns the stop into a -forced shutdown — the journal is still crash-equivalent, but work that would +That maximum is as large as the composed grace makes it: `drain_ms` is +derived from `cli_backstop_ms`, which grows with `g`, so an operator who +composes a grace of days has told the daemon it may drain for days. The bound +is a statement about *this* daemon's configuration rather than a constant, and +the operator documentation says so where it says what to set +`TimeoutStopSec` to. A service manager that kills the daemon sooner than that +turns the stop into a forced shutdown — the journal is still crash-equivalent, but work that would have settled does not, and the marker may be left for the next daemon's verified stale-writer recovery. The operator documentation states the bound and that consequence together, so a `TimeoutStopSec` shorter than it is a @@ -1689,6 +1708,17 @@ of `max(10_000, grace_ms + 2_000)` from that same grace (`apps/loopex/lib/loopex/executor.ex:458`), and `cli_backstop_ms` is larger still. +**What queues while the owner waits for it.** The owner is blocked in the +`quiesce/2` call for at most `drain_ms`, and while it is blocked it is not +reading its mailbox: a linked component's `{:EXIT, …}` waits, as does a second +signal. That is safe in one direction and deliberate in the other. The wait is +bounded, so nothing waits indefinitely; and when the call returns, the owner +reads what queued **before** telling a single client, so a Store that died +during the drain switches the daemon to the fail-stop path with its real class +rather than being reported as an orderly stop. A second `SIGTERM` during the +drain is idempotent: the sequence is already running, and the owner discards +it rather than restarting anything. + **A session waiting on an interaction cannot settle, and that is correct.** An answer to a durable interaction is a session command under ADR 0024, and step 1 has already refused admissions, so no answer can arrive during the @@ -2201,29 +2231,33 @@ do. This table is the answer to both: one row per boundary M5 touches, and every cell resting on a code line that exists today or on a component this plan names as new. It is the thing to check a change against. -**First, the process inventory**, because more than one review found two -documents counting the same processes differently. Every process any document -in this set names appears here once, with who starts it, who holds its link, -who stops it and what its death means. +**First, the process inventory**, rebuilt from scratch for this revision +because more than one review found two documents counting the same processes +differently. Every process any document in this set names appears here once, +with who starts it, who holds its link, who stops it and what its death means. +Nine fixed, one bounded dynamic population, and everything else owned by core, +the adapter or the executor. | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | -| **Daemon owner** | The `loopex daemon` escript | — | Itself; it halts the VM | There is nothing above it; the signal handler's backstop halts with `owner_lost` if a signal finds it gone | +| **Daemon owner** | The `loopex daemon` command process | — (monitored by that command process) | Itself; it halts the VM | The command process's monitor halts non-zero with `owner_lost`; the signal handler's backstop is the second route | | Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | -| Credential **custody process** (ADR 0034), **one, for the one composed model configuration** | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal. ADR 0034 fixes one token per composed model configuration and no more; a second provider needs that ADR's stated amendment before a second custody process exists | -| **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last of all** | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal — both fail-stop | +| Credential **custody process** (ADR 0034), **one, for the one composed model configuration** | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal. A second provider needs ADR 0034's stated amendment before a second exists | +| **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last of all**, in its own fixed 30 s phase | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal — both fail-stop | | **Artifact transfers owner** | The composition function | Daemon owner | Orderly step 6 | `transfers_lost`, daemon-fatal. **Absent** where transfers are disabled | | **Workspace lease** | The composition function | Daemon owner | Orderly step 6 | `workspace_lease_lost`, daemon-fatal | | **Local executor** | The composition function | Daemon owner | Orderly step 6, before the lease | `executor_lost`, daemon-fatal | | **Runtime root** (a supervisor) | The composition function | Daemon owner | Orderly step 5 | `runtime_lost`, daemon-fatal | -| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Orderly step 1 stops it accepting; step 3 closes and unlinks | `listener_lost`, daemon-fatal, and the one fatal class no client can be told | -| **Lease owner, one per activated session** (ADR 0033) | Daemon owner, on activation | Daemon owner | Orderly step 4, in sequence | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the next acquisition starts a fresh owner with a fresh epoch. Population bounded by the 64-activation ceiling | -| **Connection**, one per accepted client | The listener | The listener | Orderly step 3, or the client | That client's connection closes. Nothing else | +| **Admission relay** | Daemon owner, after the runtime | Daemon owner | Orderly step 4, after the lease owners whose tickets it holds | `relay_lost`, daemon-fatal: the record of every in-flight admission is gone | +| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Step 1 stops it accepting; step 3 closes and unlinks | `listener_lost`, daemon-fatal, and the one fatal class no client can be told | +| **Lease owner, one per session under lease or acquisition** (ADR 0033) | Daemon owner, on the first lease operation after existence validation | Daemon owner | Retires when the lease is free, no acquisition waits and the relay holds no ticket; stopped unconditionally in step 4 | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the next acquisition starts a fresh owner with a fresh epoch. At most 512 at once | +| **Connection**, one per accepted client | The listener | The listener | Step 3, or the client | That client's connection closes. Nothing else | | **Stop helper**, one per stop | Daemon owner, `spawn_monitor` | Monitored, never linked | Its own call returning or raising | Nothing: it is monitored so that whatever `GenServer.stop/3` does to it cannot reach the owner | -| **Session coordinator** | Core, under a `DynamicSupervisor` (`restart: :temporary`) | Core | Core, when the runtime stops | Core's own refusal on the next command for that session; **no signal reaches the daemon and none is owed** | +| **Relay task**, one per core call | The relay, `spawn_monitor` | Monitored by the relay | The call returning | Settles that call's ticket as unknown, the same fact `commit_unknown` carries | +| **Session coordinator** | Core, under a `DynamicSupervisor` (`restart: :temporary`) | Core | Core; **and `quiesce/2` fences and terminates it** at the drain deadline | Core's own refusal on the next command for that session; **no signal reaches the daemon and none is owed** | | **Owner group and workers** | Core, beneath a coordinator | Core | Core | Core's; a trapping owner group unwinds on its own clock and the daemon does not wait for it | | **Attachment dispatcher** | Core, per attachment | Core | Core | That attachment's, and core's existing detachment rules | -| **Trace tracer** | Core, per trace session | Core | Core | The trace session's; it carries no daemon meaning | +| **Trace tracer** | Core, per runtime | Core | Core | The trace session's; it holds the excluded-pid set, so its loss ends tracing rather than exposing anything | | **Provider sender and guardian** (ADR 0034) | The adapter, per invocation, inside the calling process | Neither is linked to the daemon owner | The guardian kills the sender at the deadline; both end with the invocation | That invocation's refusal, as one of the seven atoms. No daemon class | | **Provider child**, its Port and OS process (ADR 0019) | The adapter's launcher, per invocation | The Port's owner | The invocation | That invocation's refusal | | **Per-job Port worker, carrier and guard** (ADR 0022) | The local executor, per job | The worker is monitored by the executor; the carrier and guard are OS processes | The worker terminates the captured group when the executor goes | The job's outcome, reconciled through `commit_unknown`. **These are the processes the daemon cannot wait for at a halt** | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 8ab2680af..49f38863a 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -521,13 +521,17 @@ supervisor.** Its top-level component is one `GenServer` that traps exits and `start_link`s a **fixed set** of them: the five the composition function assembles in its caller's process — the Store adapter, the runtime root, the artifact transfers owner where enabled, the workspace lease and the local -executor — plus three of the daemon's own, the credential routing registry and -custody process ADR 0034 gives the host, and the listener. Eight where -transfers are enabled, seven where they are not. **Beside them it links one -lease owner per activated session**, a population bounded by the 64-activation -ceiling, and that one class is session-scoped rather than daemon-fatal: its -death closes that session's controller attachment and leaves every other -session serving. It keeps every pid, because +executor — plus four of the daemon's own, the credential routing registry and +custody process ADR 0034 gives the host, the **admission relay** that holds a +ticket for every core call the daemon makes, and the listener. Nine where +transfers are enabled, eight where they are not. **Beside them it links one +lease owner per session under lease or acquisition**, started at the first +lease operation rather than at activation, retired when the lease is free and +nothing is outstanding, and capped at the 512 ADR 0032 already fixes. That one +class is session-scoped rather than daemon-fatal: its death closes that +session's controller attachment and leaves every other session serving, while +the relay is what keeps the replacement's first call from overtaking an older +one. It keeps every pid, because each one is a component it must be able to name when that component dies. An exit the owner did not ask for is fatal, by that process's own clause, and that clause is what reads a dying Store's reason and turns it into the class From ea3f2ae25f790e14904c54b8b16b262e4bd5952e Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:53:55 -0700 Subject: [PATCH 084/585] plan(M5): finish the process-exclusion sweep across the set --- ...al-handoff-over-bootstrap-channel-technical.md | 15 ++++++++------- ...r-credential-handoff-over-bootstrap-channel.md | 9 ++++++--- docs/plans/M5.md | 15 ++++++++++----- 3 files changed, 24 insertions(+), 15 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index b096c2162..86ad9a602 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -655,14 +655,15 @@ Three proofs are new: `receive_custody_reply/2` or `write_credential_frame/2`, no raw trace message for them, and no credential bytes or token anywhere — because the adapter is in no namespace wildcard. Under a configuration that - **explicitly names** `Loopex.LLM.ReqLLM.ProviderBridge` and + **explicitly names `:gen_tcp`**, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec`, the tracer is asserted to receive **no - raw trace message** for any excluded MFA, while a non-excluded function of - the same module is asserted to produce one — the pre-delivery property read - where it holds, and a case that cannot pass by tracing nothing. A third case - asserts the three functions exist with their exact identities and that a - one-byte credential appears in no captured entry, so neither of the first - two can pass vacuously. + raw trace message from the sender process at all**, while a non-excluded + control process making the same `:gen_tcp.send/2` call in the same session + is asserted to produce one — the pre-delivery property read where it holds, + and a case that cannot pass by tracing nothing. A third case asserts the + three functions exist with their exact identities and that a one-byte + canary credential appears in no captured message or entry, so neither of the + first two can pass vacuously. - **Host custody, proved at each host rather than in the adapter.** The adapter's test tree cannot prove a claim about the CLI's or the daemon's composition, and an earlier draft filed all three there. Each case lives diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index e7d64dd39..fc0b3a4f4 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -101,9 +101,12 @@ because the raw call reaches the tracer first; it stays as defence in depth, resting on a bound *shape* — those bytes always travel under a credential-named key and are placeholdered at any size, which size alone would not give, since the pass leaves a short binary verbatim and a credential may -be one byte. The companion names every excluded function and module — together -the whole of the parent-side surface — and M5 proves the exclusion at the -tracer rather than at the sink. ADR 0030 is not edited: its prose is honoured +be one byte. The exclusion is by **process**, not by function: the sender excludes itself +from every trace session before it resolves anything, because a function that +carries the credential calls functions it does not own — a traced +`:gen_tcp.send/2` shows the frame whatever this adapter's modules are +patterned. M5 proves it at the tracer rather than at the sink, in a case that +names `:gen_tcp` on purpose. ADR 0030 is not edited: its prose is honoured once this lands. **Everywhere else the boundary is where the adapter's claims stop.** Inside it diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 49f38863a..5382b2e09 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -878,11 +878,16 @@ host that named the adapter would create one more message holding the credential. M5 therefore **implements what the accepted ADR already requires**, as core's -third change in this milestone: `Loopex.Trace` gains a list of excluded -`{module, function, arity}` identities, cleared after the module pattern is -installed, so an excluded function produces no trace message at all. The -mechanism was verified by probe at both toolchain pairs before it was written -down. ADR 0030 is **not** edited — an accepted ADR changes through its own +third change in this milestone — and implements it by **process** rather than +by function, because a function-level list cannot hold: an excluded function +calls functions it does not own, and a trace session naming `:gen_tcp` +sees the credential frame `ProviderCodec.send/3` hands it, whatever this +adapter's own modules are patterned. `Loopex.Trace` gains +`exclude_self/1` and an excluded-pid set: the credential-bearing process +excludes itself before it resolves anything, from every live session and every +future one, and no trace configuration can name it back in. Both the leak and +the mechanism were reproduced by probe at both toolchain pairs before this was +written down. ADR 0030 is **not** edited — an accepted ADR changes through its own amendment path — and its prose is honoured once this change lands. This is a change to an accepted ADR's subject matter rather than to its text, so it is flagged for the maintainer as such. From 9e4e30c72d28bb580591ad4657735a2417bfefdf Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 08:54:29 -0700 Subject: [PATCH 085/585] plan(M5): retire the per-component grace from the last four places --- docs/plans/M5-technical.md | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 1aa653cdc..690d26d0e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1131,10 +1131,11 @@ revision, its `{:timeout, _}` / `{:noproc, _}` / catch-all clauses, its component's fate from what a library function did to the caller, and row 1 shows that is not derivable. -**What bounds each step.** The outer `receive` carries `after grace`, the -composed cleanup grace — one bound per component, the same number everywhere, -and the same number the helper passed to `GenServer.stop/3`, so a component -gets the grace once rather than twice. The inner `receive` after the kill +**What bounds each step.** The outer `receive` waits until the phase's +**absolute deadline** — the shared teardown deadline for every non-Store stop, +the Store's own fixed phase for the Store — and the helper is given what +remains of it, so a component is bounded once rather than twice and the phase +is bounded whatever the component does. The inner `receive` after the kill carries no `after`, and needs none: `Process.exit(pid, :kill)` on a live process is unconditional, and on one already dead the exit the owner is waiting for is the one that made it dead, already queued. It is a wait for a @@ -1802,8 +1803,8 @@ to write. 3. **Stop the executor** — on every class but `executor_lost`, where it is the component that already died — under the same discipline as every other stop: a monitored helper calling `GenServer.stop(pid, :normal, grace)`, the - owner waiting on its own link with `after grace` and killing on expiry, and - the composed cleanup grace the ordered path's step 6 uses. This is not tidiness: the executor is + owner waiting on its own link until the shared teardown deadline and + killing on expiry — the same deadline the ordered path's step 6 uses. This is not tidiness: the executor is the one linked process whose work reaches outside the VM, and stopping it is what tells its Port-owning workers to terminate the captured process groups. Halting without stopping it would never start that cleanup at @@ -2275,7 +2276,7 @@ the adapter or the executor. | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the composed cleanup grace, tells clients, unlinks the socket while it still holds the marker, and then stops its linked processes in reverse order — lease owners, runtime, edges, Store last — each stop driven by a monitored helper calling `GenServer.stop(pid, :normal, grace)` while the owner waits on its own link with `after grace` and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the derived drain budget, tells clients, unlinks the socket only while it can still show it holds the marker, and then stops its linked processes in reverse order — lease owners, the relay, runtime, edges, and the Store last in its own fixed 30 s phase — each stop driven by a monitored helper calling `GenServer.stop/3` while the owner waits on its own link until the shared teardown deadline and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | From 970acf280e09b2b63376aa2d1ffde0280895017e Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 09:07:49 -0700 Subject: [PATCH 086/585] plan(M5): journal no shutdown cause, fix three citations P0-1, applied as decided: `quiesce/2` admits the existing abort command unchanged and journals no `"cause"` field. The operator-shutdown cause reaches the operator twice already -- `operator_stop` in `daemon.stopping` and the bounded stderr line -- so nothing durable needs it, and a field on a durable record is a persistent-schema decision not worth taking for a fact already reported. The rejected option is recorded with its date: a proper schema change with a version bump and a forward-only root. The rollback claim is now asserted rather than argued -- the drain witness has the released foreground surface reopen the drained root on the same adapter and resume the session -- and the three "adapter unchanged" sentences (M-1) become "unchanged in behaviour, gaining one read-only call". On the P0's stated mechanism I have to report a disagreement rather than write it into the plan. The frame's records are derived from `transaction.records` (state.ex:326-339), and replay recomputes the frame from the **stored** transaction before comparing (state.ex:414-426), so the equality is independent of which core version wrote it; the canonical binding recomputes from stored fields the same way; a record payload is validated as plain data against the shared normalizer and a byte ceiling (store.ex:1588-1600), not a fixed key set; and `apply_command_record/2` (session_state.ex:2086-2095) reads four named keys while `admissible_command_kind?/2` (:2120-2121) checks two, both ignoring unknown ones. An extra field would therefore not have produced `invalid_history` on a 0.1.0 reader by any of those paths. The decision stands on its own reasoning and the plan states that reasoning; it does not cite a breakage I could not reproduce. M-2: the 512 cap cited a line that now says something else. It cites ADR 0032 `:720` for the attachment number it reuses and `:222` for the cap itself, and the numbers table gains one sentence distinguishing the three 512s -- attachments, MiB, lease owners -- so "one number, one ADR" reads correctly. L-1: `fresh?` is bound at control.ex:895 **and used** by the cond at :903-907 to decide `start_owner`; what is discarded is the distinction in the reply, and the sentence now says that. --- ...mon-grade-store-selection-and-migration.md | 2 +- docs/plans/M5-technical.md | 102 ++++++++++++------ docs/plans/M5.md | 16 +-- 3 files changed, 81 insertions(+), 39 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 2c87eb04a..28e2a9e02 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -71,7 +71,7 @@ what backup and restore, and which binary is the oldest reader of the new root their own ADR, proposed with the successor milestone's plan, accepted on its own review, declaring `Supersedes: 0031` for the selection this pair makes. Nothing about that work binds M5, and nothing in M5 forecloses it: the local -adapter, its format and its ports are unchanged, so any successor starts from +format and its ports are unchanged, and its adapter is unchanged in behaviour, gaining one read-only call that reports whether it still holds its marker, so any successor starts from exactly the root M5 leaves. **Alternatives rejected.** Deferring this decision out of M5 entirely was diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 690d26d0e..283086f5b 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -132,7 +132,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting an abort with `"cause" => "operator_shutdown"` for every active session **before** cancelling anything, driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -298,7 +298,7 @@ over generation 1's method set under the exact-generation rule: a generation-1 client sees no daemon method and no lease field, the daemon refuses a generation-1-only initialize, and the foreground server keeps serving generation 1 unchanged. No mixed-generation stream is promised. The private -journal, its adapter and its format are unchanged; the embedded API, public +journal and its format are unchanged, and its adapter is unchanged in behaviour, gaining one read-only call — whether the marker file still holds this daemon's marker — that writes nothing and that the socket-unlink precondition needs; the embedded API, public events, snapshots, artifact formats and the executor protocol are unchanged. Source `VERSION` is distinct from protocol generation, provider build and schema digest. @@ -631,9 +631,11 @@ reliably, because core answers both the same way. All three branches at active; the command was seen before, so no owner is started; or it is fresh and an owner starts — and the value carries no trace of which. -Core already computes what is missing: `create_command_absent?/2` binds -`fresh?` at `:895`, four lines above the branch that discards it. So the fifth -change is to stop discarding it. **Core's runtime-side create result — the +Core already computes what is missing, and uses it: `create_command_absent?/2` +binds `fresh?` at `control.ex:895`, and the `cond` at `:903-907` reads it to +decide whether to `start_owner`. What is discarded is the distinction in the +**reply** — all three branches answer `{:ok, session_id}` — so the fifth change +is to stop discarding it there. **Core's runtime-side create result — the Elixir function the daemon calls, not the released public protocol result — carries two plain fields beside the session ID:** @@ -969,7 +971,7 @@ implementation: | When does one start? | On the **first lease operation for that session after successful existence validation** — an `session.acquire_control`, whether or not the session is active. Not at activation: an earlier revision said activation, which was wrong twice over, since dormant recovery acquires *before* it resumes and `loopex attach --take-over` may acquire and release a session it never activates | | When does one retire? | When the lease is free — released or expired — **and** no acquisition is waiting **and** the relay holds no outstanding ticket for that session. All three, because any one of them alone would retire an owner whose state something still depends on | | When does one stop unconditionally? | At daemon exit, in the stop sequence below | -| How many can exist at once? | One per session under lease or acquisition, capped at **512, ADR 0032's per-daemon ceiling** (`0032-…-technical.md:617`), reusing that number rather than inventing one; a lease operation that would exceed it refuses with `control_capacity_reached`. The population is **independent of the activation ceiling**, which counts something else entirely | +| How many can exist at once? | One per session under lease or acquisition, capped at **512, the per-daemon attachment ceiling ADR 0032 already fixes** (`0032-…-technical.md:720`), reused rather than invented, with the cap itself stated at `0032-…-technical.md:222`; a lease operation that would exceed it refuses with `control_capacity_reached`. The population is **independent of the activation ceiling**, which counts something else entirely | | What does its death mean? | That **session's** collaboration state, not the daemon's — the one exception to fail-stop uniformity, below | **Why not the activation ceiling.** An earlier revision bounded the population @@ -1642,13 +1644,13 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: **Three parts, and the first is the part an earlier revision got wrong.** -1. **A durable cause, admitted before any cancellation.** ADR 0023 fixes that +1. **A durable admission, before any cancellation.** ADR 0023 fixes that *only* the durable `session.abort` command cancels, and that cancellation is "never inferred from EOF or death" (`0023-…-technical.md:365`, with the method table at `:169`). Quiesce cancels, so quiesce must admit. For every active session it therefore - **admits an abort through the existing path, carrying the cause - `operator_shutdown`**, and only then runs that session's cancellation. The + **admits the existing abort command**, unchanged, and only then runs that + session's cancellation. The path is the one that exists: `propose_new/3` for `%{type: :abort}` writes a `command_admitted` record with `"command_type" => "abort"` and `"admission" => "accepted"` (`session_state.ex:1684-1700`), resolving the @@ -1657,18 +1659,36 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: (`:1750-1761`) — the right answer for an idle session, needing no special case. - **That is a durable record field**, and the plan says so rather than - letting it look like a private detail: the admitted abort record gains a - bounded `"cause"` naming why the abort exists — `operator_shutdown` here, - absent for a client's own `session.abort` — so an operator reading a - journal can tell a shutdown from a cancellation somebody asked for. It is - additive to a record generation 1 already writes and changes no existing - field. - - The rejected option is recorded: cancelling **without** a durable command, - which the previous revision's "quiesce adds no durable command" amounted - to, contradicts ADR 0023 outright and would leave a journal saying a run - ended for a reason nobody recorded. + **Nothing new is journaled, and that is the decision.** The abort quiesce + admits is the abort that exists: the same command, the same record, the + same fields a client's `session.abort` writes today. **No `cause` field is + added.** An earlier revision of this section added a bounded `"cause"` so a + journal could say which aborts were shutdowns; the maintainer rejected that + on 2026-09-20, and the reason is proportion rather than mechanism. The + operator-shutdown cause is an operator-facing fact, and the daemon already + reports it twice — as `operator_stop` in the `daemon.stopping` record every + client receives, and in its bounded `stderr` line. Nothing durable needs + it, and a field added to a durable record is a persistent-schema decision, + which is not a thing to take in passing for a fact that is already + reported. + + **So a drained root is exactly a root, and the plan can say why.** The + frame the local adapter writes is built from the transaction the caller + supplied — its records are derived from `transaction.records` + (`state.ex:326-339`) — and replay recomputes that frame from the stored + transaction and requires whole-term equality, `expected == frame`, refusing + `:frame_does_not_match_transition` otherwise (`state.ex:414-426`). A drain + that writes the records core already writes therefore produces frames the + released reader recomputes identically, and the adapter's `@schema_version` + stays `1` (`state.ex:7`) because nothing about the schema moved. That is + what makes **rollback** true rather than asserted: a root a drained daemon + leaves behind is opened by the released foreground surface, on the same + adapter, with no migration and no recovery step. + + The rejected option is recorded with its date: proposing the schema change + properly — a version bump and a root that only newer readers can open — + was available and was declined, because it would buy a journal annotation + at the price of a one-way root. 2. **A derived budget.** `drain_deadline_ms` is `drain_ms`: the maximum over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` @@ -2025,10 +2045,13 @@ the cause and try again without a recovery step. its own reason and not because the owner asked. - **In-flight shutdown, both halves of it.** Two cases, because the drain has two outcomes and proving one would hide the other. Both assert the durable - cause first: a `command_admitted` record with `"command_type" => "abort"` - and `"cause" => "operator_shutdown"` appears for the active session - **before** any cancellation, because ADR 0023 admits no cancellation that - was not commanded. + admission first: a `command_admitted` record with + `"command_type" => "abort"` appears for the active session **before** any + cancellation, because ADR 0023 admits no cancellation that was not + commanded — and both assert it is **the record a client's own + `session.abort` writes**, field for field, with no shutdown-specific field + on it. The operator learns the cause from `daemon.stopping` and from + `stderr`, not from the journal. *It settles.* A daemon with a dispatched tool effect that **can** be cancelled inside its session's own grace receives `SIGTERM`. The case @@ -2052,11 +2075,17 @@ the cause and try again without a recovery step. The journal after this path is **not** byte-identical to an abrupt death at the same instant, and the case asserts the difference rather than the old - equality: it holds exactly one more record, the admitted abort with its - cause. An earlier revision claimed byte-identity, which was true of a design - that cancelled nothing and is false of one that records why it cancelled. - What remains identical is what the abrupt-death case actually needs: the - unresolved transaction, its fence, and the outcome reconciliation produces. + equality: it holds exactly one more record per drained session, the admitted + abort. What remains identical is what the abrupt-death case actually needs: + the unresolved transaction, its fence, and the outcome reconciliation + produces. + + **And the rollback assertion sits here**, because this is the path that + writes the extra record: after the drain, the **released foreground + surface** opens that same root on the same adapter, replays it, and resumes + the session — no migration, no recovery step, no version refusal. That is + the proof that a drained root is still an ordinary root, and it is asserted + rather than argued. - **Store-loss fail-stop.** The Store is made to terminate under a live listener. The case asserts the daemon observed it, closed the listener and every connection with `store_lost`, unlinked the socket, and exited non-zero @@ -2380,11 +2409,12 @@ line; M5 introduces none of its own. | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | | Attachments per session | 64 | ADR 0032 | -| Attachments per daemon | 512 | ADR 0032 | +| Attachments per daemon | 512 | ADR 0032, `:720` | | Core event-count queue per attachment | 1,024 events | ADR 0032 | | Daemon socket output buffer per connection | 4 MiB encoded | ADR 0032 | | Resident window per session | 4,096 events and 16 MiB encoded | ADR 0032 | -| Aggregate retained encoded events per daemon | 512 MiB | ADR 0032 | +| Aggregate retained encoded events per daemon | 512 MiB | ADR 0032, `:147` and `:716` | +| Concurrent lease owners | 512, the attachment number reused rather than a second limit | ADR 0032, `:222` | | Idle time before an attachment is evicted and its window and buffer released | 10 minutes; it never stops a coordinator | ADR 0032 | | Sessions activated per daemon lifetime | 64; the 65th activation refused, the remedy being to restart the daemon. It is per lifetime rather than concurrent because nothing deactivates a coordinator, which is recorded as a limitation | ADR 0032 | | Recorded session index entries per root | 4,096; a root whose directory holds more refused at daemon start. The ceiling is on recorded entries and never on reachability: a session reached by ID beyond it is activated and not recorded, and the listing carries `index_full` | ADR 0032 | @@ -2404,6 +2434,14 @@ line; M5 introduces none of its own. | Credential frame cap | 69,632 bytes | ADR 0034, which is where the frame's shape is written; no ADR 0019 file states it | | `req_llm` version pin | `~> 1.24.0` | Maintainer decision 4B of 2026-09-20, a **plan** decision. A dependency pin is not a contract number: it binds what this milestone builds against and is changed by an ordinary reviewed dependency change, not by an ADR amendment | +**Three rows say 512 and they are three different bounds**, which is worth one +sentence because "one number, one ADR" would otherwise read as one limit: 512 +*attachments* per daemon (ADR 0032 `:720`), 512 *MiB* of retained encoded +events across every buffer and window (`:147`, `:716`), and at most 512 +concurrent *lease owners* (`:222`), the last deliberately reusing the +attachment number rather than introducing a third limit that could drift from +it. + Count and byte ceilings apply together: an event that would exceed either triggers the stated detachment, eviction or refusal before the ceiling is crossed. These are retained-payload ceilings, not an exact BEAM RSS promise; diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 5382b2e09..aba16f17a 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -54,7 +54,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits an abort with the cause `operator_shutdown` for every active session before cancelling anything, drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -367,10 +367,14 @@ did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. **The drain has a mechanism, and it is core's.** M5 adds `quiesce/2` to -`Loopex.Runtime`, and it has three parts. It **durably admits an abort** -carrying the cause `operator_shutdown` for every active session, because ADR -0023 fixes that only a durable `session.abort` cancels and nothing may infer -cancellation from a signal. It then drives what is in flight through the +`Loopex.Runtime`, and it has three parts. It **durably admits the existing +abort command** for every active session, because ADR 0023 fixes that only a +durable `session.abort` cancels and nothing may infer cancellation from a +signal. The record it writes is the one a client's own abort writes, with no +shutdown-specific field: the cause an operator wants is already reported twice +on the way out, in `daemon.stopping` and on `stderr`, and a journal that says +the same thing a third time would have cost a persistent-schema decision for +nothing. It then drives what is in flight through the cancellation sequence a coordinator already runs for an abort, under the bounds core already derives from that session's committed cleanup grace. And at the deadline it **fences and terminates** every coordinator that has not @@ -651,7 +655,7 @@ The documented recovery is to retire the root — stop the daemon, move the root aside, start a fresh one — after which a session in the retired root is reached only by reopening that root. -The private journal, its adapter and its format are unchanged, so moving a +The private journal and its format are unchanged, and its adapter is unchanged in behaviour — it gains one read-only call reporting whether it still holds its marker, and writes nothing new — so moving a state root between the daemon and the foreground surfaces is stopping one and starting the other. That is also the rollback: dropping back to `0.1.0` means stopping the daemon and using the M4 foreground server and CLI on the same From 57ae2deb28f39b137096d7b5ef00047537af79eb Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 09:13:56 -0700 Subject: [PATCH 087/585] plan(M5): say whose command ID the shutdown abort carries Q-1. `propose_new/3` writes `"command_id" => command.command_id` (session_state.ex:1686) and command identity is load-bearing across this set -- `create_command_absent?/2` decides freshness by it, replay is idempotent by it, a resume must carry a fresh one -- but nothing said where the drain's abort gets one. A client's abort carries the client's ID; quiesce has no client. Core mints it, fresh per session per drain, with the generator core already uses for identifiers of its own: `:crypto.strong_rand_bytes(16)` rendered as lowercase base16, exactly as a runtime ID is formed (session_directory.ex:545-548) and a journal token is formed (journal.ex:360), the same 128-bit entropy class ADR 0033 fixes for a writer epoch. That is 32 bytes, well inside the 256-byte bound `valid_identifier?/1` applies (control.ex:40, :1726). No new generator and no new format. It is never derived from or shared with a client's ID: deriving would make a shutdown abort forgeable by a client that guessed the derivation, and sharing would collide with a command somebody actually sent. At 128 bits a collision is the same negligible class as two client IDs colliding. Replay consequence stated plainly: every drain admits a new abort, because a drain is not a client command and nothing holds its ID to retry it; one session cannot be drained twice in a lifetime, since the daemon exits when the drain is done; and across lifetimes an earlier shutdown abort is history like any other admitted command. Core change 4's definition and the Concept's drain paragraph carry the clause, and the in-flight witness asserts the abort's `command_id` is one no client in the case sent and differs between two sessions drained by the same stop. --- docs/plans/M5-technical.md | 40 ++++++++++++++++++++++++++++++++++++-- docs/plans/M5.md | 6 ++++-- 2 files changed, 42 insertions(+), 4 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 283086f5b..2c5a76d2d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -132,7 +132,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -1659,6 +1659,39 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: (`:1750-1761`) — the right answer for an idle session, needing no special case. + + **Whose `command_id` that abort carries, which the set did not say.** + `propose_new/3` writes `"command_id" => command.command_id` + (`session_state.ex:1686`), and command identity is load-bearing everywhere + else in this plan — `create_command_absent?/2` decides freshness by it, + replay is idempotent by it, and a resume is required to carry a *fresh* + one. A client's abort carries the client's ID. Quiesce has no client, so + the question has to be answered rather than inherited. + + **Core mints it, fresh per session per drain, with the generator core + already uses for identifiers it mints itself**: `:crypto.strong_rand_bytes(16)` + rendered as lowercase base16, which is exactly how a runtime ID is formed + (`session_directory.ex:545-548`) and how a journal token is formed + (`journal.ex:360`), and the same 128-bit entropy class ADR 0033 fixes for a + writer epoch. The result is a 32-byte identifier, well inside the + 256-byte bound `valid_identifier?/1` applies (`control.ex:40`, `:1726`). + No new generator, no new format. + + **It is never derived from, nor shared with, a client's ID.** Deriving one + would make a shutdown abort forgeable by a client that could guess the + derivation; sharing one would make a drain collide with a command somebody + actually sent. Because it is 128 bits of fresh randomness, a collision with + a client's ID is the same negligible class as two client IDs colliding, + which this system already lives with everywhere identifiers are minted. + + **What that means for replay, said plainly: every drain admits a new + abort.** A drain is not a client command and is never replayed — nothing + retries it under its original ID, because no client holds that ID. Nor can + one session be drained twice in a lifetime: the daemon exits when the drain + is done. Across lifetimes, a session's earlier shutdown abort is simply + history, exactly as a client's earlier abort is, and the next daemon reads + it as a command already admitted rather than as one to repeat. + **Nothing new is journaled, and that is the decision.** The abort quiesce admits is the abort that exists: the same command, the same record, the same fields a client's `session.abort` writes today. **No `cause` field is @@ -2050,7 +2083,10 @@ the cause and try again without a recovery step. cancellation, because ADR 0023 admits no cancellation that was not commanded — and both assert it is **the record a client's own `session.abort` writes**, field for field, with no shutdown-specific field - on it. The operator learns the cause from `daemon.stopping` and from + on it. Both also assert its `command_id` is **an identifier no client in + the case ever sent**, and that it differs between two sessions drained by + the same stop, so a shared or derived ID would fail rather than pass + quietly. The operator learns the cause from `daemon.stopping` and from `stderr`, not from the journal. *It settles.* A daemon with a dispatched tool effect that **can** be diff --git a/docs/plans/M5.md b/docs/plans/M5.md index aba16f17a..20893b5b0 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -370,8 +370,10 @@ when its `terminate/2` releases the marker. `Loopex.Runtime`, and it has three parts. It **durably admits the existing abort command** for every active session, because ADR 0023 fixes that only a durable `session.abort` cancels and nothing may infer cancellation from a -signal. The record it writes is the one a client's own abort writes, with no -shutdown-specific field: the cause an operator wants is already reported twice +signal. The record it writes is the one a client's own abort writes, under a +`command_id` **core mints fresh for that session and that drain**, with the +generator core already uses for identifiers of its own and never derived from +or shared with a client's; and with no shutdown-specific field: the cause an operator wants is already reported twice on the way out, in `daemon.stopping` and on `stderr`, and a journal that says the same thing a third time would have cost a persistent-schema decision for nothing. It then drives what is in flight through the From c54ccc36a88401cd38daef6e68d2795edcd2167b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:03:10 -0700 Subject: [PATCH 088/585] plan(M5): name both generations loopex.experimental/N Two maintainer decisions of 2026-09-20. D1, the generation naming. The daemon serves `loopex.experimental/2` as ADR 0032 already says, and M5 renames the released generation-1 string `loopex.session.v1-experimental` to `loopex.experimental/1` under the 0.x policy the vision states -- experimental APIs may break in a minor release with explicit migration notes (vision-technical.md 24.2) -- `0.2.0` being a minor release. The reason recorded is collision: the vision reserves "public protocol v1" for the stable protocol, which cannot freeze before the daemon, the ACP mapping and extension namespaces, so an experimental line numbered v1 would leave the first stable release explaining why its v1 is not the one that shipped. Workstream 3 already restructures `LoopexProtocol.Session` per generation, which is where the string lives, so this is the cheap moment. Keeping both shapes is recorded as rejected. The cost is stated where it lands: generation 1's methods, record families, error codes and limits are unchanged, but the generation is an input to `schema_digest/0`, so its schema digest and its schema- and vectors-file digests are **re-pinned**. Every place the set said those pins were preserved or untouched now says they move and says why -- M5.md outcome 2, evidence row 2, ADR 0032-technical at the digest table and the pinning paragraph -- and the witness asserts the other digest inputs are byte-identical, so a changed method list still fails there. The migration is one string: a 0.1.0 client is refused `unsupported_generation` and sends the new name, nothing else about it changes, and the repository's Node client is updated in the same change. No compatibility mode is offered. Rollback is unaffected, a generation string being negotiated and never persisted. D2, the operator page. The closure obligations now require `docs/operator/daemon.md` to state the maximum graceful stop, that a shorter service-manager timeout makes the stop a forced shutdown, and the usual millisecond Store release against its 30 s ceiling; the five documents carrying the generation string are named there too. The docs gate derives its checklist from every tracked file under `docs/operator` and `docs/developer`, so neither can be marked reviewed-unchanged by accident. Drafting the page now is recorded as rejected. Two findings from verifying the brief. The string lives in **fourteen** files, not thirteen: the list omitted `CHANGELOG.md`, whose entry records what 0.1.0 shipped and is therefore deliberately not rewritten -- the rename becomes a 0.2.0 entry instead. And no accepted decision binds the literal: it appears in no accepted ADR and nowhere in the vision pair, so ADR 0023 stays accepted and unedited and no amendment path is needed. --- ...tachment-residency-and-replay-technical.md | 33 +++-- ...-daemon-attachment-residency-and-replay.md | 8 ++ docs/plans/M5-technical.md | 123 +++++++++++++++++- docs/plans/M5.md | 58 ++++++++- 4 files changed, 205 insertions(+), 17 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 86c2da1f0..4bd329c9a 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -230,8 +230,15 @@ ordered list would make the served contract differ from the digest the server advertises, which is exactly the drift the digest exists to catch. The generation-2 literal the conformance module pins is the digest of the contract *including* all four changes, and a build missing any of them computes a -different value and fails there. Generation 1's digest is untouched, since -generation 1 gains no method, no record family and no error code. +different value and fails there. Generation 1 gains no method, no record family and no error code — but its +digest is **not** untouched, because M5 renames its generation string from +`loopex.session.v1-experimental` to `loopex.experimental/1` and the generation +is the digest's first input. That rename is the plan's decision, taken under +the vision's 0.x experimental policy; this ADR records its consequence here, +which is that generation 1's schema digest is recomputed and re-pinned +alongside generation 2's, with every other input to it byte-identical. The +negotiation list a server advertises therefore carries `loopex.experimental/1` +and `loopex.experimental/2`, and neither carries the old name. ### Generation 2, at the precision literal vectors need @@ -644,10 +651,14 @@ value: the digest is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the generation and the method list, so it cannot and must not equal generation 1's. It is written out as a literal beside generation -1's, and generation 1's literal digest, schema-file digest and vectors-file -digest are asserted unchanged in the same place, so an accidental edit to -generation 1's contract fails there rather than silently renaming what -existing clients agreed to. The generation-2 schema and its +1's. Generation 1's three literals are **re-pinned** in the same place rather +than asserted unchanged, because the rename above moves them, and the case +that pins them asserts every *other* input to generation 1's digest — its +ordered methods, record families, error codes and limits — is byte-identical +to what `0.1.0` served. That is what still catches an accidental edit to +generation 1's contract: the inputs are compared, not just the result, so a +changed method list fails there instead of hiding behind a digest that was +expected to move anyway. The generation-2 schema and its vectors are new files beside generation 1's, as `apps/loopex_protocol/priv/schema/loopex-experimental-2.json` and `apps/loopex_protocol/priv/vectors/loopex-experimental-2.json`, reviewed with @@ -656,9 +667,13 @@ written into the conformance module beside the two generation 1 already pins — so an independent client can fetch either file and verify its bytes, and an edit to a generation-2 file fails the same way an edit to a generation-1 file does. The digests are computed and pinned when the files are written; -generation 1's bytes and its two pinned digests are untouched. A -negotiation vector proves selection from a list that also names generation 1 -and refusal of a generation-1-only list. The M4 foreground server keeps +generation 1's two file digests are **re-pinned** with its schema digest, +because the rename above changes the bytes of the files that carry the +generation string; everything those files say about methods, records, errors +and limits is unchanged. A negotiation vector proves selection from a list +that also names generation 1 under its new string, refusal of a list naming +only generation 1, and refusal of a list naming only the retired +`loopex.session.v1-experimental`. The M4 foreground server keeps serving generation 1 only, with its one-attachment-per-process rule. ### Attachment lifecycle diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index f14a23bc8..92fd47d03 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -39,6 +39,14 @@ generation, `loopex.experimental/2`, which adds `session.list`, `daemon.status`, the two control methods, the writer-epoch field ADR 0033 names, and one notification record family, `daemon.stopping`, carrying the reason a daemon is going away. +The milestone that +brings this ADR also renames the released generation-1 string to +`loopex.experimental/1`, so the two generations are named on one scheme and +neither claims the `v1` the vision reserves for the stable protocol; that +rename is the plan's decision under the 0.x experimental policy, and its +consequence here is that generation 1's pinned digests are recomputed with +its new name while everything else about generation 1 stays as it is. + That record is a new record family, so it is part of what generation 2's schema digest is taken over; its delivery is one bounded best-effort write attempt into the connection's existing output buffer, after which the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 2c5a76d2d..814729f90 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -133,7 +133,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's bytes, digest, method inventory and limits are proved unchanged in the same module and at their own literals — the `3a17…08f4` schema digest, the schema file digest and the vectors file digest the conformance module already pins — so the generation-2 work is proved additive rather than asserted to be. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module, so the generation-2 work is proved additive rather than asserted to be — but its **three pinned literals move, and the case asserts the move rather than the old equality**: the generation string is renamed to `loopex.experimental/1`, the string is an input to `schema_digest/0`, so the `3a17…08f4` schema digest, the schema file digest and the vectors file digest are all recomputed and **re-pinned** in this change. The case asserts each new literal against a freshly computed value and asserts the contract inputs other than the name are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -263,7 +263,33 @@ executor to the provider child, the indexes `docs/operator/README.md`, `docs/developer/README.md`, `docs/README.md` and `README.md`, and `CHANGELOG.md`. Outcome 6 adds the operator's credential sentence and the developer note on host composition to the pages that describe -provider configuration. Every other tracked file under `docs/operator/` and +provider configuration. + +**Two page-level obligations are named here rather than left to the writer**, +because both are facts an operator cannot derive from the software and a +reviewer can check against this sentence at closure. + +- **`docs/operator/daemon.md` must state the maximum graceful stop**: the + derived session drain, plus the one shared non-Store teardown budget, plus + the fixed 30-second Store phase — and, with it, that a shorter external + service-manager timeout turns the stop into a **forced shutdown**, where + work that would have settled does not and the writer marker may be left for + the next daemon's verified recovery. It must also distinguish the **usual + millisecond** Store release from that 30-second **safety ceiling**, so the + number is read as a bound on the worst case rather than as the cost of every + stop. Nothing is written until the implementation exists; this row is what + makes closure unable to forget it. +- **`docs/developer/app-server-protocol.md`, its companion, + `docs/developer/compatibility-surfaces.md`, `docs/developer/agent-context-map.md` + and `docs/operator/app-server.md` must carry the renamed generation string** + and the one-line migration it implies. + +Both are covered by the docs gate, which derives its checklist from +`git ls-files -- docs/operator docs/developer` over **every** tracked file +rather than a Markdown filter, so neither page can be marked reviewed-unchanged +by accident. + +Every other tracked file under `docs/operator/` and `docs/developer/` is read at the candidate and left unchanged only deliberately, and the derived checklist in Outcome 5's evidence row is what makes that auditable rather than asserted. @@ -303,6 +329,57 @@ events, snapshots, artifact formats and the executor protocol are unchanged. Source `VERSION` is distinct from protocol generation, provider build and schema digest. + +**The generation strings are renamed, and generation 1's is one of them.** +M5 serves `loopex.experimental/2` on the socket — the name ADR 0032 already +fixes — and **renames the released generation-1 string +`loopex.session.v1-experimental` to `loopex.experimental/1`**. That is a +break in an experimental surface, taken deliberately under the 0.x policy the +vision states: "Experimental APIs may break in a minor release with explicit +migration notes" (`vision-technical.md` § 24.2), and `0.2.0` is a minor +release. + +The reason is collision rather than tidiness. The vision reserves "public +protocol v1" for the *stable* protocol, which cannot freeze until the daemon, +the ACP mapping and extension namespaces exist. An experimental line numbered +`v1` and then `/2` would be two numbering schemes racing toward the same name, +and the first stable release would have to explain why its `v1` is not the +`v1` that shipped in 0.1.0. `loopex.experimental/N` numbers the experimental +line on its own and leaves the stable name unclaimed. + +**No accepted decision binds the literal, so this is a plan decision and not +an amendment.** That was checked rather than assumed: the string +`loopex.session.v1-experimental` appears in **no** accepted ADR and nowhere in +the vision pair — ADR 0023 fixes that client and server "agree on one +experimental protocol generation, exact" and that "source version and protocol +generation are independent" (`0023-…md:116-118`) without ever writing the +name, and ADR 0024 does not mention generations at all. The only ADR that +carries a generation string is ADR 0032, which is Proposed with this +milestone and states the rename itself. So ADR 0023 stays accepted and +unedited, and nothing here needs an amendment path. + +**Now is the cheapest moment**, which is the other half of the decision. +Workstream 3 already restructures `LoopexProtocol.Session` from one generation +in module attributes into one module serving two, with both digests pinned +side by side; the string is a module attribute in exactly that restructuring. +Renaming later would mean a second pass over the same module, the same +vectors, the same clients and the same documents. + +**The rejected option is recorded:** keep `loopex.session.v1-experimental` +beside `loopex.experimental/2`. It was rejected because the two shapes would +then coexist for as long as generation 1 is served — which is the whole of +0.2.x and beyond — so every client, document and vector would carry both +conventions, and the collision above would still be waiting at the freeze. + +**What that costs, exactly.** Generation 1's **contract** is unchanged: the +same methods, the same record families, the same error codes, the same limits. +What changes is its **name**, and the name is an input to +`LoopexProtocol.Session.schema_digest/0` — so generation 1's schema digest +changes with it, and so do the schema and vectors files that carry the string. +All of them are **re-pinned** in the same change; none of them is "preserved". +The plan says so wherever it used to say the generation-1 pins were untouched, +because a reader who trusts that sentence would read a failing build as drift. + Outcome 6 changes no public surface. The `Loopex.Model` callbacks, the private provider codec's version and frame kinds, the build manifest and ADR 0019's process topology are all unchanged. Its one compatibility effect is on host @@ -331,6 +408,48 @@ the operator page must explain, because it is what an operator meets when a root grew past the ceiling under an earlier process. A session in a retired root is reached only by reopening that root. + +**The one migration note M5 owes, and it is one string.** A `0.1.0` client +sends `loopex.session.v1-experimental` in its `initialize` generations list. +Against a `0.2.0` server that list has no common generation, so the server +refuses with `unsupported_generation` — the refusal ADR 0023 already defines +for exactly this — and the client's remedy is to send `loopex.experimental/1` +instead. Nothing else about that client changes: same framing, same methods, +same limits, same records. **The repository's own Node client is updated in +the same change**, so the independent-client evidence is written against the +new string rather than against a shim. + +There is no compatibility mode and none is offered: accepting both strings for +one generation would put two names on one contract, which is the thing this +rename exists to stop, and it would have to be removed later anyway. + +**Rollback is unaffected by the rename**, because a generation string is +negotiated and never persisted. A root written by a `0.2.0` daemon carries no +generation name anywhere, so removing the daemon restores the `0.1.0` +foreground server on the same root exactly as it would without this decision; +what a `0.1.0` *client* then talks to is a `0.1.0` server, which speaks the old +string again. + +**The fourteen files that carry the string today**, named here so workstream 3 +can be checked against a list rather than a grep: +`apps/loopex_app_server/lib/loopex_app_server.ex` and its three tests +(`app_server_test.exs`, `initialization_test.exs`, `stdio_probe_test.exs`); +`apps/loopex_protocol/lib/loopex_protocol/session.ex:32` with +`public_schema_conformance_test.exs` and `session_schema_test.exs`; +`clients/node/loopex-client.mjs`; and the documents +`docs/developer/agent-context-map.md`, +`docs/developer/app-server-protocol.md` and its technical companion, +`docs/developer/compatibility-surfaces.md`, and `docs/operator/app-server.md`. +The documents are closure obligations under the docs gate, which reads every +tracked file in `docs/operator` and `docs/developer`, so none can be missed. + +**`CHANGELOG.md` is the fourteenth and is deliberately *not* rewritten.** It +carries the string in the entry that records what `0.1.0` shipped, and that +entry stays true: `0.1.0` did serve `loopex.session.v1-experimental`. The +rename is recorded as a `0.2.0` entry instead. An earlier list of these files +had thirteen and omitted it, which would have left the rename either missing +from the changelog or silently editing history. + Rollback to `0.1.0` is stopping the daemon. Removing it restores the M4 foreground server and the CLI on the same root with no durable dependency on residency, index or lease state, because none of those is persisted. A diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 20893b5b0..cca36c0c0 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -55,7 +55,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | | 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | -| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's bytes and digest are proved unchanged, a generation-1-only client refused, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | +| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its three pinned literals are re-pinned for the generation rename, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | @@ -518,9 +518,38 @@ implementation that depends on it, not before unrelated work. | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | One daemon-owned in-memory controller lease per session, held by its own lease-owner process, with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, and cross-process abort through the core's own cancellation | 3 | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | The provider credential is named by an opaque token bound at composition and **resolved per invocation**, routed by a host-owned registry that holds routing only, and resolved from a host-owned custody process inside the sender that writes it to the child's private channel, after the child proves its identity and before the invocation frame; the token's shape, registry and custody ownership, rotation, the guardian-enforced deadline, `:unavailable` on loss with no reconstruction, and every failure are exact; the adapter reads no environment variable for a credential, while the launcher's ADR 0019 scrubbing read stays and is proved never consulted for one | 6 | -**Two design decisions are settled here rather than in an ADR**, because both -are internal structure that no public or durable contract depends on. They are -recorded because getting either wrong would be expensive to discover later. +**Three design decisions are settled here rather than in an ADR**, because +each is internal structure or a naming choice that no accepted decision binds. +They are recorded because getting any of them wrong would be expensive to +discover later. + +**The protocol generations are named on one scheme, and generation 1 is +renamed to match.** The daemon serves `loopex.experimental/2`, and M5 renames +the released generation-1 string `loopex.session.v1-experimental` to +**`loopex.experimental/1`**. This is a break in an experimental surface, taken +under the policy the vision already states — experimental APIs may break in a +minor release with explicit migration notes — and `0.2.0` is a minor release. + +The reason is that `v1` is reserved. The vision keeps "public protocol v1" for +the *stable* protocol, which cannot freeze before the daemon, the ACP mapping +and extension namespaces exist; an experimental line that had already spent +`v1` would leave the first stable release explaining why its `v1` is not the +one that shipped in `0.1.0`. `loopex.experimental/N` numbers the experimental +line on its own and leaves the stable name free. Doing it now is the cheap +moment: workstream 3 already restructures `LoopexProtocol.Session` per +generation, which is where the string lives. + +**Keeping `loopex.session.v1-experimental` beside `loopex.experimental/2` was +rejected**, because the two shapes would then coexist for as long as +generation 1 is served, and the collision above would still be waiting at the +freeze. The migration is one string, and the companion states it: a `0.1.0` +client is refused `unsupported_generation` and sends the new name; generation +1's contract is otherwise unchanged, while its pinned digests are re-pinned +because the generation name is an input to them; the repository's own Node +client is updated in the same change. No accepted ADR binds the literal, so +this is a plan decision rather than an amendment — ADR 0023 fixes that a +generation is negotiated exactly and that source version and generation are +independent, and never writes the string. **The daemon owns its own lifetime, through an owner process rather than a supervisor.** Its top-level component is one `GenServer` that traps exits and @@ -712,7 +741,13 @@ lease — and the companion's rejoin order says where each part goes. and `negotiate/2` matching a single `@generation`. Serving two generations from one module — and pinning both digests side by side in the conformance module — means restructuring it per generation, which is where that - restructuring is owned. Then the daemon's side: the + restructuring is owned. **The generation rename lands here too**, in that + same restructuring: `loopex.experimental/1` replacing + `loopex.session.v1-experimental` across the fourteen files that carry it + today — the app-server module and its three tests, the protocol module and + its two suites, the Node client, five documents, and a new `CHANGELOG` + entry rather than an edit to the `0.1.0` one — with generation 1's three + pinned literals recomputed and re-pinned as part of it. Then the daemon's side: the listener, its owner-only peer check and path bound, the startup ordering and its readiness line, signal handling and the orderly-shutdown sequence, the exit-status classes, `loopex daemon`, `loopex attach` and the live form @@ -794,7 +829,7 @@ that adds the tests it names. | # | State | Evidence | | --- | --- | --- | | 1 | Open | No daemon exists. Session lifetime with zero attachments, marker-first startup with explicit stale-writer recovery, store-loss shutdown, capacity as store loss, lazy activation and its ceilings, the index crash cut, bounded listing and reopening under the foreground server are its separate witnesses | -| 2 | Open | No socket transport exists; generation 2 has no schema or vectors yet | +| 2 | Open | No socket transport exists; generation 2 has no schema or vectors yet, and both generations still carry the released `loopex.session.v1-experimental` name the rename replaces | | 3 | Open | No controller lease, writer epoch or takeover exists above core | | 4 | Open | Core replaces an existing same-session attachment today; no independent concurrent attachments, resident window, socket output buffer or eviction exists | | 5 | Open | No two-process workflow, daemon operator guide or `0.2.0` source archive exists | @@ -867,6 +902,17 @@ it displaced and why: | 3 | `ProviderLauncher` keeps its launch-time environment enumeration for ADR 0019 scrubbing; the prohibition narrows to credential reads | Deleting the enumeration for a fixed closed removal list, and before that moving the snapshot to composition — both of which weakened an accepted decision | | 4 | The `req_llm` upgrade is explicit M5 scope pinned at `~> 1.24.0`, separate from ADR 0035 and adding no M5 call path | Leaving the pin loose at `~> 1.24`, and running one bounded ADR 0035 experiment inside M5's required release check | +**Two further decisions of 2026-09-20, recorded after those four.** The +maintainer settled the **protocol generation naming** — both generations on +`loopex.experimental/N`, which renames the released generation-1 string under +the 0.x experimental policy — and made the **daemon operator page's stop bound +a closure obligation**: that page must state the maximum graceful stop, what a +shorter service-manager timeout turns a stop into, and the usual millisecond +Store release against its thirty-second ceiling. Both are written into the +sections they govern. Drafting that page now was rejected, because it would +document a component that does not exist; the obligation is what carries it to +closure instead. + ADR 0031 carries no decision from this round and is unchanged by it. ADR 0035 remains Proposed and wholly deferred; decision 4 neither accepts nor partially implements it. ADRs 0019 and 0030 remain Accepted and unchanged, and nothing From 9e493721f1e26977deea34a51b2ce636d58ef89f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:09:44 -0700 Subject: [PATCH 089/585] plan(M5): one pin moves, and the manifests already agree M-1, verified at source before editing. `schema_digest/0` hashes five inputs including `@generation` (session.ex:192-199), so the rename moves exactly one pinned literal: the `3a17...08f4` schema digest at public_schema_conformance_test.exs:291-292. The two file digests at :297-298 do not move. Reading the manifests as JSON confirms why: both `priv/schema/loopex-experimental-1.json` and `priv/vectors/loopex-experimental-1.json` contain zero occurrences of `loopex.session.v1-experimental` and already declare `"generation": "loopex.experimental/1"`, the schema manifest also declaring `server_records.initialized.selected_generation` as the same. Every place that said three literals move now says one, and names it. That turns out to be the strongest argument for the decision, so it is stated as such in M5.md's decision text: the released surface already disagrees with itself. session.ex:32 serves the old name and the conformance module pins it at :282, while the digest-pinned manifests those same independent clients fetch declare the new one. Nothing catches it, because the conformance test binds each manifest by file digest and never compares its `generation` with `Session.generation()`. The rename therefore closes a live discrepancy in a released surface rather than opening one, and the manifests are what the code is made to agree with rather than files to edit -- so the fourteen-file list says they are not among them. The Outcome 2 witness gains the assertion whose absence let the drift live: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the same way. The progress notes record the discrepancy as found 2026-09-20 during planning review, with no change made to `0.1.0`: M5's rename resolves it. --- ...tachment-residency-and-replay-technical.md | 28 +++++++----- docs/plans/M5-technical.md | 43 +++++++++++++++---- docs/plans/M5.md | 36 +++++++++++++--- 3 files changed, 83 insertions(+), 24 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 4bd329c9a..1c92d33ca 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -235,8 +235,11 @@ digest is **not** untouched, because M5 renames its generation string from `loopex.session.v1-experimental` to `loopex.experimental/1` and the generation is the digest's first input. That rename is the plan's decision, taken under the vision's 0.x experimental policy; this ADR records its consequence here, -which is that generation 1's schema digest is recomputed and re-pinned -alongside generation 2's, with every other input to it byte-identical. The +which is that generation 1's **schema digest** — and only that — is +recomputed and re-pinned alongside generation 2's, with every other input to +it byte-identical. Its two published manifests are not touched: they already +declare `loopex.experimental/1`, so the rename makes the code agree with them +rather than changing them. The negotiation list a server advertises therefore carries `loopex.experimental/1` and `loopex.experimental/2`, and neither carries the old name. @@ -651,11 +654,12 @@ value: the digest is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the generation and the method list, so it cannot and must not equal generation 1's. It is written out as a literal beside generation -1's. Generation 1's three literals are **re-pinned** in the same place rather -than asserted unchanged, because the rename above moves them, and the case -that pins them asserts every *other* input to generation 1's digest — its -ordered methods, record families, error codes and limits — is byte-identical -to what `0.1.0` served. That is what still catches an accidental edit to +1's. Generation 1's **schema digest** is re-pinned in the same place rather +than asserted unchanged, because the rename above moves it — its two +manifest file digests do not move, those files already carrying the new +name — and the case that pins it asserts every *other* input to generation 1's +digest, its ordered methods, record families, error codes and limits, is +byte-identical to what `0.1.0` served. That is what still catches an accidental edit to generation 1's contract: the inputs are compared, not just the result, so a changed method list fails there instead of hiding behind a digest that was expected to move anyway. The generation-2 schema and its @@ -667,10 +671,12 @@ written into the conformance module beside the two generation 1 already pins — so an independent client can fetch either file and verify its bytes, and an edit to a generation-2 file fails the same way an edit to a generation-1 file does. The digests are computed and pinned when the files are written; -generation 1's two file digests are **re-pinned** with its schema digest, -because the rename above changes the bytes of the files that carry the -generation string; everything those files say about methods, records, errors -and limits is unchanged. A negotiation vector proves selection from a list +generation 1's two file digests are **unchanged**, because those manifests +already carry `loopex.experimental/1` and never carried the retired name; only +its schema digest moves, the generation being one of that digest's inputs. +Every served generation is additionally asserted to have `Session.generation()` +equal to its own manifest's `/generation`, which is the check whose absence +let the released code and the released manifests disagree in the first place. A negotiation vector proves selection from a list that also names generation 1 under its new string, refusal of a list naming only generation 1, and refusal of a list naming only the retired `loopex.session.v1-experimental`. The M4 foreground server keeps diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 814729f90..f90412015 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -133,7 +133,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module, so the generation-2 work is proved additive rather than asserted to be — but its **three pinned literals move, and the case asserts the move rather than the old equality**: the generation string is renamed to `loopex.experimental/1`, the string is an input to `schema_digest/0`, so the `3a17…08f4` schema digest, the schema file digest and the vectors file digest are all recomputed and **re-pinned** in this change. The case asserts each new literal against a freshly computed value and asserts the contract inputs other than the name are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -373,12 +373,37 @@ conventions, and the collision above would still be waiting at the freeze. **What that costs, exactly.** Generation 1's **contract** is unchanged: the same methods, the same record families, the same error codes, the same limits. -What changes is its **name**, and the name is an input to -`LoopexProtocol.Session.schema_digest/0` — so generation 1's schema digest -changes with it, and so do the schema and vectors files that carry the string. -All of them are **re-pinned** in the same change; none of them is "preserved". -The plan says so wherever it used to say the generation-1 pins were untouched, -because a reader who trusts that sentence would read a failing build as drift. +What changes is its **name** — and the name is one of the five inputs +`LoopexProtocol.Session.schema_digest/0` hashes (`session.ex:192-199`), so +generation 1's **schema digest** changes with it and is re-pinned. Exactly one +pin moves. + +**The two manifests do not move, and the reason is the strongest argument for +this decision.** `apps/loopex_protocol/priv/schema/loopex-experimental-1.json` +and `apps/loopex_protocol/priv/vectors/loopex-experimental-1.json` — the files +an independent client fetches and verifies, pinned by file digest at +`public_schema_conformance_test.exs:297-298` — contain **no occurrence of +`loopex.session.v1-experimental`**. They already declare +`"generation": "loopex.experimental/1"`, and the schema manifest also declares +`server_records.initialized.selected_generation` as `loopex.experimental/1`. + +So the released surface is **already inconsistent with itself**: `session.ex:32` +serves `loopex.session.v1-experimental`, the conformance module pins that +string at `:282`, and the digest-pinned manifests those same clients read say +`loopex.experimental/1`. Nothing catches it, because the conformance test pins +each manifest by its **file digest** and never compares the manifest's +`/generation` with `Session.generation()`. + +That reframes the rename. It is not a break introduced for tidiness; it is the +change that makes the **code agree with the artifacts already published beside +it**, and it closes a live discrepancy in a released surface rather than +opening one. The manifests are the thing being conformed to, not files to +edit. + +The plan says all of this wherever it used to say the generation-1 pins were +untouched, because a reader who trusts that sentence would read a failing +build as drift — and equally, a reader told that three pins move would go +looking for two changes that are not there. Outcome 6 changes no public surface. The `Loopex.Model` callbacks, the private provider codec's version and frame kinds, the build manifest and ADR 0019's @@ -435,7 +460,9 @@ can be checked against a list rather than a grep: `apps/loopex_app_server/lib/loopex_app_server.ex` and its three tests (`app_server_test.exs`, `initialization_test.exs`, `stdio_probe_test.exs`); `apps/loopex_protocol/lib/loopex_protocol/session.ex:32` with -`public_schema_conformance_test.exs` and `session_schema_test.exs`; +`public_schema_conformance_test.exs` and `session_schema_test.exs` — **and +not the two `priv` manifests**, which already carry the new name and are what +the code is being made to agree with; `clients/node/loopex-client.mjs`; and the documents `docs/developer/agent-context-map.md`, `docs/developer/app-server-protocol.md` and its technical companion, diff --git a/docs/plans/M5.md b/docs/plans/M5.md index cca36c0c0..ad14949ae 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -55,7 +55,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | | 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | -| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its three pinned literals are re-pinned for the generation rename, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | +| 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | @@ -539,13 +539,26 @@ line on its own and leaves the stable name free. Doing it now is the cheap moment: workstream 3 already restructures `LoopexProtocol.Session` per generation, which is where the string lives. +**The strongest argument for it, found while planning this, is that the +released surface already disagrees with itself.** The two manifests an +independent client fetches and verifies — +`apps/loopex_protocol/priv/schema/loopex-experimental-1.json` and the matching +vectors file — **already declare `loopex.experimental/1`** and contain no +occurrence of `loopex.session.v1-experimental`, while the code that serves +them declares the old name. Nothing catches it, because the conformance module +pins each manifest by file digest and never compares the manifest's +`generation` with the one the code reports. So this rename does not introduce +a break in a consistent surface; it **closes a live discrepancy in a released +one**, making the code agree with artifacts that were published beside it. The +companion adds the missing assertion, so generation 2 cannot repeat it. + **Keeping `loopex.session.v1-experimental` beside `loopex.experimental/2` was rejected**, because the two shapes would then coexist for as long as generation 1 is served, and the collision above would still be waiting at the freeze. The migration is one string, and the companion states it: a `0.1.0` client is refused `unsupported_generation` and sends the new name; generation -1's contract is otherwise unchanged, while its pinned digests are re-pinned -because the generation name is an input to them; the repository's own Node +1's contract is otherwise unchanged, while its schema digest is re-pinned +because the generation name is one of that digest's inputs; the repository's own Node client is updated in the same change. No accepted ADR binds the literal, so this is a plan decision rather than an amendment — ADR 0023 fixes that a generation is negotiated exactly and that source version and generation are @@ -746,8 +759,9 @@ lease — and the companion's rejoin order says where each part goes. `loopex.session.v1-experimental` across the fourteen files that carry it today — the app-server module and its three tests, the protocol module and its two suites, the Node client, five documents, and a new `CHANGELOG` - entry rather than an edit to the `0.1.0` one — with generation 1's three - pinned literals recomputed and re-pinned as part of it. Then the daemon's side: the + entry rather than an edit to the `0.1.0` one — with generation 1's schema + digest recomputed and re-pinned as part of it, and its two manifest file + digests left alone, because those manifests already carry the new name. Then the daemon's side: the listener, its owner-only peer check and path bound, the startup ordering and its readiness line, signal handling and the orderly-shutdown sequence, the exit-status classes, `loopex daemon`, `loopex attach` and the live form @@ -913,6 +927,18 @@ sections they govern. Drafting that page now was rejected, because it would document a component that does not exist; the obligation is what carries it to closure instead. +**One `0.1.0` defect was found during that review and is recorded rather than +patched.** On 2026-09-20, checking what the generation rename would cost, the +released protocol surface was found to disagree with itself: `session.ex:32` +serves `loopex.session.v1-experimental` and the conformance module pins that +string, while the two digest-pinned manifests published for independent +clients already declare `loopex.experimental/1`. The conformance test binds +each manifest by file digest and never compares its `generation` with the +code's, which is why nothing noticed. **No change is made to `0.1.0`**: the +defect is resolved by M5's rename, which makes the code agree with the +manifests, and by the assertion M5 adds so no served generation can drift from +its manifest again. + ADR 0031 carries no decision from this round and is unchanged by it. ADR 0035 remains Proposed and wholly deferred; decision 4 neither accepts nor partially implements it. ADRs 0019 and 0030 remain Accepted and unchanged, and nothing From 5ee0bd2a226cafe2091388077fb0d7713d8dccd6 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:39:40 -0700 Subject: [PATCH 090/585] plan(M5): no departing daemon unlinks the socket path Finding 1. The marker-ownership precondition was check-then-act across a process death: between the check and the `File.rm` the Store can die and release the marker (local.ex:166), a successor can acquire it, remove the stale path and bind, and the predecessor's unlink then deletes the successor's socket. No ordering of the two syscalls closes it, because the thing checked is owned by a process that can stop being the answer at any instant. So no predecessor path unlinks: not the orderly stop, not any fail-stop, not reverse cleanup. Only the next daemon that has acquired and verified the marker removes a pre-existing pathname, before it binds. The cost is stated -- a stopped daemon leaves a file that looks live, and a client meeting it is refused rather than hung. Three things go with the precondition: the `File.stat` inode guard, the admitted stat-then-unlink race, and the read-only marker-ownership call the previous revision added to `loopex_store_local`. Nothing else needed that call, so the adapter is unchanged again -- the ownership table, the compatibility sentence, M5.md and ADR 0031 all say so. Swept: the orderly sequence's step 3 and step 6, the fail-stop's step 5, reverse cleanup, evidence rows 1 and 5, the store-loss and idle-shutdown witnesses, the listener and socket-file boundary rows, and ADR 0032's socket rule. The successor-socket witness now asserts the *absence* of an unlink on all three exit paths and runs the old race directly. --- ...store-selection-and-migration-technical.md | 7 +- ...tachment-residency-and-replay-technical.md | 12 +- docs/plans/M5-technical.md | 198 ++++++++---------- 3 files changed, 101 insertions(+), 116 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 49d4e8b96..f742acbb8 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -64,9 +64,10 @@ revision of this paragraph said the daemon bypasses composition entirely, which would have meant a second copy of the wiring layer. On the reported exit it refuses service, closes every connection with `store_lost`, or `store_capacity_exceeded` where that was the store's own reason, and exits -non-zero. It does **not** unlink the socket: the marker is already released, -so this daemon's claim on that pathname has ended, and ADR 0032 makes removing -it the next verified marker holder's job. The next daemon finds no marker to +non-zero. It does **not** unlink the socket — and neither does any other exit path, +orderly or otherwise: a daemon's claim on that pathname is its marker, and ADR +0032 makes removing the pathname the next verified marker holder's job +precisely so that no departing daemon can remove a successor's socket. The next daemon finds no marker to recover, because the dying store already gave it back, and removes the stale pathname before it binds. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 1c92d33ca..ff2593109 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -105,11 +105,13 @@ without touching the socket. that follows from the same rule read in the other direction. A daemon's claim on the path is its marker, so the claim ends when the marker does — which can happen without the daemon being asked, since the Store releases the marker in -its own `terminate/2`. A daemon therefore unlinks only while it can still show -it holds the marker, and one that has lost it, or cannot show it, leaves the -file. Nothing is lost by that: the next daemon to acquire and verify the -marker removes the stale pathname before binding, which is the one moment at -which removing a socket file is unambiguously correct. If the daemon loses store ownership while +its own `terminate/2`. **No daemon unlinks on its way out at all** — not on an orderly stop, not on +any fail-stop, not in reverse cleanup — because a daemon that checked its +ownership and then unlinked would be acting across a window in which the Store +can die, the marker can be released and a successor can bind, and the +predecessor would then delete the successor's socket. The next daemon to +acquire and verify the marker removes the stale pathname before binding, which +is the one moment at which removing a socket file is unambiguously correct. If the daemon loses store ownership while running, because its Store child exits or the marker can no longer be proved held, it closes the listener and every connection before anything else and then exits; no connection outlives the daemon's ownership of the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index f90412015..0cd4c4fa6 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -39,7 +39,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | --- | --- | --- | | `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace.exclude_self/1`, which keeps a credential-bearing process out of every trace session, live and future, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create result's `disposition` and `residency` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | -| `loopex_store_local` | The local adapter, unchanged in behaviour and gaining exactly one read-only call — whether the marker file still holds this daemon's marker, which the socket-unlink precondition needs and `WriterLock` does not expose (`writer_lock.ex:92-105`) — its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | +| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | | `loopex_composition` | The edge-assembly sequence, and the one new public function that runs it in the caller's process and returns the edges — used by `RuntimeOwner` and by the daemon's owner | Daemon lifetime, ownership of what it assembles, or any knowledge of a daemon | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses, and its use of `with_runtime/2`, which M5 does not change | Daemon lifetime or residency | @@ -132,7 +132,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket unlinked while the marker is still held, the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -324,7 +324,7 @@ over generation 1's method set under the exact-generation rule: a generation-1 client sees no daemon method and no lease field, the daemon refuses a generation-1-only initialize, and the foreground server keeps serving generation 1 unchanged. No mixed-generation stream is promised. The private -journal and its format are unchanged, and its adapter is unchanged in behaviour, gaining one read-only call — whether the marker file still holds this daemon's marker — that writes nothing and that the socket-unlink precondition needs; the embedded API, public +journal, its adapter and its format are unchanged; the embedded API, public events, snapshots, artifact formats and the executor protocol are unchanged. Source `VERSION` is distinct from protocol generation, provider build and schema digest. @@ -1396,75 +1396,56 @@ than in taste: `Loopex.Store.Local` answers an append error with observes it, the store is gone and the marker is already released. A sequence that ends "then stop the Store" cannot run when the Store is what died. -**Who may unlink the socket: only a daemon that still demonstrably holds the -marker, and nobody else ever.** The socket path is not the daemon's by -possession; it is the daemon's *because it holds the writer marker*, which is -what ADR 0032 already says. The consequence an earlier revision missed is that -the permission **ends when the marker does**, and the marker is released by -the Store's `terminate/2` (`local.ex:166`) — which can happen before the -daemon is finished, and without the daemon being asked. - -The rule is therefore one rule, not two, and it is a **precondition rather -than a comparison**: - -- **A daemon unlinks the path only while it can show it still holds the - marker.** Immediately before the unlink, and nowhere else, the owner checks - two things: that the Store **process is alive**, and that the Store still - **owns the marker it took**. Both must hold; either failing means this - daemon may no longer touch the path, and it does not. -- **The unlink precedes any Store stop**, so on the orderly path the check is - being made while the Store is still running normally and the answer is - ordinarily yes. -- **The fail-stop path never unlinks at all.** On `store_lost` and - `store_capacity_exceeded` the marker is already gone, so the precondition - can never hold. On the other classes the daemon *could* unlink, and still - does not: a fail-stop is a path where something the daemon depended on has - failed, and the pathname is not worth a check it might get wrong. It leaves - the file. -- **The successor removes what a predecessor left.** A daemon that has - acquired and verified the marker removes the stale pathname before binding — - that is its right, because it *is* the marker holder, and it is the only - moment at which removing a socket file is unambiguously correct. This is - the rule that makes the fail-stop path's litter harmless, and it is stated - as a startup step rather than as a hope. - -**The ownership check needs a narrow addition to the local adapter, and the -plan names it rather than assuming it.** `Loopex.Store.Local.WriterLock` -exposes `acquire/3` and `release/1` and nothing else (`writer_lock.ex:92-105`); -there is no way to ask "do I still hold this". M5 adds one read-only call on -the adapter — answered from the state it already carries, the `writer_lock` -term it was given at open — that reports whether the marker file still holds -this daemon's marker. It writes nothing, changes no behaviour, and exists so -that the unlink has a precondition it can actually evaluate. This is -`loopex_store_local` work, small and named, and the ownership table says so -rather than continuing to call that application unchanged. - -**What this deletes.** The inode guard is gone: comparing a `File.stat` device -and inode against a pair captured at bind was an attempt to make unlinking -safe *after* ownership had lapsed, and the honest answer is that it is never -safe then. Gone with it is the admitted stat-then-unlink race — a window this -design does not have, because it never unlinks without ownership — and the -assumption that a successor whose socket file was removed would simply be -restarted, which was a claim about an operator's behaviour rather than about -this system. - -**One ordering consequence, and the reason the check is a liveness check and -not a flag.** During an orderly stop the owner defers the exits it is not -currently waiting for, so a Store that dies *during* the sequence is not -classified until its own step. The unlink must not rely on the owner's belief -about the Store; it asks the Store, at the moment of asking. A Store that has -died leaves the check failing, the path untouched, and the successor's startup -to remove it. +**Who may unlink the socket: nobody, except the next daemon that has proved it +holds the marker.** The socket path is not the daemon's by possession; it is +the daemon's *because it holds the writer marker*, which is what ADR 0032 +already says. The permission therefore **ends when the marker does**, and the +marker is released by the Store's `terminate/2` (`local.ex:166`) — which can +happen without the daemon being asked and without the daemon noticing. + +An earlier revision tried to keep the unlink by putting a precondition in +front of it: check the Store is alive and still holds its marker, then unlink. +**That is check-then-act across a process death, and it is wrong.** Between +the check and the `File.rm` the Store can die, release the marker, a successor +can acquire it, remove the stale path and bind its own — and the predecessor's +unlink then removes the successor's socket. No ordering of the two syscalls +closes it, because the thing being checked is owned by a process that can stop +being the answer at any instant. + +So the rule is one line, and it has no precondition to get wrong: + +- **No predecessor path ever unlinks.** Not the orderly stop, not any + fail-stop, not reverse cleanup. The orderly stop closes the listener, tells + clients, and **leaves the pathname where it is**. +- **Only the next verified marker holder removes it**, at startup, before it + binds — the one moment at which removing a socket file is unambiguously + correct, because the remover provably holds the exclusion the path belongs + to. A stale `daemon.sock` is therefore an ordinary condition of startup + rather than a failure of shutdown. + +**What that costs, said plainly.** A stopped daemon leaves a socket file +behind. Nothing connects through it — no process is listening, so a client +gets `ECONNREFUSED` rather than a hang — and the next daemon removes it. An +operator inspecting a stopped root sees a file that looks live and is not, +which the operator page states; that is the price of never removing a file +that might belong to somebody else. + +**Three things are deleted with the precondition.** The `File.stat` device and +inode guard, which tried to make unlinking safe after ownership had lapsed. +The admitted stat-then-unlink race, which this design no longer has because it +never unlinks at all. And **the read-only marker-ownership call the previous +revision added to the local adapter**: nothing else needed it, so +`loopex_store_local` is unchanged again, exactly as it was before that +revision invented a use for a query that could not be used safely. **`--socket` is constrained to the selected root.** An override must resolve inside that root's `daemon/` directory — the same directory the default path sits in, under the same owner and symbolic-link rules — and a path outside it is refused at startup with `invalid_socket_path`, before the marker is acquired. Without that constraint two daemons on *different* roots could be -pointed at one path, and neither's marker would say anything about the -other's: the precondition above would be satisfied by a daemon that holds a -marker for a different root entirely, which says nothing about this path. -Inside one root, the marker is the exclusion and there is exactly one holder. +pointed at one path, and the successor rule would have one daemon removing a +path another daemon's marker governs. Inside one root the marker is the +exclusion, there is exactly one holder, and the holder is the only remover. **How a signal reaches the owner, and when the handler is installed.** The daemon does not inherit a usable signal disposition; it installs one, and the @@ -1613,14 +1594,13 @@ the owner fixes. time it answers, every session it could not settle has already been fenced and terminated inside core. This is the drain; what it does, and what it cannot do, is set out below. -3. **Clients are told, and the socket path is unlinked — if it is still - ours.** Each open connection gets one `daemon.stopping` naming +3. **Clients are told, and the listener closes. The socket path is left + where it is.** Each open connection gets one `daemon.stopping` naming `operator_stop`, bounded best-effort as ADR 0032 fixes — one write attempt - into the existing 4 MiB output buffer — and is closed. **Then the owner - checks that the Store process is alive and still owns its marker, and - unlinks only if both hold.** This is before any Store stop, so on an - ordinary stop both hold and the path goes. Where they do not, the path is - left for the next verified marker holder to remove at its own startup. + into the existing 4 MiB output buffer — and is closed, and the listening + socket is closed with them. **Nothing unlinks the pathname**, on this path + or any other: the next daemon to prove it holds the marker removes it + before binding, which is the only safe moment there is. 4. **Every lease owner stops, then the admission relay**, in sequence, against the shared `teardown_ms` deadline. Every lease vanishes with the owners; the relay goes after them because it is what holds their admission @@ -1684,7 +1664,8 @@ the owner fixes. terminating the captured process groups. Then custody and the registry, which hold nothing durable. Then the Store, whose `terminate/2` releases the writer marker — see the marker invariant in ADR 0031. The socket path is already gone, - unlinked in step 3, so the last act is the halt: **`0`**, or the class, + left in place by step 3 for the next marker holder to remove, so the last + act is the halt: **`0`**, or the class, in the case above where something failed on the way out. **The executor is stopped before the lease, and that order is load-bearing** @@ -2031,11 +2012,9 @@ to write. and found dead, refuses with `store_writer_unverifiable` where it cannot be decided, and refuses with `store_writer_active` where it is alive. A surviving marker is a case with a defined answer, not a corruption. -5. **The socket path is left alone.** The fail-stop never unlinks: on the two - store classes the marker is already gone and the precondition can never - hold, and on the rest the daemon declines to spend a check it might get - wrong on a path whose litter the next verified marker holder removes before - binding anyway. **The runtime root, the lease owners, the registry, the +5. **The socket path is left alone**, exactly as the orderly path leaves it. + No daemon unlinks a path on its way out, whatever class it is exiting with; + the next verified marker holder removes it before binding. **The runtime root, the lease owners, the registry, the custody process and the transfers owner are not stopped on this path**, and that is deliberate rather than an omission. A fail-stop is not a drain, and none of them owns anything that outlives the VM: the executor does, which @@ -2168,8 +2147,9 @@ vocabulary of what an exit may say. **Reverse cleanup.** Startup happens inside the owner, so a failure at any step unwinds what that step and its predecessors did, in reverse — and "predecessors" means **every process the startup started**, not the three an -earlier revision named. A bound socket is closed and its path unlinked, a -`daemon/` subdirectory the owner created is removed — no lease owner can exist +earlier revision named. A bound socket is **closed, and its path left in +place** — reverse cleanup unlinks nothing, for the same reason no shutdown +path does — a `daemon/` subdirectory the owner created is removed — no lease owner can exist yet, since none is started before a session is activated — and **every pid the composition function returned is stopped in reverse start order** — runtime, executor, workspace lease, transfers where it exists @@ -2187,16 +2167,18 @@ mechanism; it reuses the one the shutdown sequence defines, against the pid map it already holds. The owner does this in its own start path rather than leaving it to a crash, -because a crashing owner would take the links down without unlinking the -socket file, which no exit signal removes. A daemon that refuses to start -leaves no marker and no socket file behind, which is what lets an operator fix -the cause and try again without a recovery step. +because a crashing owner would take the links down without releasing the +marker or removing the directory it made. A daemon that refuses to start +leaves **no marker held** — which is what lets an operator fix the cause and +try again without a recovery step — and may leave a socket pathname, which the +next daemon removes before binding. **Witnesses**, all on real operating-system processes: - **Idle shutdown.** A daemon with sessions activated and no work in flight receives `SIGTERM`, writes nothing further to `stdout`, closes every - connection with the stop reason, unlinks the socket, releases the marker and + connection with the stop reason, leaves the socket pathname for the next + marker holder, releases the marker and exits `0`; the foreground server then opens the same root immediately, which is what proves the marker was actually released. The case also asserts the negative that the `stopping` field exists for: **no fatal class is recorded @@ -2211,7 +2193,7 @@ the cause and try again without a recovery step. component named in `stopping` and the operator is owed the reason it actually went down for; **the sequence runs to its end**, reaching the Store's own step — where the stop raises `noproc` and is caught — then - unlinking the socket; and the class reaches `stderr` with a non-zero exit + leaving the socket pathname; and the class reaches `stderr` with a non-zero exit rather than the owner dying of `noproc` with no status, no message and a socket file left behind. A second daemon opens the same root immediately afterwards, which is what proves the path completed. @@ -2219,7 +2201,7 @@ the cause and try again without a recovery step. is made to raise in its own `terminate/2` during an orderly stop, so its stop returns that reason rather than `:normal` and the two-clause catch would have killed the owner. The case asserts the sequence completes — the - Store still stopped, the socket still unlinked — and that the exit class is + Store still stopped — and that the exit class is `transfers_lost` rather than `operator_stop`, because the component died of its own reason and not because the owner asked. - **In-flight shutdown, both halves of it.** Two cases, because the drain has @@ -2270,7 +2252,7 @@ the cause and try again without a recovery step. rather than argued. - **Store-loss fail-stop.** The Store is made to terminate under a live listener. The case asserts the daemon observed it, closed the listener and - every connection with `store_lost`, unlinked the socket, and exited non-zero + every connection with `store_lost`, left the socket pathname in place, and exited non-zero with that class on `stderr` — and that it did **not** attempt the ordered sequence, because the marker was already released by the Store's own `terminate/2` before the daemon could act. A second daemon starts on that @@ -2292,20 +2274,21 @@ the cause and try again without a recovery step. fixed set, so one of those dying without a class is a failing case rather than a silent `:shutdown`. A lease owner is deliberately not in this case: its own witness is below, and it asserts the daemon **keeps running**. -- **A successor's socket survives its predecessor's exit.** Two daemons on - one root. The first loses its Store, so the marker is released before it can - act, and it is held at the point where an earlier design would have - unlinked. The second acquires the marker, removes the stale path as the - verified holder, binds its own socket and prints readiness. The first is - then released. The case asserts it **unlinks nothing** — a fail-stop never - does — and that the second daemon's socket is still bound and still serving - a client afterwards. - - The orderly variant asserts the precondition rather than a comparison: the - unlink happens only after the owner has confirmed the Store process alive - and still holding its marker, and a variant that kills the Store immediately - before that check asserts the path is **left alone** and that the next - daemon removes it at startup and serves normally. +- **No daemon ever unlinks, and a successor's socket survives.** Three cases, + one per exit path, each asserting the **absence** of an unlink rather than + its correctness. After an **orderly stop**, the pathname is still on disk + and `connect` to it fails as refused rather than hanging; the next daemon + removes it, binds and serves. After a **store-loss fail-stop**, the same. + After a **failed start** — the marker acquired and the socket bound, then + the index bound exceeded — the same again, with no marker held. + + The race the old design had is then run directly: the first daemon is held + at the instant it would have unlinked, its Store is killed so the marker is + released, the second daemon acquires, removes the stale path, binds and + prints readiness, and the first is released. The case asserts the second + daemon's socket is **still bound and still serving a client** afterwards — + which a predecessor that unlinked under any precondition would have + broken. - **A `--socket` path outside the root is refused.** A path in a directory that is otherwise perfectly valid — right owner, right mode — but outside the selected root's `daemon/` directory exits `invalid_socket_path` with no @@ -2377,7 +2360,7 @@ the cause and try again without a recovery step. the runtime's teardown past the shared teardown deadline. The case asserts the owner **survives** rather than dying of whatever the stop did to the helper, that it then kills the runtime supervisor, and that it still reaches the - Store stop and the socket unlink — the step a stop called inline would skip. + Store stop — the step a stop called inline would skip. - **Cleanup grace 1 ms: the owner survives, classifies from the exit, and still releases the marker.** The same daemon is composed with `cleanup_grace_ms: 1` — the smallest admitted value, since `0` is refused @@ -2388,8 +2371,7 @@ the cause and try again without a recovery step. the owner survives, that it kills and reads the exit, that the class follows the **exit reason** and not the stop's outcome — `operator_stop` and exit `0` where the component still managed to exit `:normal`, its own class where - it did not — and that the sequence still reaches the Store stop and the - socket unlink. + it did not — and that the sequence still reaches the Store stop. It also asserts the thing a grace of 1 ms would otherwise have broken: **the next daemon opens that root with no stale marker to recover.** That is @@ -2461,7 +2443,7 @@ the adapter or the executor. | **Local executor** | The composition function | Daemon owner | Orderly step 6, before the lease | `executor_lost`, daemon-fatal | | **Runtime root** (a supervisor) | The composition function | Daemon owner | Orderly step 5 | `runtime_lost`, daemon-fatal | | **Admission relay** | Daemon owner, after the runtime | Daemon owner | Orderly step 4, after the lease owners whose tickets it holds | `relay_lost`, daemon-fatal: the record of every in-flight admission is gone | -| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Step 1 stops it accepting; step 3 closes and unlinks | `listener_lost`, daemon-fatal, and the one fatal class no client can be told | +| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Step 1 stops it accepting; step 3 closes it, leaving the pathname | `listener_lost`, daemon-fatal, and the one fatal class no client can be told | | **Lease owner, one per session under lease or acquisition** (ADR 0033) | Daemon owner, on the first lease operation after existence validation | Daemon owner | Retires when the lease is free, no acquisition waits and the relay holds no ticket; stopped unconditionally in step 4 | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the next acquisition starts a fresh owner with a fresh epoch. At most 512 at once | | **Connection**, one per accepted client | The listener | The listener | Step 3, or the client | That client's connection closes. Nothing else | | **Stop helper**, one per stop | Daemon owner, `spawn_monitor` | Monitored, never linked | Its own call returning or raising | Nothing: it is monitored so that whatever `GenServer.stop/3` does to it cannot reach the owner | @@ -2489,7 +2471,7 @@ the adapter or the executor. | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | | **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the derived drain budget, tells clients, unlinks the socket only while it can still show it holds the marker, and then stops its linked processes in reverse order — lease owners, the relay, runtime, edges, and the Store last in its own fixed 30 s phase — each stop driven by a monitored helper calling `GenServer.stop/3` while the owner waits on its own link until the shared teardown deadline and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | -| **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` from a dead daemon | Only the marker holder may unlink and rebind, so two starts resolve at the marker and never at the socket | The loser exits without touching the socket | **Not durable:** the socket file is a path, never state | +| **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` left by any exit path | Only a daemon that has acquired and verified the marker removes it, at startup, before binding; no daemon removes one on its way out, so no predecessor can delete a successor's socket | The loser of two simultaneous starts exits without touching the socket; a client meeting a stale path is refused rather than hung | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | Three rows deserve their reading stated, because they are where earlier drafts From dd789356be48d1ebda617722b77d835cfaa86886 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:42:12 -0700 Subject: [PATCH 091/585] plan(M5): fence the Store at the drain deadline, drain in two phases Finding 2. Terminating an unsettled coordinator is not a fence. A coordinator commits through a synchronous call -- `OwnerLane.call/4` runs `Store.transact/2` (store/owner_lane.ex:120-121) -- and a delivered `GenServer.call` completes whether or not its caller is alive; I reproduced that at both pairs, a sleeping handler with its caller killed mid-call still running and still producing its effect. `Control`'s DOWN handler only releases the EventDispatcher fence and leaves the entry (control.ex:805-826), which fences delivery, not the journal. So quiesce now commits an `advance_owner` transaction for each terminated session -- the type the Store already defines (store.ex:168-178), linearized at state.ex:241-254 -- after which an older `session_commit` is refused `:stale_owner_epoch` by the rule that already governs every commit (state.ex:548-551). An old transaction therefore either wins before the fence and is observed or loses after it, and the daemon's report is true when it is read. The witness pauses a transaction at the adapter's existing `:before_linearization` checkpoint (local.ex:252), kills the coordinator, installs the fence and asserts the refusal -- with a variant releasing before the fence and asserting the commit. Finding 3. The Concept promised every abort durable before any cancellation; the mechanism was per session, and cleanup starts on the commit reply path (`begin_admitted_cleanup/1`, session_coordinator.ex:4806-4815), so admitting one session's abort began its cleanup while another's was unwritten. Quiesce is now two-phase inside core: phase one admits and pauses exactly where that function would have begun; phase two releases every cleanup concurrently once every admission has resolved. Core derives each session's `cleanup_grace_ms` itself (session_coordinator.ex:422, :5366), the empty-set maximum is 0, and the call uses an explicit `:infinity` reply timeout with its own deadline carried as data, because `control_call/3` and `dispatcher_call/3` default to 5_000 (runtime.ex:470, :478) and would abandon a working drain. Quiesce's answer gains a third list, `absent`: an `:active` Control entry whose coordinator already died (control.ex:821-823) is reported as not drained, admits no abort, and is fenced all the same, since its in-flight transaction is exactly what the fence is for. --- docs/plans/M5-technical.md | 164 ++++++++++++++++++++++++++++++------- docs/plans/M5.md | 22 +++-- 2 files changed, 147 insertions(+), 39 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0cd4c4fa6..0dc76df1e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -132,7 +132,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` durably admitting, for every active session **before** cancelling anything, the same abort command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -1769,23 +1769,58 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: {:ok, %{settled: [session_id], unsettled: [session_id]}} ``` -**Three parts, and the first is the part an earlier revision got wrong.** +**Three parts, in order, and the first two are one thing split in half.** -1. **A durable admission, before any cancellation.** ADR 0023 fixes that - *only* the durable `session.abort` command cancels, and that cancellation - is "never inferred from EOF or death" +1. **Phase one: every live coordinator admits the abort, and then stops.** + ADR 0023 fixes that *only* the durable `session.abort` command cancels, and + that cancellation is "never inferred from EOF or death" (`0023-…-technical.md:365`, with the method table at `:169`). Quiesce - cancels, so quiesce must admit. For every active session it therefore - **admits the existing abort command**, unchanged, and only then runs that - session's cancellation. The - path is the one that exists: `propose_new/3` for `%{type: :abort}` writes a + cancels, so quiesce must admit — and the Concept promises **every** abort + is durable before **any** cancellation begins, which a per-session + admit-then-cancel loop cannot deliver. + + It cannot because cleanup starts on the commit reply path: + `begin_admitted_cleanup/1` runs "from the reply path of a committed + command" and starts cleanup the moment the reducer marks a run aborting + (`session_coordinator.ex:4806-4815`). Admitting session A's abort therefore + begins A's cleanup while session B's abort is still unwritten. + + So quiesce **splits admission from cleanup**, and the split is the change + to that path: under a drain, a coordinator admits the abort and **pauses at + exactly the point `begin_admitted_cleanup/1` would have begun** — the + record is committed, the queued steer and follow-up are resolved as they + already are, and no cancellation runs. The admission path is otherwise + untouched: `propose_new/3` for `%{type: :abort}` writes the same `command_admitted` record with `"command_type" => "abort"` and - `"admission" => "accepted"` (`session_state.ex:1684-1700`), resolving the - queued steer and follow-up as it goes, and answers with + `"admission" => "accepted"` (`session_state.ex:1684-1700`), and answers `"admission" => "rejected_no_active_run"` where nothing is running - (`:1750-1761`) — the right answer for an idle session, needing no special - case. - + (`:1750-1761`), which is the right answer for an idle session and needs no + special case. + +2. **Phase two: cancellation is released, concurrently, only once every + admission has resolved.** Core waits for phase one to finish for every + session — committed, refused as having no active run, or failed — and then + releases the paused cleanups together. That is what makes the Concept's + ordering true globally rather than per session, and it is also why the two + phases are inside core: a host that ran them would need two round trips per + session and a way to hold a coordinator between them. + + **Concurrently, not in sequence**, because each session's cleanup is + bounded by its own committed grace and running them one after another would + add those bounds together. + + **Core derives each session's `cleanup_grace_ms` itself** from the durable + state it already holds (`session_coordinator.ex:422`, `:5366`); the daemon + passes no per-session number and does not know them. The drain budget is + the maximum over the drained sessions of + `cancellation_bounds(g_i).cli_backstop_ms` + (`apps/loopex/lib/loopex/executor.ex:456-474`), and over an **empty** set + of drained sessions that maximum is **`0`**: a daemon with nothing active + drains instantly rather than waiting out a number derived from nothing. + + Inside the budget each session's cancellation runs under its own `g`, + through `Loopex.Executor.cancel/4` (core), exactly as the coordinator + already drives it at `session_coordinator.ex:3614` and `:5366`. **Whose `command_id` that abort carries, which the set did not say.** `propose_new/3` writes `"command_id" => command.command_id` @@ -1850,21 +1885,58 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: was available and was declined, because it would buy a journal annotation at the price of a one-way root. -2. **A derived budget.** `drain_deadline_ms` is `drain_ms`: the maximum over - the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` - (`apps/loopex/lib/loopex/executor.ex:456-474`). Inside it each session's - cancellation runs under its own `g`, through `Loopex.Executor.cancel/4` - (core) exactly as the coordinator already drives it at - `session_coordinator.ex:3614` and `:5366`. - -3. **A synchronous fence at the deadline.** When the budget is spent, core - does not merely report what did not settle: for each unsettled session it - **fences the coordinator, terminates it, and waits for its `DOWN` before - returning**. Without that, "unsettled" would name a coordinator still - running and free to commit a terminal fact after the daemon had reported it - unfinished and moved on to tell clients — a report false by the time it was - read. After `quiesce/2` returns, every session in `unsettled` has no live - coordinator, and nothing can be appended for it until the next activation. +3. **A Store-linearized fence at the deadline, because terminating a + coordinator is not one.** When the budget is spent, core fences and + terminates every unsettled coordinator and waits for its `DOWN` before + returning. An earlier revision stopped there and claimed nothing could be + appended for that session afterwards. **That claim was false**, and the + reason is worth stating because it is the general shape of this whole + class of bug: a coordinator commits through a *synchronous* call — + `OwnerLane.call/4` runs `Store.transact/2` (`store/owner_lane.ex:120-121`) + — and a `GenServer.call` that has already been delivered runs to + completion whether or not its caller is still alive. Probed at both + toolchain pairs: a handler that sleeps, with its caller killed mid-call, + **still ran and still produced its effect**. So an in-flight transaction + can be linearized by the Store (`local.ex:250-256`) after its coordinator + is gone, and `Control`'s `DOWN` handler does not prevent it — all that + handler does is `EventDispatcher.release_fence/2` and leave the entry + (`control.ex:805-826`), which fences *delivery*, not the journal. + + So quiesce installs a fence the **Store** enforces, using machinery that + already exists. After terminating an unsettled coordinator it commits an + **`advance_owner` transaction** for that session — the type the Store + already defines, binding `expected_owner_epoch` and + `expected_journal_version` and proposing a new incarnation + (`store.ex:168-178`, linearized at `state/local/state.ex:241-254`). Once it + commits, the session's `owner_epoch` has moved, and any older + `session_commit` the Store linearizes afterwards is refused + **`:stale_owner_epoch`** by the rule that already governs every commit + (`state.ex:548-551`). + + That turns an unanswerable question into a decided one. An old transaction + either wins the race to linearization — in which case it commits, is + observed, and the session's durable state includes it — or it loses, and is + refused as stale. Either way, when `quiesce/2` returns, **no transaction + for an unsettled session can still commit**, and the daemon's report is + true when it is read rather than true when it was written. + + **The classification quiesce returns has three lists, not two**, because + `Control` can hold an entry whose coordinator is already dead: its `DOWN` + handler leaves an `:active` entry in place (`control.ex:821-823`), which is + correct for residency and misleading for a drain. Such a session is + **`absent`**: quiesce admits no abort for it, runs no cancellation, and + fences it exactly as it fences an unsettled one, because an old transaction + from that dead coordinator is precisely the case the fence exists for. The + daemon reports it as not drained rather than counting it settled. + +**Quiesce is not called through the facade's default timeout.** `control_call/3` +and `dispatcher_call/3` both default to `5_000` (`runtime.ex:470`, `:478`), and +a drain whose budget is derived from a session's cleanup grace will routinely +exceed that — a five-second reply timeout would abandon a drain that was +working and leave the daemon tearing down underneath it. `quiesce/2` therefore +calls with an explicit `:infinity` reply timeout and carries its **own** +deadline as data: the budget is enforced inside core, where the work is, and +the caller waits for the answer rather than racing it. `Loopex.Runtime.Control` already holds every active session and its coordinator pid, so there is nowhere else this could live and nothing to @@ -2197,6 +2269,38 @@ next daemon removes before binding. rather than the owner dying of `noproc` with no status, no message and a socket file left behind. A second daemon opens the same root immediately afterwards, which is what proves the path completed. +- **The fence is a Store fence, proved against a transaction in flight.** + This is the case a terminated coordinator alone would fail. A session's + terminal transaction is **paused inside the Store, before linearization**, + using the adapter's existing fault probe — `checkpoint(state.fault_probe, + transition, :before_linearization)` at `local.ex:252` is exactly that + injection point. With it paused, the coordinator is killed, so the caller of + that transaction is dead while the transaction itself is still pending. + Quiesce then runs its deadline path: it terminates the coordinator, waits + for the `DOWN`, and commits the `advance_owner` fence for that session. The + paused transaction is released. The case asserts it is **refused + `:stale_owner_epoch`**, that the journal contains no terminal for it, and + that the daemon's `unsettled` report was therefore true when it was read. + + A variant releases the paused transaction **before** the fence commits and + asserts the other half: it commits, it is observed, and the session's + durable state includes it. Both outcomes are decided; neither is a race the + plan has to argue about. +- **The drain is globally durable-first, not per session.** Two sessions are + active, each with a cancellable effect. The case asserts that **both** + aborts are committed to the journal **before either** cleanup begins — + read from the journal's order, not from timing — which a per-session + admit-then-cancel loop would fail, since `begin_admitted_cleanup/1` starts + cleanup on the commit reply path. A second assertion covers the empty case: + a daemon with no active session drains with a budget of `0` and does not + wait. +- **An `:active` entry whose coordinator is already dead is reported, not + drained.** A session's coordinator is killed and the daemon is stopped + before `Control`'s entry is replaced. The case asserts the session appears + in quiesce's **`absent`** list rather than in `settled` or `unsettled`, that + no abort was admitted for it, and that it was **fenced** all the same — the + `advance_owner` commits — because a dead coordinator's in-flight + transaction is exactly what the fence is for. - **A component that fails while it is being stopped.** The transfers owner is made to raise in its own `terminate/2` during an orderly stop, so its stop returns that reason rather than `:normal` and the two-clause catch @@ -2229,7 +2333,7 @@ next daemon removes before binding. unresolved mutation receives `SIGTERM`. The case asserts the session is in the `unsettled` list; that its coordinator is **gone before `quiesce/2` returned**, proved by the pid being dead at the instant the daemon reports - it, which is what the synchronous fence exists for; and then the negative + it; and then the negative that matters: **no terminal is claimed for the work that did not settle** — no `cancelled`, no `outcome_unknown` for it. The ambiguous mutation stays `commit_unknown`, each client is sent the stop reason on a transport that diff --git a/docs/plans/M5.md b/docs/plans/M5.md index ad14949ae..61492f7c5 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -367,10 +367,13 @@ did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. **The drain has a mechanism, and it is core's.** M5 adds `quiesce/2` to -`Loopex.Runtime`, and it has three parts. It **durably admits the existing -abort command** for every active session, because ADR 0023 fixes that only a -durable `session.abort` cancels and nothing may infer cancellation from a -signal. The record it writes is the one a client's own abort writes, under a +`Loopex.Runtime`, and it has three parts. **Phase one** durably admits the +existing abort command for every active session and stops there, because ADR +0023 fixes that only a durable `session.abort` cancels and nothing may infer +cancellation from a signal. **Phase two** releases every session's +cancellation, concurrently, only once every admission has resolved — which is +what makes "every abort durable before any cancellation" true across the +daemon rather than one session at a time. The record it writes is the one a client's own abort writes, under a `command_id` **core mints fresh for that session and that drain**, with the generator core already uses for identifiers of its own and never derived from or shared with a client's; and with no shutdown-specific field: the cause an operator wants is already reported twice @@ -378,11 +381,12 @@ on the way out, in `daemon.stopping` and on `stderr`, and a journal that says the same thing a third time would have cost a persistent-schema decision for nothing. It then drives what is in flight through the cancellation sequence a coordinator already runs for an abort, under the -bounds core already derives from that session's committed cleanup grace. And -at the deadline it **fences and terminates** every coordinator that has not -settled, waiting for each to be gone before it answers — so "unsettled" names -a session with no live coordinator rather than one still free to commit -something after the daemon has reported it unfinished. It belongs in core +bounds core already derives from that session's committed cleanup grace. And at the deadline it **terminates every coordinator that has not settled +and then commits a Store-linearized owner-epoch fence for it**, so an older +transaction still in flight either wins before the fence and is observed or +loses after it and is refused as stale. Terminating the coordinator alone +would not have done it: a transaction already delivered to the Store completes +whether or not the process that sent it is still alive. It belongs in core because core owns coordinator lifetime, cancellation and admission; a daemon-side drain would have to reach into coordinator internals, which the dependency direction forbids, or run a cancellation loop of its own, which is From 47572f1e26ba4338615e0e8965536b0046d62225 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:43:21 -0700 Subject: [PATCH 092/585] plan(M5): give the teardown deadline a number and a scope Finding 4. `teardown_ms` was named and never valued, which left the operator bound unstatable and every "what remains" reference undefined, and the formula covered only the stops -- leaving the `daemon.stopping` writes, the connection closes and the listener close outside any bound. It is now `5_000`, fixed, recorded in the limits table with its rationale: nothing under this deadline waits on a session, an effect or a filesystem sync, and of the processes stopped here only the transfers owner runs a `terminate/2`, so five seconds is a ceiling for actions that are each milliseconds. The deadline starts the instant `quiesce/2` returns and covers every non-Store action from that point; helpers receive `remaining(deadline)` and no component carries a budget of its own. The Store phase is exactly 30_000 on every path, with no grace entering it. Operator bound: `drain_ms` + 5 s + 30 s, in both files. Swept the old examples: the helper call that still passed a raw `grace`, the executor stop sentence, the fail-stop executor and Store steps -- the last of which still said `max(grace, 30_000)` -- and the limits table row. --- docs/plans/M5-technical.md | 48 +++++++++++++++++++++++++++----------- docs/plans/M5.md | 5 ++-- 2 files changed, 38 insertions(+), 15 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0dc76df1e..8da0c29aa 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -270,8 +270,8 @@ because both are facts an operator cannot derive from the software and a reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop**: the - derived session drain, plus the one shared non-Store teardown budget, plus - the fixed 30-second Store phase — and, with it, that a shorter external + derived session drain, plus the fixed five-second budget covering every + non-Store action after it, plus the fixed 30-second Store phase — and, with it, that a shorter external service-manager timeout turns the stop into a **forced shutdown**, where work that would have settled does not and the writer marker may be left for the next daemon's verified recovery. It must also distinguish the **usual @@ -1244,7 +1244,9 @@ only from the exit the owner observes on its own link.** For each component: 1. The owner sets `stopping` to that component, as before. 2. It `spawn_monitor`s a **helper** whose whole body is - `GenServer.stop(pid, :normal, grace)`. The helper is monitored, never + `GenServer.stop(pid, :normal, remaining(deadline))`, where `remaining/1` is + what is left of the phase's own deadline and no component carries a budget + of its own. The helper is monitored, never linked, so whatever that call raises, exits or returns dies with the helper and never reaches the owner. The owner needs nothing from it — not its return value, not its `DOWN` — and ignores both. @@ -1334,7 +1336,7 @@ process** spawned per bounded job), and the module defines **no `terminate/2`** at all. Two consequences, re-derived: - **Stopping the executor is fast, not slow.** With no trap and no - `terminate/2`, `GenServer.stop(executor, :normal, grace)` returns about as + `terminate/2`, that stop returns about as quickly as the mailbox allows. It is not the step that spends the grace; it is the step that *starts* the cleanup. - **The cleanup happens elsewhere, in processes the daemon does not hold.** @@ -1504,7 +1506,7 @@ state. The contract is three clocks: | --- | --- | --- | | **`g`**, each session's committed `cleanup_grace_ms` | The cancellation of that session's effects, and nothing else | The session's own composition; already used by `Loopex.Executor.cancellation_bounds/1` | | **`drain_ms`** | The whole drain, across every session | Derived: `max` over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` (`apps/loopex/lib/loopex/executor.ex:456-474`, where `cli_backstop_ms` is defined as `observe + reserve + terminal` and documented as "the sum a process-liveness backstop must cover"). `g` itself is never a deadline | -| **`teardown_ms`** | **One absolute deadline shared by every non-Store stop** — lease owners, the relay, the runtime, executor, workspace lease, transfers, custody, registry | A single budget the owner fixes once, so the worst case is one bound rather than a sum over components | +| **`teardown_ms`, fixed at `5_000`** | **One absolute deadline covering every non-Store action after the drain** — the `daemon.stopping` writes, closing the connections, closing the listener, the lease owners, the relay, the runtime, the executor, the workspace lease, transfers, custody and the registry | A plan decision, and the rationale is that each of those is a bounded write or a stop of a process with no `terminate/2` to run: milliseconds apiece, so five seconds is a ceiling none of them should approach and an upper bound an operator can add up | | **The Store phase** | The Store's stop alone | A **fixed 30 s**, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of `g` and of `teardown_ms` | `drain_ms` is derived rather than chosen because the cancellation it waits on @@ -1524,9 +1526,27 @@ is a ceiling that matters only when the filesystem is wedged, which is exactly when killing the Store mid-release is worst. The same fixed phase applies in the failed-start reverse cleanup, for the same reason. -**So the operator-facing bound is stated, once:** +**`teardown_ms` is `5_000`, and it is a number rather than a formula.** An +earlier revision named the clock and never gave it a value, which left the +operator bound unstatable and every "what remains" reference undefined. Five +seconds is chosen, not derived: nothing under this deadline waits on a +session, an effect or a filesystem sync — the notification writes are one +attempt into an existing buffer, the closes are closes, and of the processes +stopped here only the transfers owner runs a `terminate/2` at all — so the +budget is a ceiling for a set of actions that are each milliseconds. It is +recorded in the limits table with that rationale. -> **Maximum graceful stop = `drain_ms` + `teardown_ms` + 30 s.** +**The deadline starts the instant `quiesce/2` returns**, and it covers +**every** non-Store action from that point: the stop records, the connection +closes, the listener close, and every stop from the lease owners through the +registry. An earlier revision's formula covered only the stops, which left the +notification and closure steps outside any bound at all. Every helper under it +is given `remaining(teardown_deadline)` and nothing else — no component has a +budget of its own to spend. + +**So the operator-facing bound is stated, once, and it adds up:** + +> **Maximum graceful stop = `drain_ms` + 5 s + 30 s.** That maximum is as large as the composed grace makes it: `drain_ms` is derived from `cli_backstop_ms`, which grows with `g`, so an operator who @@ -2054,9 +2074,11 @@ to write. class on the other six. 3. **Stop the executor** — on every class but `executor_lost`, where it is the component that already died — under the same discipline as every other - stop: a monitored helper calling `GenServer.stop(pid, :normal, grace)`, the - owner waiting on its own link until the shared teardown deadline and - killing on expiry — the same deadline the ordered path's step 6 uses. This is not tidiness: the executor is + stop: a monitored helper calling + `GenServer.stop(pid, :normal, remaining(deadline))`, the owner waiting on + its own link until the shared teardown deadline and killing on expiry — the + same five-second deadline the ordered path uses, started when this path + began. This is not tidiness: the executor is the one linked process whose work reaches outside the VM, and stopping it is what tells its Port-owning workers to terminate the captured process groups. Halting without stopping it would never start that cleanup at @@ -2072,8 +2094,8 @@ to write. is nothing to stop. On the other six, the Store is **still alive**, and because `System.halt/1` runs no `terminate/2`, halting past it would leave the marker file behind on a daemon that shut down deliberately. So the - owner stops it here, under the same bounded treatment as every other stop - and under the same floor: the Store's wait is `max(grace, 30_000)`, so a + owner stops it here, in **its own fixed 30-second phase**, exactly as the + orderly path gives it — no grace of any kind enters that number — so a deliberate fail-stop cannot kill it mid-release either. **If that stop times out and the Store is killed, the marker survives.** @@ -2691,7 +2713,7 @@ line; M5 introduces none of its own. | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | -| Non-Store teardown | one absolute deadline shared by every non-Store stop | This plan; one bound rather than a sum over components | +| Non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/2` returns, covering the stop records, the connection and listener closes and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | | Store shutdown phase | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 61492f7c5..e85c6a102 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -394,8 +394,9 @@ the second loop this milestone forbids, and it could not admit a durable command on its own authority at all. **A graceful stop has a stated maximum**, because an operator configuring a -service manager needs one: the derived drain budget, plus one shared budget -for every non-Store teardown, plus a fixed thirty-second Store phase. A +service manager needs one: the derived drain budget, plus **five seconds** for +every non-Store action after it — the stop records, the closes, and every stop +but the Store's — plus a fixed **thirty-second** Store phase. A service manager that kills the daemon sooner turns the stop into a forced shutdown — the journal stays crash-equivalent, but work that would have settled does not, and the writer marker may be left for the next daemon's From a43506a8409e4de3555f31842a162837d67d72a0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:44:32 -0700 Subject: [PATCH 093/585] plan(M5): start the owner unlinked, check between composition edges Finding 5, both halves. The command process both linked and monitored the owner, which defeats the monitor: an abnormal exit travels the link first and kills the command process, so the DOWN meant to produce `owner_lost` is never handled. The owner is now started with `GenServer.start/3`, unlinked, and monitored immediately -- which is also what the inventory row already claimed, so the two now agree. And "the owner drains its mailbox before each edge" was impossible: the composition chain is one synchronous `with` (loopex_composition.ex:166-178) and the owner is inside that call for all of it. The function therefore takes an interrupt checkpoint, `interrupt: (-> :continue | {:stop, term()})`, evaluated in the caller's process before each edge is started, which the daemon implements as the drain-and-check it performs elsewhere. On an interrupt or an edge failure the function returns `{:error, reason, started}` -- the same map shape success returns, holding only the keys that exist yet -- because otherwise an interrupted composition leaves the owner holding edges it cannot name and reverse cleanup unwinds less than exists. A caller passing no `interrupt` behaves as today, so `RuntimeOwner` and the app-server host are unaffected. The ownership table, the Concept's composition paragraph, the inventory row and the startup witness follow, the last gaining a case that interrupts between two edges and asserts reverse cleanup stops exactly the started ones. --- docs/plans/M5-technical.md | 98 +++++++++++++++++++++++++------------- docs/plans/M5.md | 6 ++- 2 files changed, 70 insertions(+), 34 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8da0c29aa..b7a14d3ee 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -41,7 +41,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | -| `loopex_composition` | The edge-assembly sequence, and the one new public function that runs it in the caller's process and returns the edges — used by `RuntimeOwner` and by the daemon's owner | Daemon lifetime, ownership of what it assembles, or any knowledge of a daemon | +| `loopex_composition` | The edge-assembly sequence, and the one new public function that runs it in the caller's process, calls the caller's `interrupt` checkpoint before each edge, and returns the edges — or, on an interrupt or a failure, returns the ones it has already started so the caller can unwind them — used by `RuntimeOwner` and by the daemon's owner | Daemon lifetime, ownership of what it assembles, or any knowledge of a daemon | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses, and its use of `with_runtime/2`, which M5 does not change | Daemon lifetime or residency | | `loopex_cli` | `loopex daemon` with its readiness line, signal handling and exit classes, `loopex attach` with its roles, takeover presentation and cursor reconnect, the live `loopex sessions --daemon` form beside the unchanged offline one, and the host-side credential custody and registry it composes | Normative lease or session semantics, and any change to the released offline `loopex sessions` | | `loopex_llm_reqllm` | The credential handoff, its sender, the token it accepts, the launcher's unchanged ADR 0019 scrubbing enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | @@ -971,38 +971,66 @@ A failure at any step exits non-zero with that step's reason class, after the reverse cleanup below, and touches nothing after it. -**Startup is interruptible, and the owner is monitored — both because a -synchronous sequence inside one process is not, by itself, process-safe.** -The steps above run in the owner, and while they run the owner is not reading -its mailbox: a `SIGTERM` handled by `:erl_signal_server` becomes a message -that waits, and a linked component's `{:EXIT, …}` waits beside it. Left -alone, that means a daemon can take the marker, bind the socket and print +**Startup is interruptible, and the owner is monitored rather than linked — +both because a synchronous sequence inside one process is not, by itself, +process-safe.** The steps above run in the owner, and while they run the owner +is not reading its mailbox: a `SIGTERM` handled by `:erl_signal_server` becomes +a message that waits, and a linked component's `{:EXIT, …}` waits beside it. +Left alone, that means a daemon can take the marker, bind the socket and print readiness *after* a stop it has already been told about, or after a component it depends on has already died — and then read both and shut down, having announced itself ready in between. -Two rules, both narrow: - -- **Before every acquisition, the owner drains and checks.** Before taking the - marker, before calling the composition function, before each edge the - function returns to it, before binding the socket and before printing the - readiness line, the owner reads whatever is in its mailbox for a stop - message or an `{:EXIT, …}`, and checks that every component it has already - started is alive. Any of those aborts the start into the reverse cleanup - above, which unwinds exactly what exists. Nothing is acquired after a stop - is known, and nothing is announced on top of a component that is gone. -- **The process that started the owner monitors it.** The escript command - process — the one that called `start_link` — holds a monitor and, on `DOWN`, - halts non-zero with `owner_lost` on `stderr` immediately. That is where - `owner_lost` is actually observed: an earlier revision had it arriving only - when a *later signal* found no owner, which leaves a daemon whose owner has - crashed sitting with a bound socket, a held marker and nobody running it - until somebody happens to send `SIGTERM`. The signal handler's own backstop - stays as the second route, for the case where the owner dies in the instant - between the signal and the handler's send. - -Neither rule needs a new process or a supervisor: the drain is a receive with -a zero timeout and a liveness check, and the monitor is the command process +Three rules, each narrow: + +- **The owner is started unlinked and monitored.** The escript command process + calls **`GenServer.start/3`, not `start_link/3`**, and monitors the owner + immediately. An earlier revision had it both link *and* monitor, which + defeats the monitor: an abnormal exit travels the link first and kills the + command process, so the `DOWN` that was supposed to produce `owner_lost` is + never handled by anybody. Unlinked, the command process survives every way + the owner can die, halts non-zero with `owner_lost` on `stderr` on the + `DOWN`, and gives the operating system an exit status — which is the whole + of its job. The inventory row says unlinked-and-monitored, and now the + design does too. +- **The owner drains and checks before every acquisition it performs itself.** + Before taking the marker, before calling the composition function, before + binding the socket and before printing the readiness line, the owner reads + whatever is in its mailbox for a stop message or an `{:EXIT, …}` and checks + that every component it has already started is alive. Any of those aborts + the start into the reverse cleanup above. +- **The composition function checks between its own edges, because the owner + cannot.** Its chain is one synchronous `with` (`loopex_composition.ex:166-178`): + the owner is inside that call for the whole of it and can read nothing + between the Store and the runtime. An earlier revision claimed a mailbox + check "before each edge the function returns to it", which is not a thing + the owner can do. So the function takes an **interrupt checkpoint** as an + option and calls it **before starting each edge**: + + ```elixir + interrupt: (-> :continue | {:stop, term()}) + ``` + + A zero-arity function, supplied by the caller, evaluated in the caller's own + process, which the daemon implements as exactly the drain-and-check above. + Where it answers `{:stop, reason}` the composition starts nothing further. + + **And on any early exit it returns what it has already started**, which the + interrupt makes necessary and an edge failure needed anyway: + + ```elixir + {:error, reason, %{store: pid, transfers: pid | nil, workspace_lease: pid, executor: pid, runtime_supervisor: pid}} + ``` + + — the same map shape a success returns, holding only the keys that exist + yet. Without it, an interrupted or failed composition would leave the owner + linked to edges it cannot name, and reverse cleanup would unwind less than + exists. A caller that passes no `interrupt` sees the behaviour it sees + today, so `RuntimeOwner` and the app-server host are unaffected. + +Neither the monitor nor the checkpoint needs a new process or a supervisor: +the drain is a receive with a zero timeout and a liveness check, the interrupt +is a function the caller already has, and the monitor is the command process doing what it is already there to do — wait for the daemon to end and give the operating system an exit status. @@ -2435,9 +2463,13 @@ next daemon removes before binding. the command process's monitor doing it. A second case kills the owner and *then* sends `SIGTERM`, asserting the same class by whichever route wins, so the two cannot both fail silently. -- **Startup is interruptible.** A `SIGTERM` is delivered mid-startup, at the - step before the marker is taken and again at the step before the socket is - bound. Each case asserts **no readiness line is printed**, that no marker is +- **Startup is interruptible, including inside the composition call.** A + `SIGTERM` is delivered mid-startup at the step before the marker is taken, + again at the step before the socket is bound, and again **between two edges + inside the composition function** — which the interrupt checkpoint is what + makes observable. That third case asserts the function returns + `{:error, reason, started}` naming every edge it had started, and that + reverse cleanup stops exactly those. Each case asserts **no readiness line is printed**, that no marker is held and no socket file exists afterwards, and that a following daemon starts cleanly with nothing to recover. A third kills the Store immediately after the composition call returns and asserts the start aborts into reverse @@ -2560,7 +2592,7 @@ the adapter or the executor. | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | -| **Daemon owner** | The `loopex daemon` command process | — (monitored by that command process) | Itself; it halts the VM | The command process's monitor halts non-zero with `owner_lost`; the signal handler's backstop is the second route | +| **Daemon owner** | The `loopex daemon` command process, with `GenServer.start/3` — **unlinked**, and monitored immediately | Nothing; the command process holds a monitor, not a link | Itself; it halts the VM | The command process's monitor halts non-zero with `owner_lost`; the signal handler's backstop is the second route | | Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | | Credential **custody process** (ADR 0034), **one, for the one composed model configuration** | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal. A second provider needs ADR 0034's stated amendment before a second exists | | **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last of all**, in its own fixed 30 s phase | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal — both fail-stop | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index e85c6a102..ad84815c8 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -601,7 +601,11 @@ in the companion with all three reasons it fails. **`loopex_composition` gains one narrow public function**, which assembles the edges it already assembles but **in the caller's process**, returning them -instead of owning them. The daemon's owner calls it from inside its own +instead of owning them — calling a caller-supplied interrupt checkpoint before +each edge, since the caller is inside one synchronous call for the whole +chain and can check nothing itself, and returning the edges it has already +started when that checkpoint stops it or an edge fails, so the caller can +unwind exactly what exists. The daemon's owner calls it from inside its own trap-exit process, so every link lands where the daemon can act on it, and `RuntimeOwner` calls the same function from its spawned process so `start/1` and `with_runtime/2` are unchanged. The rejected alternative is the daemon From 33c9403dbe485af9f512820a2c881ff9b6045a71 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:46:01 -0700 Subject: [PATCH 094/585] plan(M5): narrow the relay to mutations and make its ticket real Finding 6, all three holes. (a) Tickets cover only the lease-authorized existing-session mutations ADR 0033 already lists -- resume, prompt, steer, follow_up, abort, respond_interaction, admit_resources, activate_skill, each carrying `writer_epoch` (0033-technical:170-178). Reads are not ticketed: "every core call" would have included `next_event/1`, an `:infinity` dispatcher call by construction (runtime.ex:236-244), so a quiet observer sitting on a read would have blocked every takeover for that session indefinitely. (b) The ticket is recorded by a synchronous call from the lease owner, acknowledged before the relay spawns the task, so no mutation exists that the relay has not recorded -- a cast would have let an owner pass its holder check and die before the message arrived. The relay also monitors every lease owner, so the BEAM's per-sender ordering puts every ticket an owner sent ahead of that owner's DOWN. (c) A task dying without a result no longer settles anything. A delivered call completes whether or not its caller lives, so a dead task says nothing about whether core received the mutation; treating it as `commit_unknown` would admit a successor over a mutation still on its way in. The ticket is retained and the relay exits `relay_lost` -- the honest answer, since a daemon that cannot say whether a successor would overtake an older mutation must not keep granting leases. ADR 0033's relay paragraph, the inventory's relay-task row and the witnesses follow: a task killed mid-call keeps its ticket and takes the daemon down, a blocking read does not hold a takeover, and an owner killed between its holder check and its call still leaves a ticket a replacement waits on. --- ...controller-lease-and-takeover-technical.md | 30 +++++-- docs/plans/M5-technical.md | 88 +++++++++++++++---- 2 files changed, 91 insertions(+), 27 deletions(-) diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 712853144..043c7eaf4 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -76,15 +76,29 @@ on its way, because core orders what it receives rather than what is in flight, and core never sees the writer epoch at all. **The daemon closes that window with one fixed process, the admission relay**, -added on the maintainer's decision of 2026-09-20. Every core call the daemon -makes is routed through it; it issues a ticket per call, naming the session; -it survives lease-owner death, being fixed rather than per-session; and **a +added on the maintainer's decision of 2026-09-20. Every **lease-authorized +existing-session mutation** — the set this pair lists below, each carrying +`writer_epoch` and admitted only from the recorded holder — is routed through +it, and nothing else is: reads are not ticketed, since a read grants nothing, +orders nothing, and a blocking read would otherwise hold a takeover for as +long as an observer sat on it. + +The lease owner **calls** the relay and waits for the acknowledgement before +the core call is made, so no mutation exists that the relay has not recorded; +the relay **monitors** every lease owner, so the BEAM's per-sender message +ordering puts every ticket an owner sent ahead of that owner's `DOWN`; it +survives lease-owner death, being fixed rather than per-session; and **a replacement owner's first grant for a session blocks until that session's -outstanding tickets have settled**. A ticket settles when the relay has -observed the call's outcome — its own task returning core's result, or that -task dying and the relay treating the call as settled-unknown, the fact -`commit_unknown` already carries. A connection disappearing settles nothing, -because the call it made is still running. +outstanding tickets have settled**. + +A ticket settles **only** when the relay has the call's real outcome — its +task returning core's answer, refusal included. A task that dies **without** +one settles nothing and keeps its ticket: a delivered call completes whether +or not its caller lives, so a dead task says nothing about whether core +received the mutation, and the relay exits `relay_lost` rather than admit a +successor over a mutation it can no longer account for. A connection +disappearing settles nothing either, because the call it made is still +running. So the ordering claim rests on the relay, and the session-scoped rule gives the rest: the successor is granted a fresh epoch, the dead controller's diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index b7a14d3ee..448651bb3 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1104,21 +1104,54 @@ epoch nor core's serial ownership prevents that reordering: the fresh epoch stops a *later* command from the old tenure, and core orders what it receives, not what is still on the way. -So one fixed, daemon-owned process holds what the lease owners cannot: - -- **Every admitted core call goes through the relay**, which performs it in a - monitored task it owns and issues a **ticket** naming the session, the - admission and the connection it came from. -- **A ticket settles when the relay has observed that call's outcome**, and - that is defined precisely because "the call is finished" is exactly the - ambiguity this closes: either the task returns core's result — any result, - including a refusal — or the task dies and the relay observes its `DOWN` - and treats the call as settled-unknown, which is the same fact - `commit_unknown` already carries in the journal. A connection disappearing - does **not** settle a ticket, because the call it made is still running - inside core; the ticket outlives the connection exactly as the call does. -- **The relay survives lease-owner death**, being fixed rather than - per-session, so the tickets survive with it. +So one fixed, daemon-owned process holds what the lease owners cannot — and +three details of it are the difference between closing the window and looking +as though it does: + +- **Tickets cover exactly the lease-authorized existing-session mutations, and + nothing else.** ADR 0033 lists them: `session.resume`, `session.prompt`, + `session.steer`, `session.follow_up`, `session.abort`, + `session.respond_interaction`, `session.admit_resources` and + `session.activate_skill` — every generation-2 call that carries + `writer_epoch` and is admitted only from the recorded holder + (`0033-…-technical.md:170-178`). **Reads are not ticketed.** An earlier + revision said "every core call the daemon makes", which would have included + `Loopex.Runtime.next_event/1` — an `:infinity` dispatcher call by + construction (`runtime.ex:236-244`) — so a quiet observer sitting on a read + would have blocked every takeover for that session for as long as it sat + there. A read grants nothing, orders nothing and cannot overtake a mutation. +- **The ticket is recorded synchronously, before the call exists.** The lease + owner **calls** the relay and waits for the acknowledgement, and only then + does the relay spawn the monitored task that performs the core call. A cast + would have left the window open at the other end: an owner could pass its + holder check, send its ticket and die before the message arrived, and a + replacement would see no ticket for a call that was about to be made. +- **The relay monitors every lease owner**, so an owner's death is ordered + *after* the tickets it sent. Message ordering between one sender and one + receiver is guaranteed by the BEAM — signals from a process to a process are + delivered in send order, and a monitor's `DOWN` is a signal from the same + pair — so every ticket an owner sent before dying is in the relay's mailbox + ahead of that owner's `DOWN`. The relay therefore knows, at the instant it + learns an owner is gone, exactly which of that owner's calls it is holding. +- **A ticket settles only on a real core result**, and this is the part an + earlier revision got backwards. The task returning core's answer — any + answer, including a refusal — settles the ticket. The task **dying without + one does not**: the relay does not know whether the call reached a + coordinator, and a delivered `GenServer.call` completes whether or not its + caller is alive, so "the task died" says nothing about the call. Treating + that as `commit_unknown` would have admitted a successor while an older + mutation was still on its way into core, which is the exact hole the relay + exists to close. + + So a task that dies without a result **retains its ticket**, and the relay + **exits `relay_lost`** — daemon-fatal, the class it already has. That is the + honest answer: the daemon has lost track of a mutation it authorized and + cannot say whether a successor would overtake it, and a daemon that cannot + answer that question must not keep granting leases. It is rare by + construction, the task's only job being one call. +- **A connection disappearing settles nothing**, because the call it made is + still running inside core; the ticket outlives the connection exactly as the + call does. - **A replacement owner's first grant for a session blocks until that session's outstanding tickets have settled.** Not the daemon's admissions generally — just that session's, which is why the ticket names one. @@ -1127,7 +1160,7 @@ That is the ordering claim ADR 0033's owner-loss section now rests on: a successor's first call cannot be issued while an older call for the same session is unaccounted for, so it cannot overtake one. The relay grants no authority, holds no lease and makes no decision about who may control what; it -is a bookkeeping process on the path core calls already take. +is a bookkeeping process on the path lease-authorized mutations already take. Its own failure is **daemon-fatal**, class `relay_lost`, and for the plainest reason in the fatal map: a daemon whose relay is gone has lost the record of @@ -2493,8 +2526,25 @@ next daemon removes before binding. blocking unconditionally. A late command from the dead controller's tenure is refused on the epoch check, as it would be for any released lease. - **The relay's own death is daemon-fatal.** Killing it exits `relay_lost` - with that `fatal:` on the wire and leaves no stale marker, like every - other fixed component. + with that `fatal:` on the wire, like every other fixed component. +- **A relay task that dies without a result keeps its ticket and takes the + daemon down.** The task performing a ticketed mutation is killed while the + call is in flight. The case asserts the ticket is **still outstanding**, + that no replacement owner is granted the session in the meantime, and that + the daemon exits `relay_lost` — **not** that the mutation is treated as + settled. It is the case that separates this design from the one that + admitted a successor over a call it had lost track of. +- **A read never holds a takeover.** An observer sits on + `Loopex.Runtime.next_event/1`, which blocks indefinitely by construction, + while a controller dies and a new client takes over. The case asserts the + takeover is **granted** — the read is not ticketed — and that the observer's + own read still completes when an event arrives. +- **A ticket exists before its call does.** A lease owner is killed in the + window between its holder check and its core call, injected at the + acknowledgement boundary. Because the ticket is recorded by a synchronous + call, the case asserts the relay holds a ticket for a mutation whose core + call was never made, and that a replacement grant waits on it rather than + proceeding into a gap. - **Owners exist for dormant sessions, and the population is not the activation count.** A dormant session is acquired for recovery without being resumed: the case asserts an owner exists for it, that the **activation @@ -2605,7 +2655,7 @@ the adapter or the executor. | **Lease owner, one per session under lease or acquisition** (ADR 0033) | Daemon owner, on the first lease operation after existence validation | Daemon owner | Retires when the lease is free, no acquisition waits and the relay holds no ticket; stopped unconditionally in step 4 | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the next acquisition starts a fresh owner with a fresh epoch. At most 512 at once | | **Connection**, one per accepted client | The listener | The listener | Step 3, or the client | That client's connection closes. Nothing else | | **Stop helper**, one per stop | Daemon owner, `spawn_monitor` | Monitored, never linked | Its own call returning or raising | Nothing: it is monitored so that whatever `GenServer.stop/3` does to it cannot reach the owner | -| **Relay task**, one per core call | The relay, `spawn_monitor` | Monitored by the relay | The call returning | Settles that call's ticket as unknown, the same fact `commit_unknown` carries | +| **Relay task**, one per ticketed mutation | The relay, `spawn_monitor`, after the ticket is acknowledged | Monitored by the relay | The call returning | **Does not settle its ticket**: the relay cannot tell whether core received the call, so it keeps the ticket and exits `relay_lost` | | **Session coordinator** | Core, under a `DynamicSupervisor` (`restart: :temporary`) | Core | Core; **and `quiesce/2` fences and terminates it** at the drain deadline | Core's own refusal on the next command for that session; **no signal reaches the daemon and none is owed** | | **Owner group and workers** | Core, beneath a coordinator | Core | Core | Core's; a trapping owner group unwinds on its own clock and the daemon does not wait for it | | **Attachment dispatcher** | Core, per attachment | Core | Core | That attachment's, and core's existing detachment rules | From fff6f778c1d1cb831b5589952959c7c4d28404cd Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:47:15 -0700 Subject: [PATCH 095/585] plan(M5): reserve the activation slot before the call, not after Finding 7. Core starts the coordinator inside the call that would tell the daemon it did -- `start_owner` at control.ex:908 for a fresh create, `start_resume_owner` at :318 and :321 for a resume that is not a replay -- so counting on the reply is always too late. At 63 two concurrent calls both see 63 and both coordinators start; at 64 an uncounted dormant resume starts a sixty-fifth. The daemon now takes an atomic slot reservation before any activation-capable call and maintains `|activation set| + |reservations| <= 64`, refusing `activation_ceiling_reached` before core is called at all. Atomicity needs no new mechanism: the daemon's serial owner decides. Reservations are keyed by the identity available at reservation time -- the session ID for a resume, the create `command_id` for a create, whose session ID does not exist yet -- and converted or released idempotently, so a retry or a duplicated reply cannot double-count or double-free. The resolution table is complete rather than illustrative, because an unlisted branch leaks a slot until restart: fresh create and fresh resume convert; replayed create against an active or dormant session, replayed resume, and every refusal release; a prepared-capability activation holds until it resolves; and a call that never answers is held and resolved by asking core whether that session is active, since releasing could exceed the ceiling and converting could spend a slot that was never taken. Witnesses: two simultaneous activations at 63 yielding exactly one coordinator, a dormant resume at 64 refused with core not called at all, and one case per row of the table asserting the remaining slot count. --- docs/plans/M5-technical.md | 67 ++++++++++++++++++++++++++++++++++++++ docs/plans/M5.md | 2 +- 2 files changed, 68 insertions(+), 1 deletion(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 448651bb3..d93a12cef 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -871,6 +871,55 @@ never a bound on reachability — would become exactly that. The activation set has no such gap, because a session cannot be activated without entering it. `loopex resume --daemon` is unaffected: it acquires, resumes, and only then attaches, by which time the session is active. + +**The ceiling is enforced by reservation, because counting after the call is +a race.** Core starts a coordinator *inside* the call that would tell the +daemon it did — `start_owner` for a fresh create (`control.ex:908`), +`start_resume_owner` for a resume that is not a replay (`control.ex:318`, +`:321`) — so a daemon that counts when the call returns has already let it +happen. Two consequences, both real: at 63 activations two concurrent calls +each see 63, both proceed, and both coordinators start; and at 64 a dormant +resume that the daemon has not yet counted starts a sixty-fifth. + +So the daemon takes an **atomic slot reservation before any +activation-capable call**, and the invariant it maintains is + +> **|activation set| + |reservations| ≤ 64.** + +A call that cannot reserve is refused `activation_ceiling_reached` **before +core is called at all**, which is the only place a refusal can be both +truthful and early. The reservation is taken in the daemon's own serial +owner, so "atomic" needs no new mechanism: it is one process deciding. + +**A reservation is keyed by the identity the daemon has when it takes one** — +the session ID for a resume, the create `command_id` for a create, whose +session ID does not exist yet — and it is **converted or released +idempotently**: converting records the session ID in the activation set and +drops the reservation; releasing drops it. Repeating either for the same key +is a no-op, so a retry, a crash-recovered handler or a duplicated reply +cannot double-count or double-free. + +**Every branch of both results resolves the reservation, and the table is +complete rather than illustrative**, because a branch nobody listed is a slot +leaked until the daemon restarts: + +| Result of the call | Slot | +| --- | --- | +| Create, `disposition: :fresh` | **Converted** — a coordinator started | +| Create, `:historical` with `residency: :active` | Released — that session was counted when it was activated | +| Create, `:historical` with `residency: :dormant` | Released — a replay starts nothing | +| Resume, `disposition: :fresh` | **Converted** — a coordinator started | +| Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | +| Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | +| Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | +| Either call **crashing or timing out**, so the daemon has no result at all | **Held, then resolved by observation**: the daemon asks core whether that session is active and converts or releases accordingly. It does not guess, and it does not leak the slot | + +The last row is the one that would otherwise be missed. A call that gives the +daemon no answer may still have started a coordinator, so releasing the +reservation would let the ceiling be exceeded and converting it would spend a +slot that may not exist; asking is the only honest resolution, and the daemon +already has a read-only query for exactly this class of question. + `loopex attach --take-over` against a dormant session therefore acquires successfully and is refused at attach, holding a lease it no longer wants. That is exactly why the general rule matters: **a CLI that holds a lease @@ -2612,6 +2661,24 @@ next daemon removes before binding. refuses `session.create` with `activation_ceiling_reached` **whether the create is fresh or a replay**, and the case asserts the replay is refused too — the stated cost — and that no coordinator was started by the attempt. +- **The ceiling holds under concurrency, which counting afterwards would not.** + A daemon at **63** activations receives two activation-capable calls at + once — one create and one resume, on two connections. The case asserts + **exactly one** succeeds, the other is refused `activation_ceiling_reached`, + and that core started **one** coordinator, not two: the refusal happens + before the second call is made, so there is no second coordinator to + discover afterwards. +- **A dormant resume at the ceiling is refused before the call.** A daemon at + **64** receives `session.resume` for a dormant session. The case asserts the + refusal, and asserts core was **not called** — proved by that session having + no coordinator and no new journal record — which a post-call count would + have failed by starting a sixty-fifth. +- **Every branch releases or converts its reservation.** One case per row of + the resolution table: a fresh create, a replayed create against an active + and a dormant session, a fresh resume, a replayed resume, a refusal, and a + call that never answers. Each asserts the daemon's remaining slot count + afterwards, so a branch that leaked a reservation shows up as a daemon that + refuses early rather than as a silent drift. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting diff --git a/docs/plans/M5.md b/docs/plans/M5.md index ad84815c8..180def439 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -54,7 +54,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | From 856f09252098ab4ebad71472429627638dbe2f15 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:48:38 -0700 Subject: [PATCH 096/585] adr(0032): write generation 2 as DTO tables, not prose Finding 8. The method table was prose an implementer would have to guess from, so generation 2 is now written at the exactness a literal vector needs: per-method tables of request and result keys with types and optionality for `session.list`, `daemon.status`, `session.acquire_control` and `session.release_control`, field tables for both notification records, and a table of every new error code stating what it carries beyond ADR 0023's envelope -- which for all of them is nothing. Four contradictions go with it. The Concept said one notification family and the Technical said two; the Concept now says two and names `daemon.notice`. `control_held` returned the current epoch in ADR 0033 (0033-technical:159) against ADR 0032's rule that a refusal carries no session state (:324); it now carries no epoch, because an epoch is authority-shaped and a client just refused control is the last that should hold one. The limits input claimed to be unchanged while this pair advertises residency limits a client reads; the five added keys are enumerated. And the digest-input count now reads **five** everywhere -- the digest table, the plan's evidence row -- rather than four in one place and "the first two" in another. --- ...tachment-residency-and-replay-technical.md | 105 +++++++++++++++++- ...-daemon-attachment-residency-and-replay.md | 7 +- ...controller-lease-and-takeover-technical.md | 6 +- docs/plans/M5-technical.md | 2 +- 4 files changed, 114 insertions(+), 6 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index ff2593109..39174a9ae 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -157,6 +157,107 @@ enforced inside core. ### Generation 2 additions +Every table below is the wire contract at the exactness a literal vector +needs: the keys a request carries, the keys a result carries, which are +optional, and what type each is in ADR 0023's vocabulary — `binary identity`, +`u64` (a canonical unsigned decimal **string**), `bool`, `plain_object`. The +envelope is ADR 0023's unchanged: a request is a flat object with exactly +`method`, `request_id` and its row's fields, an optional field is **absent** +rather than `null`, and unknown fields refuse before a facade call +(`0023-…-technical.md:131-136`). + +**`session.list`** + +| Direction | Key | Type | Optionality | +| --- | --- | --- | --- | +| request | `limit` | integer 1 to 256 | required | +| request | `after_session_id` | binary identity | optional | +| result | `entries` | array of entry objects, at most `limit` | required | +| entry | `session_id` | binary identity | required | +| entry | `placement_identity` | binary identity | required | +| entry | `residency` | `"active"` \| `"dormant"` | required | +| entry | `controlled` | bool | required | +| result | `next_after_session_id` | binary identity | present **exactly when** more entries exist | +| result | `index_full` | bool `true` | present **exactly when** the index is at its 4,096-entry ceiling | + +Entries are ordered by session ID bytes ascending, and carry nothing else — +no content, no durable session state. + +**`daemon.status`** + +| Direction | Key | Type | Optionality | +| --- | --- | --- | --- | +| request | — | — | takes no fields | +| result | `placement_identity` | binary identity | required | +| result | `daemon_incarnation` | binary identity | required | +| result | `socket_path` | string | required | +| result | `attachments` | integer, and `attachment_limit` beside it | required | +| result | `active_sessions` | integer, and `activation_limit` beside it | required | +| result | `index_entries` | integer, and `index_limit` beside it | required | +| result | `uptime_ms` | `u64` | required | + +**`session.acquire_control`** + +| Direction | Key | Type | Optionality | +| --- | --- | --- | --- | +| request | `session_id` | binary identity | required | +| result | `writer_epoch` | binary identity, ≤ 64 bytes | required | +| result | `expires_in_ms` | `u64`, the remaining term on the daemon's clock | required | + +**`session.release_control`** + +| Direction | Key | Type | Optionality | +| --- | --- | --- | --- | +| request | `session_id` | binary identity | required | +| request | `writer_epoch` | binary identity | required | +| result | `released` | bool `true` | required | + +**Notification records — there are two**, and the Concept says two as well: + +| Family | Key | Type | Optionality | +| --- | --- | --- | --- | +| `daemon.stopping` | `reason` | one of the closed set below | required | +| | `message` | bounded non-secret string | required | +| | `retry_after_ms` | `u64` | present **only** for `operator_stop` | +| `daemon.notice` | `code` | closed set, today `"index_write_failed"` | required | +| | `session_id` | binary identity | required | +| | `message` | bounded non-secret string | required | + +Neither is correlated and neither carries a cursor. + +**The new error codes, with their shape.** All of these are **correlated** +errors answering one request: each carries that request's `request_id`, no +`event_cursor`, no session state, and closes nothing. + +| Code | Answers | Carries beyond the envelope | +| --- | --- | --- | +| `control_held` | `session.acquire_control` | **Nothing.** It does *not* carry the current epoch: an epoch is authority-shaped, and handing one to a client that was just refused is exactly the value it must not have. An earlier revision of ADR 0033 said it named the current epoch; that is withdrawn | +| `control_not_held` | `session.release_control` from a non-holder | nothing | +| `control_pending` | `session.acquire_control` that waited out its deadline | nothing | +| `control_capacity_reached` | any lease operation beyond the 512 concurrent-owner cap | nothing | +| `session_dormant` | `session.attach` | nothing | +| `session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate` | any method that validates existence first | nothing | +| `activation_ceiling_reached` | `session.create`, `session.resume` | nothing | +| `composition_mismatch` | `session.resume` on a session this composition cannot serve | nothing | + +The one **uncorrelated** error generation 2 adds is `control_owner_lost`, +defined below with its cursor and its close behaviour. + +**The limits input is not unchanged**, which an earlier revision's digest +table said while this pair advertised residency limits a client can read. The +added keys are enumerated so the digest covers them: + +| Limit key | Value | +| --- | --- | +| `attachments_per_session` | 64 | +| `attachments_per_daemon` | 512 | +| `session_list_page_max` | 256 | +| `session_index_entries` | 4,096 | +| `lease_term_ms` | 30,000 | + +ADR 0023's own framing and input ceilings are unchanged; these are additions +beside them, and **all five** digest inputs therefore change in generation 2. + | Method | Required fields | Result | | --- | --- | --- | | `session.list` | `limit` (1 to 256), optional `after_session_id` | A page of at most `limit` index entries ordered by session ID bytes ascending and starting strictly after `after_session_id`; each entry carries the session identity, the placement identity recorded for it, `residency` of `active` or `dormant`, and `controlled` as a boolean, never content and never durable session state; `next_after_session_id` is present exactly when more entries exist, and `index_full` is present and true exactly when the index is at its 4,096-entry ceiling, so a client is told the listing may be incomplete rather than reading an omission as an absence | @@ -191,7 +292,7 @@ justify. **This changes the generation-2 digest, and so do the error codes.** `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the -limits — five inputs, and generation 2 changes four of them: +limits — five inputs, and generation 2 changes **all five**: | Digest input | Generation 2 | | --- | --- | @@ -199,7 +300,7 @@ limits — five inputs, and generation 2 changes four of them: | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` and `daemon.notice` | | **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client | -| Limits | Unchanged from ADR 0023's ceilings | +| **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 makes a lease owner's failure session-scoped: the daemon closes that session's diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 92fd47d03..4a83f71ae 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -37,8 +37,11 @@ unchanged — and its request records with exactly one addition, the generation 2 a new schema digest rather than a rename. It serves exactly one generation, `loopex.experimental/2`, which adds `session.list`, `daemon.status`, the two -control methods, the writer-epoch field ADR 0033 names, and one notification -record family, `daemon.stopping`, carrying the reason a daemon is going away. +control methods, the writer-epoch field ADR 0033 names, and **two** +notification record families: `daemon.stopping`, carrying the reason a daemon +is going away, and `daemon.notice`, carrying a bounded code for something an +operator should know about a session whose command nonetheless succeeded — +today, an activation whose directory write failed. The milestone that brings this ADR also renames the released generation-1 string to `loopex.experimental/1`, so the two generations are named on one scheme and diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 043c7eaf4..f261ccfef 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -156,7 +156,11 @@ the local store's writer marker, unchanged. - `session.acquire_control` (`session_id`, `request_id`): grants control when no lease is held, or when the held lease is released or expired; refuses - with `control_held` naming the current epoch otherwise. The result carries + with `control_held` otherwise, **carrying no epoch** — an epoch is + authority-shaped, and a client that was just refused control is the last one + that should be handed the current one. An earlier revision of this sentence + said the refusal named it; ADR 0032's error table is the contract and it + carries nothing beyond the envelope. The result carries the new `writer_epoch` and `expires_in_ms`, the remaining term on the daemon's clock. For a known dormant session, a connection may acquire by session ID before attach. The daemon validates durable session existence diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d93a12cef..33baf1181 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -133,7 +133,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes the first two, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | From 4d2dc084c1f41dc7bd0cb6850e6e7c991d3faf61 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:49:42 -0700 Subject: [PATCH 097/585] plan(M5): sweep the daemon-fatal lease-owner residue Finding 9. Four places still said a lease owner's death takes the daemon down, against the session-scoped rule the rest of the set carries: M5.md's outcome 3, M5-technical's evidence row 3, ADR 0033's Concept evidence line and its technical evidence list. All four now say what actually happens -- that session's controller attachment closed with `control_owner_lost`, its observers kept, the relay's ticket for the in-flight mutation retained, and the replacement owner's first grant waiting until that ticket settles -- which is also the only phrasing that mentions the mechanism the ordering claim rests on. The boundary row follows: a dying lease owner takes its in-flight admission set with it and the relay's tickets do not go with it, which is the whole point of the relay being fixed. --- ...boration-controller-lease-and-takeover-technical.md | 10 ++++++---- ...0033-collaboration-controller-lease-and-takeover.md | 6 ++++-- docs/plans/M5-technical.md | 4 ++-- docs/plans/M5.md | 2 +- 4 files changed, 13 insertions(+), 9 deletions(-) diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index f261ccfef..fe3be2629 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -306,10 +306,12 @@ early and the transport cannot tell the other two apart — an explicit closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after it in both cases; a controller killed mid-run fenced after takeover, its late commands refused; a -lease owner killed while a mutation is in flight taking the -listener, every connection and the daemon down with it, after which the -restarted daemon holds no lease, has activated nothing, and the previous -holder's delayed command is refused on both the holder and the epoch check; +lease owner killed while a mutation is in flight taking neither the daemon nor +any other session down: that session's controller attachment closes with +`control_owner_lost`, its observers stay attached, the relay retains the +outstanding ticket, the replacement owner's first grant waits until it +settles, and the previous holder's delayed command is refused on both the +holder and the epoch check; an abort from the new controller cancelling work dispatched under the old controller's command with a truthful cleanup outcome; an observer never acquiring authority diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index 7adeed350..1cfddad4b 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -108,8 +108,10 @@ negative tests on real processes plus a security reading of the admission path: every refusal — stale epoch, copied current epoch, non-holder connection, released lease, expired lease, observer abort — proved before core admission and before any session write, a controller killed mid-run fenced -after takeover, a lease owner killed while a mutation is in flight taking the -daemon down rather than being restarted beneath live sockets, and a daemon +after takeover, a lease owner killed while a mutation is in flight taking neither the daemon +nor any other session down — its controller closed with `control_owner_lost`, +its observers kept, and the replacement's grant held until the relay's +outstanding ticket settles — and a daemon restart leaving every session uncontrolled with every earlier epoch refused. No durable record changes, so no migration or rollback evidence is owed. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 33baf1181..3f19e9a16 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -134,7 +134,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking the listener, every connection and the daemon down with it, after which the restarted daemon holds no lease and the previous holder's delayed command is refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-custody cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/1` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -2739,7 +2739,7 @@ the adapter or the executor. | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies, taking that session's in-flight admission set with it | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller attachment closes with `control_owner_lost`; observers stay attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | +| **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies; its in-flight admission set goes with it, and the relay's ticket for any mutation it had authorized does not | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller attachment closes with `control_owner_lost`; observers stay attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch, its first grant waiting until the relay's outstanding tickets for that session settle | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 180def439..a00442f7f 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -56,7 +56,7 @@ second loop and no new durable command. | --- | --- | --- | --- | | 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | -| 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight takes the daemon down rather than forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | +| 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the credential is named by an opaque token bound at composition, whose **resolution** is what happens per invocation, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, ADR 0034's host-custody cases at `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/`, the security review recorded in `docs/evidence/M5-closure-runs.md` | From b86a95d984862202554998e9075012eea0bbd8e2 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:52:25 -0700 Subject: [PATCH 098/585] adr(0034): reach the tracer by capability, honour 0030's mechanism Finding 10. A tracer pid in model options is wrong three ways, all read from the tree: the tracer is the runtime supervisor's last child (runtime/supervisor.ex:87) while options are built before the runtime starts, so there is nothing to name; core itself resolves it dynamically on every call (runtime.ex:343-345); and the strategy is `:rest_for_one` (:92), so a tracer crash restarts the tracer alone and changes its pid while every earlier child survives. The exclusion is now reached through a host-composed capability -- the same class as the registry handle beside it -- which holds the runtime reference and resolves the current tracer, and membership lives in `Loopex.Runtime.Control`, the supervisor's second child (:70), which survives every tracer restart, already holds per-runtime process state and already monitors pids and handles DOWN (control.ex:805-826). Control monitors each excluded sender and drops it on DOWN, so the set returns to baseline instead of keeping a dead pid per invocation forever. It fails closed: a present-but-unreachable capability refuses the invocation `:unavailable` and resolves no credential, while an explicitly absent capability proceeds, since a host that composed no tracing has no session to trace. Finding 11. Core change 3 is now **both** mechanisms and says so: the match-specification exclusion ADR 0030 names, for the two bridge functions that receive the resolved bytes, plus the process exclusion for their transitive callees. Replacing a named mechanism with a different one while claiming the accepted ADR was honoured is not a thing a plan may do. Finding 12. Registry and custody waits are `:infinity`, because a `GenServer.call` default would put a hidden five-second deadline inside the invocation deadline and expire first, producing a refusal the guardian never decided; the guardian keeps the only deadline and a blocked registry is its `:timeout`. Ownership is named per host: `RuntimeOwner` for the CLI and the app server, the daemon's owner for the daemon, with normal, failed- start and owner-death cleanup stated. And the "only credential-bearing transfer in the parent" claim narrows to "into or within the adapter", since custody provisioning and rotation are the host's own transfers. Witnesses: a tracer restart keeping the exclusion, the set returning to baseline, and the fail-closed refusal with no credential resolved. --- ...andoff-over-bootstrap-channel-technical.md | 151 +++++++++++++----- ...edential-handoff-over-bootstrap-channel.md | 10 +- docs/plans/M5.md | 23 +-- 3 files changed, 134 insertions(+), 50 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 86ad9a602..80706b412 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -215,9 +215,26 @@ separate: refusal, precisely so an operator can tell a refusal from a silence. A registry that is *gone* answers immediately, because the call fails rather than waits, and that is `:unavailable`. +- **Every wait on the registry and on custody is deadline-free, because the + guardian owns the only deadline.** Both are `GenServer` calls, and a + `GenServer.call/2` carries a hidden five-second default that would sit + *inside* the invocation deadline and expire first — producing a refusal the + guardian never decided, at a time nobody chose. So the sender calls both + with `:infinity` (or an equivalent deadline-free protocol) and the guardian + kills it at the invocation deadline, reporting `:timeout`. One deadline, + owned by one process, is the whole rule; a blocked registry is therefore a + `:timeout` from the guardian and never a silent five-second refusal. - **Its lifetime is the host supervisor's, and a restart invalidates the handle.** The host starts the registry under its own supervisor when it - composes the runtime. If the registry dies, the handle a composed runtime + composes the runtime. **Exactly which supervisor, per host:** `RuntimeOwner` + for the reference CLI and for the app-server host, which is the process that + already owns their composed edges; the **daemon's owner process** for the + daemon, which links the registry and the custody process as fixed + components. In all three the normal path stops them with the rest of the + composition, a failed start unwinds them in the same reverse cleanup as any + other started edge, and the owner's own death takes them with it — they are + linked, so there is no path on which they outlive the host that composed + them. If the registry dies, the handle a composed runtime holds is invalid and every resolution through it answers `:unavailable` **until the host recomposes** — the adapter does not re-look-up, does not wait and does not rebuild, because it has nothing to rebuild from. That is @@ -315,41 +332,88 @@ boundary, not an absolute: strictest sense: there is no message for a sink to redact, and ADR 0030's rule is satisfied by a stronger mechanism than the one its prose names. - **The VM does not make it sticky, so core does.** The same probe shows a - later `:trace.process(session, pid, true, …)` re-enabling the process, so - the exclusion cannot be left to the BEAM. `Loopex.Trace` is a per-runtime - `GenServer` holding the session and its configuration; it gains an - **excluded-pid set** in that state, and three rules: - - 1. `exclude_self/1` adds the caller to the set and, if a session is live, - installs `false` for it before replying; - 2. when a session starts, every pid in the set is skipped where - `runtime_processes/1` would otherwise be flagged — the same place - `excluded?/3` already excludes the tracer and the dispatcher by role - (`trace.ex:411`); - 3. nothing in a trace **configuration** can clear the set. It is not part of - `modules`, `level`, `limits` or `sink`; a host can name any module it - likes and cannot name a process back in. - - **The ordering is acknowledged, not hoped for.** The tracer is one process - and serializes its mailbox, so by the time `exclude_self/1` returns, either - the session started first and the exclusion was installed over it, or the - exclusion was recorded first and the session skipped that pid. There is no - interleaving in which the sender resolves a credential while traced. - - **Reaching the tracer.** The sender has no runtime handle of its own, so - composition puts a **tracer reference in the model `options`**, beside the - registry handle and the credential token — the same class of composition - data as the executor's `reference:`, which `LoopexComposition` already fills - with a live pid. Where no tracer is composed, `exclude_self/1` answers - `{:error, :trace_unavailable}` and the sender **proceeds**: a tracer that is - not running has no session and cannot trace, and making credential delivery - depend on an observability process would be the wrong dependency entirely. - - **What is dropped.** The excluded-MFA list and the module-wide exclusion of - `ProviderCodec` are withdrawn — they cost this adapter's tracing and never - bought the property, for the callee reason above. Core change 3 is now the - process exclusion alone, which is smaller and total. + **The VM does not make it sticky, and neither the tracer nor a pid in + options can hold it.** The same probe shows a later + `:trace.process(session, pid, true, …)` re-enabling the process, so the + exclusion cannot be left to the BEAM. Two further facts decide where it + lives, and both contradict an earlier revision of this pair: + + - **A tracer pid cannot be an option.** The tracer is the runtime + supervisor's **last** child (`runtime/supervisor.ex:87`), while model + options are built before the runtime starts — so at the moment the option + would be filled there is no tracer to name. Core itself never holds a + tracer pid either: `Loopex.Runtime.trace/2` resolves it **dynamically** + through `RuntimeSupervisor.children/1` on every call (`runtime.ex:343-345`). + - **A tracer pid would not survive a restart.** The supervisor's strategy is + `:rest_for_one` (`runtime/supervisor.ex:92`) and the tracer is last, so a + tracer crash restarts the tracer **and nothing else** — a new pid, and + every earlier child, including `Control`, still alive. + + So the exclusion is reached through a **capability**, and remembered in a + process that outlives the tracer: + + - **The capability is a host-owned process reference in model options**, the + same class as the credential registry handle beside it and as the + executor's `reference:`. The host starts it before composition, as it + already starts the registry and the custody process, and hands it the + runtime reference as soon as the composition function returns one. It + holds no membership and makes no decision; it exists because options are + built before the runtime and something has to bridge that order. + - **Membership lives in `Loopex.Runtime.Control`**, chosen by reading the + tree rather than by preference: it is the runtime supervisor's **second** + child (`runtime/supervisor.ex:70`), so under `:rest_for_one` it survives + every tracer restart; it already holds per-runtime process state; and it + already monitors pids and handles `DOWN` (`control.ex:805-826`), which is + the exact machinery the set needs. + - **The set is bounded because Control monitors every excluded sender and + removes it on `DOWN`.** An earlier revision kept a pid per invocation + forever, which is a leak measured in invocations; senders are short-lived + by construction, so the set returns to its baseline — normally empty — + as they exit. + - **A new trace session consults the set.** When the tracer starts a session + it skips every pid Control holds, the same place `excluded?/3` already + excludes the tracer and the dispatcher by role (`trace.ex:411`), and a + tracer that has just restarted asks Control rather than starting empty. + + **It fails closed.** `exclude_self/1` returns only once the exclusion is + installed. If the capability is present but the exclusion cannot be + installed — a tracer restarting in that instant — the sender **does not + resolve the credential**: the invocation refuses with `:unavailable`, the + atom the closed set already carries for "the arrangement needed to resolve + is not there", and the caller retries as it would for any other + `:unavailable`. The alternative, proceeding untraced-but-unexcluded, would + be the one case where a credential is resolved in a process a session may be + tracing. + + **Only an explicitly absent capability proceeds.** Where the host composed + no tracing capability at all, there is no tracer and no session, so nothing + can trace and the sender resolves normally. Absent is not the same as + unreachable, and the two are distinguished at composition rather than at + the call. + + **Core change 3 is both mechanisms, not one instead of the other.** ADR 0030 + says the key-bearing call "is excluded by match specification" + (`0030-…-technical.md:27`), and an earlier revision of this pair replaced + that with process flags while claiming ADR 0030 was honoured — which is not + a thing a plan gets to do to an accepted decision. So: + + - **A match-specification exclusion for the direct key-bearing calls**, the + functions that receive the resolved bytes themselves — + `receive_custody_reply/2` and `write_credential_frame/2` — installed as + ADR 0030's own sentence describes, by clearing those `{module, function, + arity}` identities after the module pattern. This is the mechanism ADR + 0030 names, implemented rather than reinterpreted. + - **And the process exclusion**, for everything those functions *call*: + `ProviderCodec.send/3`, `encode/2` and its private path, `:gen_tcp.send/2` + and whatever a future codec calls beneath them. This is the protection ADR + 0030 did not foresee, because a match specification names functions and + the leak is through callees. + + Neither is sufficient alone: the match specification cannot reach a callee, + and an earlier revision's claim that process exclusion alone "satisfies" ADR + 0030 was substituting a different mechanism for a named one. The + module-wide exclusion of `ProviderCodec` is dropped, since the process + exclusion covers its calls without costing every other frame's tracing. **What is kept as defence in depth**, explicitly labelled so nobody mistakes it for the mechanism: the **keyed shape**. The three bridge functions carry @@ -378,8 +442,19 @@ boundary, not an absolute: The third is the ordering: `exclude_self/1` is asserted to return **before** the token is routed, and a session started concurrently with it is asserted - to produce no message from the sender either way round, which is the - serialization claim made checkable rather than asserted. + to produce no message from the sender either way round. + + Three more cover what the capability is for. **A tracer restart keeps the + exclusion**: the tracer is killed, the supervisor restarts it, a new session + starts, and a sender that excluded itself before the restart is asserted to + produce no message under the new session — which a design holding a tracer + pid in options would fail. **The set returns to baseline**: after a run of + invocations, the excluded-pid set `Control` holds is asserted empty again, + proving the monitors remove what the senders left. And **it fails closed**: + with the tracer made unavailable at the instant `exclude_self/1` is called, + the invocation is asserted to refuse `:unavailable` and **no credential is + resolved**, while a composition with no tracing capability at all is + asserted to resolve normally. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index fc0b3a4f4..957472ec9 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -80,8 +80,14 @@ is gone, resolution answers `:unavailable` and every invocation on that token refuses the same way until the host recomposes. Nothing rebuilds the secret, and nothing could: the registry holds no bytes to rebuild it from. -**Exactly one credential-bearing transfer exists in the parent, and this pair -names it.** A host that keeps the bytes and answers a resolver call has to send +**Exactly one credential-bearing transfer exists into or within the adapter, +and this pair names it.** The narrower wording is deliberate: the host puts the +bytes into custody when it composes, and may replace them there when it +rotates, and both are transfers in the parent that this pair does not govern — +they are the host's, before the adapter is involved at all. What this pair +governs is everything from the adapter's edge inward. + +**Within that boundary the transfer is one, and this pair names it.** A host that keeps the bytes and answers a resolver call has to send them to the process that asked; a contract saying the value is never in a message could never be implemented alongside one. So the rule is a permission with a boundary: the custody process's reply to the sender is the one diff --git a/docs/plans/M5.md b/docs/plans/M5.md index a00442f7f..9e8d803f0 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -965,16 +965,19 @@ host that named the adapter would create one more message holding the credential. M5 therefore **implements what the accepted ADR already requires**, as core's -third change in this milestone — and implements it by **process** rather than -by function, because a function-level list cannot hold: an excluded function -calls functions it does not own, and a trace session naming `:gen_tcp` -sees the credential frame `ProviderCodec.send/3` hands it, whatever this -adapter's own modules are patterned. `Loopex.Trace` gains -`exclude_self/1` and an excluded-pid set: the credential-bearing process -excludes itself before it resolves anything, from every live session and every -future one, and no trace configuration can name it back in. Both the leak and -the mechanism were reproduced by probe at both toolchain pairs before this was -written down. ADR 0030 is **not** edited — an accepted ADR changes through its own +third change in this milestone — and implements it **as both mechanisms**, +because neither alone is enough. The match specification ADR 0030 names +excludes the key-bearing bridge calls themselves. It cannot reach what they +*call*: an excluded function calls functions it does not own, and a trace +session naming `:gen_tcp` sees the credential frame `ProviderCodec.send/3` +hands it, whatever this adapter's own modules are patterned. So `Loopex.Trace` +also gains `exclude_self/1` and an excluded-pid set held in `Control` and +reached through a capability the host composes, since the tracer is the +runtime's last child and is resolved dynamically: the credential-bearing +process excludes itself before it resolves anything, from every live session +and every future one, and no trace configuration can name it back in. Both the +leak and the mechanism were reproduced by probe at both toolchain pairs before +this was written down. ADR 0030 is **not** edited — an accepted ADR changes through its own amendment path — and its prose is honoured once this change lands. This is a change to an accepted ADR's subject matter rather than to its text, so it is flagged for the maintainer as such. From 685b8d8058ddd37ee55f9477c9fb25f033d61bd5 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:53:11 -0700 Subject: [PATCH 099/585] adr(M5): unwind the acceptance circularity across the five ADRs Finding 13. M5-technical required these ADRs accepted before the implementation that depends on them, while each ADR made implementation tests the evidence its acceptance requires -- which no decision could ever satisfy, since implementation waits on acceptance. Acceptance now binds the reviewed design and its future evidence obligations, and the block is renamed in all five to "Implementation and milestone-closure evidence", with exact-diff tests and the security review reserved for Outcome closure. Finding 14. ADR 0031 said an owner that crashes still runs the Store's `terminate/2`, so the marker comes back. It cannot promise that: the command process halts the VM on the owner's DOWN, and the adapter cannot win that race from inside. Owner loss is now stated as crash-equivalent for the marker -- released or stale, undecidable from the daemon -- which costs nothing, because the successor's liveness-probed recovery already answers both cases. --- ...de-store-selection-and-migration-technical.md | 16 ++++++++++++++-- ...daemon-grade-store-selection-and-migration.md | 2 +- ...032-daemon-attachment-residency-and-replay.md | 2 +- ...ollaboration-controller-lease-and-takeover.md | 2 +- ...-credential-handoff-over-bootstrap-channel.md | 2 +- ...035-typed-decision-models-as-policy-inputs.md | 2 +- docs/plans/M5-technical.md | 12 +++++++++++- 7 files changed, 30 insertions(+), 8 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index f742acbb8..05d3a38e2 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -35,8 +35,20 @@ the daemon does not promise is that every process has finished before it exits. The adapter also **traps exits**, which this arrangement relies on: an owner -that crashes rather than stopping still runs the Store's `terminate/2`, so the -marker comes back. What leaves it is a kill, a power loss, or a bounded stop +that crashes rather than stopping gives the Store's `terminate/2` the chance +to run, so the marker ordinarily comes back. + +**Ordinarily, not always**, and the qualification is about process lifetime +rather than about the adapter. The Store runs `terminate/2` only while the VM +is alive, and the command process that monitors the daemon owner halts the VM +the moment it sees that owner's `DOWN` — a race the adapter cannot win from +inside. So **owner loss is crash-equivalent for the marker**: it is released +or it is stale, the daemon cannot tell which, and neither can this ADR. That +costs nothing, because the successor's liveness-probed recovery already +handles both — a marker whose recorded holder is proved dead is reclaimed, one +that cannot be decided refuses `store_writer_unverifiable`, and a live holder +refuses `store_writer_active`. Claiming the release always happens would have +been a claim about scheduling. What leaves it is a kill, a power loss, or a bounded stop of the Store that expired and had to be ended with `Process.exit(pid, :kill)` — the three cases the next daemon's verified stale-writer recovery is for. diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 28e2a9e02..7044f6f4d 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -100,7 +100,7 @@ successor adapter's evidence, and buying it here would double M5's store evidence to make one operator message nicer. Until then the daemon's capacity behaviour is the adapter's, stated plainly rather than promised away. -**Evidence its acceptance requires.** The M5 half is a durability claim, so +**Implementation and milestone-closure evidence.** The M5 half is a durability claim, so its class is process and store fault injection on the real adapter plus a rollback proof: a root driven to capacity refuses the append with the store's own reason, terminates the store, and the daemon closes the listener and every diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 4a83f71ae..6991bcadc 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -181,7 +181,7 @@ lazy recovery avoids: a root with 4,096 recorded sessions would start 4,096 coordinators to serve the one a client wanted. And a root with one unservable session would fail a start that need never have reached it. The companion records each in full. -**Evidence its acceptance requires.** Two classes together. The transport and +**Implementation and milestone-closure evidence.** Two classes together. The transport and its generation are a protocol claim, so they need vectors and a compatibility proof: a generation-2 negotiation vector, refusal of a generation-1-only initialize, and an independent client over the socket. The residency rules are diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index 1cfddad4b..f9de5c7ea 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -103,7 +103,7 @@ survivor moves the same window one process up; making it survivable at all would mean making it durable, which is the durable lease record this decision already rejects. -**Evidence its acceptance requires.** This is a trust claim, so its class is +**Implementation and milestone-closure evidence.** This is a trust claim, so its class is negative tests on real processes plus a security reading of the admission path: every refusal — stale epoch, copied current epoch, non-holder connection, released lease, expired lease, observer abort — proved before core diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 957472ec9..20fe9a8ee 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -184,7 +184,7 @@ decision buys. A resolver supplied as a function was rejected because a closure is not plain boundary data and its captured environment is exactly the retention the security review has to exclude. -**Evidence its acceptance requires.** This is a trust claim, so its class is +**Implementation and milestone-closure evidence.** This is a trust claim, so its class is negative tests plus a security review, with a real-provider proof for the path the release check already runs. Every credential-plane negative that M0 to M2 established is re-pointed at the new handoff and must hold with its assertion diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs.md b/docs/adr/0035-typed-decision-models-as-policy-inputs.md index 3aa9d71be..bd3823e77 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs.md @@ -83,7 +83,7 @@ schema constrains the shape of an answer but yields no probability and no confidence, so a host has nothing to threshold on, and it costs a full generation to obtain. -**Evidence its acceptance requires.** This is a trust claim, so its class is +**Implementation and milestone-closure evidence.** This is a trust claim, so its class is negative tests plus a real-provider proof. The negatives are the load-bearing half: no typed answer, at any confidence including 1.0, ever produces a grant the host's policy would not otherwise have produced; a missing, malformed, diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 3f19e9a16..c9337fc06 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -12,7 +12,17 @@ Concept: [Non-goals](M5.md#concept-plan-non-goals). M5 waits on four decisions. Each is accepted before the implementation that depends on it, not before unrelated work, and none may be outstanding at -closure. The repository status check reads the links in this section, so a +closure. + +**Acceptance binds a design and its evidence obligations, not the evidence +itself**, which is the only reading that is not circular. Each of these ADRs +lists tests that exist once the milestone implements it; requiring those +tests *before* acceptance would mean no decision could ever be accepted, +since implementation waits on acceptance. So acceptance means the maintainer +has read the design and the obligations it commits to, and those obligations — +renamed in every one of the five to **implementation and milestone-closure +evidence** — are discharged at Outcome closure, where the exact-diff tests and +the security review belong. The repository status check reads the links in this section, so a decision named only in prose declares nothing. | Decision | Acceptance point | What its acceptance settles | From f4ec48d206dd84e02f99d364eabae1b206d6037e Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:56:26 -0700 Subject: [PATCH 100/585] plan(M5): regroup the inventory and close the material items (1) The inventory claimed to be exhaustive while mixing exact processes, per-thing families and omitted runtime children at three resolutions. It is now grouped ownership at one stated granularity: the daemon's fixed processes exactly -- nine, eight without transfers, now including the tracing capability -- its dynamic groups with their bounds, and core's, the adapter's and the executor's as groups with their owners. The runtime's seven children under `:rest_for_one` are named as a group (runtime/supervisor.ex:66-92), and the event dispatcher is corrected to one per runtime rather than one per attachment. (2) "Create result" becomes "create and resume results" in all five places, and ADR 0032's "four core changes" becomes five. (3) The parent-environment proof narrows to two checkable assertions -- the configured name absent, and no environment read for a credential anywhere in the adapter's call path -- and the old "no value equal to the credential" scan is withdrawn with its reasons: it cannot enumerate what it scans, it would fail a host that keeps the same secret under its own second name, and passing it proves nothing about where the adapter looks. (4) ADR 0032's acceptance is what authorizes the released generation-name change, stated where the no-amendment finding is; ADR 0023 is unedited and nothing supersedes it, since it never named the string. (5) Every witness names its file, its case name and its lane when it is written -- stated once as a rule -- and ADR 0034's host-custody cases are given as a table of file, cases and lane per host. (6) ADR 0035 records three questions for whoever takes it to acceptance: `evaluation_recorded` against "every durable record untouched", the policy claim needing to be a monotonicity property rather than a sentence, and the evaluation provider belonging behind ADR 0019 and ADR 0034 rather than beside them. --- ...tachment-residency-and-replay-technical.md | 9 +- ...andoff-over-bootstrap-channel-technical.md | 40 +++++-- ...ision-models-as-policy-inputs-technical.md | 26 ++++- docs/plans/M5-technical.md | 104 ++++++++++++------ docs/plans/M5.md | 8 +- 5 files changed, 132 insertions(+), 55 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 39174a9ae..66866e0a3 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -332,8 +332,8 @@ a refusal reason invented at implementation time and not entered in the ordered list would make the served contract differ from the digest the server advertises, which is exactly the drift the digest exists to catch. The generation-2 literal the conformance module pins is the digest of the contract -*including* all four changes, and a build missing any of them computes a -different value and fails there. Generation 1 gains no method, no record family and no error code — but its +*including* all five changed inputs, and a build missing any of them computes +a different value and fails there. Generation 1 gains no method, no record family and no error code — but its digest is **not** untouched, because M5 renames its generation string from `loopex.session.v1-experimental` to `loopex.experimental/1` and the generation is the digest's first input. That rename is the plan's decision, taken under @@ -696,8 +696,9 @@ awaiting an answer, a recovery in progress, an unresolved `commit_unknown`, or an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and -none of M5's four core changes (concurrent attachment, the read-only existence -query, the excluded-function trace list, and `quiesce/2`) stops a coordinator, +none of M5's five core changes (concurrent attachment, the read-only existence +query, the trace exclusion, `quiesce/2`, and the create and resume results' +`disposition` and `residency` fields) stops a coordinator, so a deactivation call would be a further core change this milestone does not make. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 80706b412..e286cc5a2 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -658,12 +658,22 @@ proves, and the refusal above the ceiling, are unchanged. Three proofs are new: -- **Parent environment.** From the completion of composition onward — before, - during and after a call — the parent VM's environment holds no credential - under the adapter's name and no value equal to the credential in use. - "During" is observed from inside the call, at the point the child reports - readiness. The case composes the runtime the way a reference host does, with - the variable set, and asserts that composition returns having deleted it. +- **Parent environment**, stated as two checkable things rather than one + unfalsifiable one. From the completion of composition onward — before, + during and after a call — **the configured credential name is absent from + the parent VM's environment**, and **no function in the adapter's call path + reads the environment for a credential**. "During" is observed from inside + the call, at the point the child reports readiness. The case composes the + runtime the way a reference host does, with the variable set, and asserts + that composition returns having deleted it. + + An earlier revision also asserted that no environment value **equals** the + credential in use, which is a different and much weaker claim than it + sounds: it scans values the test cannot enumerate ahead of time, it would + fail for a host that legitimately keeps the same secret under a second name + of its own, and passing it proves nothing about where the adapter looks. + The two assertions above are what the decision actually rests on, and the + drift-protection case is what enforces the second. - **Independence across runtimes.** Two runtimes composed in one VM, each with its own registry, custody and token, run invocations at once; each child records only its own credential, and neither child — nor either @@ -742,12 +752,18 @@ Three proofs are new: - **Host custody, proved at each host rather than in the adapter.** The adapter's test tree cannot prove a claim about the CLI's or the daemon's composition, and an earlier draft filed all three there. Each case lives - where its subject lives: `apps/loopex_cli/test/` for the reference CLI, - `apps/loopex_app_server/test/` for the app-server host, and - `apps/loopex_daemon/test/` for the daemon. Each proves that composition - reads the variable exactly once, deletes it from the VM's environment, and - that the holding process's `format_status/1` redacts its state under a - forced crash report. The adapter's own tree keeps only what is the adapter's + where its subject lives, named to the file and the case so the closure + matrix can be checked against a list rather than a directory: + + | Host | File | Cases | Lane | + | --- | --- | --- | --- | + | Reference CLI | `apps/loopex_cli/test/credential_custody_test.exs` | `reads the credential variable exactly once at composition`; `deletes the credential variable from the VM environment`; `custody state is redacted in a forced crash report` | fast | + | App-server host | `apps/loopex_app_server/test/credential_custody_test.exs` | the same three | fast | + | Daemon | `apps/loopex_daemon/test/credential_custody_test.exs` | the same three, plus `custody and registry are stopped with the daemon and on a failed start` | fast | + + Each proves that composition reads the variable exactly once, deletes it + from the VM's environment, and that the holding process's `format_status/1` + redacts its state under a forced crash report. The adapter's own tree keeps only what is the adapter's to prove: that it reads no environment variable for a credential and that the token and resolution contract behaves. diff --git a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md index 850159e97..e5c924466 100644 --- a/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md +++ b/docs/adr/0035-typed-decision-models-as-policy-inputs-technical.md @@ -197,8 +197,30 @@ exemption predicate ADR 0009 refuses, arriving with a number attached. Concept: [Consequences and rollback](0035-typed-decision-models-as-policy-inputs.md#concept-adr-0035-consequences). Nothing public changes. The `Loopex.Policy` and `Loopex.Model` callbacks, the -public protocol and its generations, public events, snapshots, artifacts, the -executor protocol and every durable record are untouched. A runtime with no +public protocol and its generations, public events, snapshots, artifacts and +the executor protocol are untouched. + +**Three questions are recorded for whoever takes this pair to acceptance**, +because they are contradictions or gaps in the design as written rather than +in its prose, and this pair stays Proposed and deferred rather than resolving +them now: + +1. **`evaluation_recorded` versus "every durable record untouched".** The + evidence above requires a new journaled record and this section says no + durable record changes. Both cannot hold: a new record kind is a durable + addition, with the compatibility question that carries — which readers + accept it, and what a reader that does not makes of it. +2. **"Never widens what a policy would otherwise allow" needs to be a + monotonicity property, not a sentence.** As written it is a claim about + intent; to be checkable it has to say that for any host policy and any + evaluation answer the admitted set is a subset of what the same policy + admits with no evaluation at all, and the evidence has to test that shape + rather than two chosen answers. +3. **The evaluation provider is a provider.** It resolves a credential, spawns + a process and talks to a network endpoint, so it belongs behind ADR 0019's + protected provider process and ADR 0034's credential handoff rather than + beside them. Whether it reuses that machinery or duplicates it is the + largest implementation question this pair leaves open. A runtime with no evaluation configured is byte-for-byte the runtime that exists today. The one compatibility effect is on host composition and arrives with the prerequisite amendment rather than with this pair: a host that configures evaluation diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index c9337fc06..9bfa8050c 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -147,7 +147,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-custody cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the parent VM's environment holds no credential under the adapter's name and no value equal to the credential in use, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/1` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-custody cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/1` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -305,7 +305,13 @@ deliberately, and the derived checklist in Outcome 5's evidence row is what makes that auditable rather than asserted. **Test honesty.** Future test bodies are written with their implementation; a -missing witness is never a pass. Real-provider cases live in their own files +missing witness is never a pass. **Every witness this pair or an ADR in this +set describes names three things when it is written: the exact file, the case +name, and the lane it runs in** — `fast` for `bash scripts/check.sh`, +`release` for `bash scripts/check-release.sh`, and `attended` for the two +release cases that need a person. A witness described only by what it asserts +is a witness nobody can find at closure, and the derived checklist in Outcome +5's evidence row is where the three are checked against what exists. Real-provider cases live in their own files under the `real_provider` tag. A daemon that proxies several socket connections to one replaceable core attachment cannot satisfy Outcome 4, because independent concurrent attachments, lifetime with zero attachments, @@ -365,8 +371,12 @@ experimental protocol generation, exact" and that "source version and protocol generation are independent" (`0023-…md:116-118`) without ever writing the name, and ADR 0024 does not mention generations at all. The only ADR that carries a generation string is ADR 0032, which is Proposed with this -milestone and states the rename itself. So ADR 0023 stays accepted and -unedited, and nothing here needs an amendment path. +milestone and states the rename itself — so **ADR 0032's acceptance is what +authorizes the change to a released generation name**, and it is the right +place for it: that ADR fixes generation 2 and its negotiation, and the rename +is the other half of the same naming decision. ADR 0023 stays accepted and +unedited, and nothing supersedes it: it never named the string, so nothing it +says stops being true. **Now is the cheapest moment**, which is the other half of the decision. Workstream 3 already restructures `LoopexProtocol.Session` from one generation @@ -777,7 +787,7 @@ deadline, because a mutation sent after the term elapsed will be refused anyway and a client that keeps trying only obscures when control was lost. -**Core's create result tells the daemon which create it was, and that is core's +**Core's create and resume results tell the daemon which call it made, and that is core's fifth M5 change.** The daemon has two duties that pull against each other: charge a *fresh* create against the activation ceiling, because a fresh create starts a coordinator; and repair a directory entry for a session whose create @@ -791,7 +801,7 @@ Core already computes what is missing, and uses it: `create_command_absent?/2` binds `fresh?` at `control.ex:895`, and the `cond` at `:903-907` reads it to decide whether to `start_owner`. What is discarded is the distinction in the **reply** — all three branches answer `{:ok, session_id}` — so the fifth change -is to stop discarding it there. **Core's runtime-side create result — the +is to stop discarding it there. **Core's runtime-side create and resume results — the Elixir function the daemon calls, not the released public protocol result — carries two plain fields beside the session ID:** @@ -2710,36 +2720,64 @@ do. This table is the answer to both: one row per boundary M5 touches, and every cell resting on a code line that exists today or on a component this plan names as new. It is the thing to check a change against. -**First, the process inventory**, rebuilt from scratch for this revision -because more than one review found two documents counting the same processes -differently. Every process any document in this set names appears here once, -with who starts it, who holds its link, who stops it and what its death means. -Nine fixed, one bounded dynamic population, and everything else owned by core, -the adapter or the executor. +**First, the process inventory, at one stated granularity.** Earlier revisions +called this table exhaustive while listing twenty-one rows that mixed exact +processes with per-thing families and omitted the runtime's own children — +three different resolutions in one table, which is why it kept being wrong. It +is now **grouped ownership**: every **fixed daemon process** appears exactly, +because the daemon's topology is a closed set this plan fixes; everything +owned by core, the adapter or the executor appears as a **group with its +owner**, because their counts are those components' business and naming them +individually would make this table a copy that rots. + +**The daemon's fixed processes — nine, eight without transfers:** | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | -| **Daemon owner** | The `loopex daemon` command process, with `GenServer.start/3` — **unlinked**, and monitored immediately | Nothing; the command process holds a monitor, not a link | Itself; it halts the VM | The command process's monitor halts non-zero with `owner_lost`; the signal handler's backstop is the second route | +| **Daemon owner** | The `loopex daemon` command process, `GenServer.start/3` — **unlinked**, monitored immediately | Nothing; the command process holds a monitor | Itself; it halts the VM | The command process halts non-zero with `owner_lost`; the signal handler's backstop is the second route | | Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | -| Credential **custody process** (ADR 0034), **one, for the one composed model configuration** | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal. A second provider needs ADR 0034's stated amendment before a second exists | -| **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last of all**, in its own fixed 30 s phase | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal — both fail-stop | -| **Artifact transfers owner** | The composition function | Daemon owner | Orderly step 6 | `transfers_lost`, daemon-fatal. **Absent** where transfers are disabled | -| **Workspace lease** | The composition function | Daemon owner | Orderly step 6 | `workspace_lease_lost`, daemon-fatal | -| **Local executor** | The composition function | Daemon owner | Orderly step 6, before the lease | `executor_lost`, daemon-fatal | -| **Runtime root** (a supervisor) | The composition function | Daemon owner | Orderly step 5 | `runtime_lost`, daemon-fatal | -| **Admission relay** | Daemon owner, after the runtime | Daemon owner | Orderly step 4, after the lease owners whose tickets it holds | `relay_lost`, daemon-fatal: the record of every in-flight admission is gone | -| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Step 1 stops it accepting; step 3 closes it, leaving the pathname | `listener_lost`, daemon-fatal, and the one fatal class no client can be told | -| **Lease owner, one per session under lease or acquisition** (ADR 0033) | Daemon owner, on the first lease operation after existence validation | Daemon owner | Retires when the lease is free, no acquisition waits and the relay holds no ticket; stopped unconditionally in step 4 | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the next acquisition starts a fresh owner with a fresh epoch. At most 512 at once | -| **Connection**, one per accepted client | The listener | The listener | Step 3, or the client | That client's connection closes. Nothing else | -| **Stop helper**, one per stop | Daemon owner, `spawn_monitor` | Monitored, never linked | Its own call returning or raising | Nothing: it is monitored so that whatever `GenServer.stop/3` does to it cannot reach the owner | -| **Relay task**, one per ticketed mutation | The relay, `spawn_monitor`, after the ticket is acknowledged | Monitored by the relay | The call returning | **Does not settle its ticket**: the relay cannot tell whether core received the call, so it keeps the ticket and exits `relay_lost` | -| **Session coordinator** | Core, under a `DynamicSupervisor` (`restart: :temporary`) | Core | Core; **and `quiesce/2` fences and terminates it** at the drain deadline | Core's own refusal on the next command for that session; **no signal reaches the daemon and none is owed** | -| **Owner group and workers** | Core, beneath a coordinator | Core | Core | Core's; a trapping owner group unwinds on its own clock and the daemon does not wait for it | -| **Attachment dispatcher** | Core, per attachment | Core | Core | That attachment's, and core's existing detachment rules | -| **Trace tracer** | Core, per runtime | Core | Core | The trace session's; it holds the excluded-pid set, so its loss ends tracing rather than exposing anything | -| **Provider sender and guardian** (ADR 0034) | The adapter, per invocation, inside the calling process | Neither is linked to the daemon owner | The guardian kills the sender at the deadline; both end with the invocation | That invocation's refusal, as one of the seven atoms. No daemon class | -| **Provider child**, its Port and OS process (ADR 0019) | The adapter's launcher, per invocation | The Port's owner | The invocation | That invocation's refusal | -| **Per-job Port worker, carrier and guard** (ADR 0022) | The local executor, per job | The worker is monitored by the executor; the carrier and guard are OS processes | The worker terminates the captured group when the executor goes | The job's outcome, reconciled through `commit_unknown`. **These are the processes the daemon cannot wait for at a halt** | +| Credential **custody process** (ADR 0034), one for the one composed model configuration | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal | +| **Tracing capability** (ADR 0034) | Daemon owner, beside the other two | Daemon owner | Orderly step 6 | Treated as the registry is: daemon-fatal, since a sender that cannot exclude itself must not resolve | +| **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last**, in its own fixed 30 s phase | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal | +| **Artifact transfers owner** | The composition function | Daemon owner | Orderly step 6 | `transfers_lost`. **Absent** where transfers are disabled | +| **Workspace lease** | The composition function | Daemon owner | Orderly step 6 | `workspace_lease_lost` | +| **Local executor** | The composition function | Daemon owner | Orderly step 6, before the lease | `executor_lost` | +| **Runtime root** (a supervisor; its children are core's, below) | The composition function | Daemon owner | Orderly step 5 | `runtime_lost` | +| **Admission relay** | Daemon owner, after the runtime | Daemon owner | Orderly step 4, after the lease owners whose tickets it holds | `relay_lost`, daemon-fatal | +| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Step 1 stops it accepting; step 3 closes it, leaving the pathname | `listener_lost`, and the one fatal class no client can be told | + +**The daemon's dynamic processes, each with its bound:** + +| Group | Started by | Bound | Its death | +| --- | --- | --- | --- | +| **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | +| **Connections**, one per accepted client | The listener | ADR 0032's attachment ceilings | That client's connection closes | +| **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time | Nothing: monitored, never linked | +| **Relay tasks**, one per ticketed mutation | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | + +**Core's processes, as groups with their owner.** The runtime root supervises +seven children under `:rest_for_one` (`runtime/supervisor.ex:66-92`): the tool +registry, `Control`, a worker task supervisor, an owner-group dynamic +supervisor, a session dynamic supervisor, the event dispatcher and the tracer. +The daemon holds none of them and names none of them in its fatal map — it +links the **root**, and a death anywhere beneath it that the root does not +survive arrives as `runtime_lost`. + +| Group | Owner | Count | What its loss means to the daemon | +| --- | --- | --- | --- | +| **Session coordinators** | Core's session supervisor, `restart: :temporary` | One per active session | Core's own refusal on the next command; **no signal reaches the daemon and none is owed**. `quiesce/2` terminates and fences them at the drain deadline | +| **Owner groups and their workers** | Core, beneath a coordinator | Per coordinator | Core's; a trapping owner group unwinds on its own clock and the daemon does not wait | +| **Event dispatcher** | The runtime root | **One per runtime**, holding the per-attachment queues — not one per attachment, which an earlier revision of this table said | Restarted by the root under `:rest_for_one`, which restarts the tracer with it | +| **`Control`** | The runtime root | One per runtime | Holds the trace exclusion set and the session entries; its restart is the root's business, and it carries the tracer with it | +| **Tracer** | The runtime root, **last** child | One per runtime | Restarts alone, changing pid, which is why nothing holds a tracer pid | + +**The adapter's and executor's processes, likewise:** + +| Group | Owner | Count | Its death | +| --- | --- | --- | --- | +| **Provider sender and guardian** (ADR 0034) | The adapter, inside the calling process | Two per invocation | That invocation's refusal, one of the seven atoms. No daemon class | +| **Provider child, its Port and OS process** (ADR 0019) | The adapter's launcher | One per invocation | That invocation's refusal | +| **Per-job Port worker, carrier and guard** (ADR 0022) | The local executor | One set per job | The job's outcome, reconciled through `commit_unknown`. **These are the processes the daemon cannot wait for at a halt** | | Boundary | Owner | What fails | Who observes it, and how | What the client sees | Durable / not durable | | --- | --- | --- | --- | --- | --- | @@ -2800,7 +2838,7 @@ already reached the tracer, and a list of excluded `{module, function, arity}` identities cannot cover what an excluded function *calls* — a traced `:gen_tcp.send/2` shows the credential frame however this adapter's own modules are patterned. One pid excluded from every session, live and future, -is both smaller and total. **Two plain fields on the runtime-side create result** — which unify +is both smaller and total. **Two plain fields on the runtime-side create and resume results** — which unify nothing and add no wire surface: they exist because core computes `fresh?` at `control.ex:895` and then throws it away four lines later, leaving every caller unable to tell a fresh create from a replay. Direct code cannot supply diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 9e8d803f0..3a7bc6472 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -43,7 +43,7 @@ attachments to one session; one read-only query that answers whether a session ID exists durably in the root; `Loopex.Trace.exclude_self/1`, which keeps a credential-bearing process out of every trace session, live and future, before any message is delivered, and which accepted ADR 0030 already requires; `quiesce/2`, the bounded settle an orderly stop -drains through; and two plain fields on the **runtime-side** create result, +drains through; and two plain fields on the **runtime-side** create and resume results, telling a host whether the create it just made was fresh or a replay and whether the session is active or dormant — the public protocol result is unchanged. It gains no lease, no transport, no @@ -100,7 +100,7 @@ serves generation `loopex.experimental/2` only, which adds `session.list`, the one-attachment-per-process rule to residency limits. It adds no durable method: core owns durable session truth and its M5 changes are concurrent attachment, one read-only existence query, trace exclusion, the bounded -`quiesce/2` and two fields on the runtime-side create result, none of which is +`quiesce/2` and two fields on the runtime-side create and resume results, none of which is a durable command, so a daemon method that ended a session durably would have to add one, which M5 does not do. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, @@ -118,7 +118,7 @@ is not "quiescent" and stopping on idleness would destroy exactly what Outcome 1 exists to prove. And there is nothing to stop it with: core owns coordinator lifetime, and M5's five core changes — concurrent attachment, a read-only existence query, trace exclusion, the bounded `quiesce/2` and the -create result's two new fields — none of them stops a coordinator. +create and resume results' two new fields — none of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation @@ -472,7 +472,7 @@ No controller lease, transport, socket or collaboration rule inside core. Its only M5 changes are independent concurrent attachment support, one read-only session-existence query, the trace exclusion that accepted ADR 0030 already requires, the bounded `quiesce/2` an orderly stop drains through, and two -plain fields on the runtime-side create result — none of which is a durable +plain fields on the runtime-side create and resume results — none of which is a durable command, and none of which changes a wire schema. No daemon-grade store adapter, journal format version, migration, backup tooling, compaction, retention cutoff or NIF dependency; no daemon-served generation 1; no durable From 21e9516b1dcfff3b665a939773febfa676fbd5c8 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 10:57:39 -0700 Subject: [PATCH 101/585] plan(M5): apply the adversarial pass over this round's diff Three of the added classes produced changes rather than confirmations. (p) Caller death against a delivered call, applied to the stop helpers: killing a helper does not cancel the stop it has already delivered, which is the same property that makes a dead coordinator's transaction commit and a dead relay task's mutation reach core. That is stated where the helper is defined, because it is the reason classification comes from the exit reason on the owner's own link and never from what became of the helper. (q) Every ceiling consumed by a core call is reserved before that call, not only the activation one. `session.attach` creates the attachment inside core, so `attachments_per_session` and `attachments_per_daemon` get the same treatment -- two concurrent attaches at 511 would otherwise both see 511 and both succeed -- with a witness asserting core holds 512 afterwards and not 513. The index entries and the concurrent lease owners need no reservation, because the daemon creates those itself, serially. (t) Hidden defaults: `control_call/3` and `dispatcher_call/3` default to five seconds (runtime.ex:470, :478), so "the call gave the daemon no answer" is an ordinary outcome of a slow root rather than an exotic one -- which is where the reservation table's held-and-resolved-by-observation row comes from. Calls that consume a ceiling carry explicit timeouts. `exclude_self/1` carries an explicit bound too, and the plan says why a bound is right there and wrong for the registry and custody calls: the safe answer to an unconfirmed exclusion is to refuse, not to wait. The other classes confirmed the round's fixes rather than finding more: the socket check-then-act is gone, pid-holding sets are monitored or restart-free, option contents are started before what they name, and the DTO and inventory classes were the subject of their own findings. --- ...andoff-over-bootstrap-channel-technical.md | 7 +++- docs/plans/M5-technical.md | 40 +++++++++++++++++-- 2 files changed, 42 insertions(+), 5 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index e286cc5a2..0d2295ad8 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -376,7 +376,12 @@ boundary, not an absolute: tracer that has just restarted asks Control rather than starting empty. **It fails closed.** `exclude_self/1` returns only once the exclusion is - installed. If the capability is present but the exclusion cannot be + installed, and it carries an **explicit** bound rather than inheriting a + `GenServer.call` default — a hidden five seconds here would be a silent + deadline inside the invocation's, exactly the fault the registry and custody + calls avoid by waiting deadline-free. Here a bound is correct where there it + was not, because the safe answer to "I cannot confirm the exclusion" is to + refuse rather than to wait. If the capability is present but the exclusion cannot be installed — a tracer restarting in that instant — the sender **does not resolve the credential**: the invocation refuses with `:unavailable`, the atom the closed set already carries for "the arrangement needed to resolve diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 9bfa8050c..46704c962 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -892,8 +892,18 @@ has no such gap, because a session cannot be activated without entering it. `loo resumes, and only then attaches, by which time the session is active. -**The ceiling is enforced by reservation, because counting after the call is -a race.** Core starts a coordinator *inside* the call that would tell the +**Every ceiling consumed by a core call is reserved before that call**, and +the activation ceiling is the one where getting it wrong is most visible. The +rule is general: `attachments_per_session` (64) and `attachments_per_daemon` +(512) are consumed by `session.attach`, which creates the attachment inside +core, so the daemon reserves an attachment slot before calling and releases it +on any refusal — two concurrent attaches at 511 would otherwise both see 511 +and both succeed. The index's 4,096 entries and the 512 concurrent lease +owners need no reservation, because the daemon creates those itself, serially, +in its own process. + +**The activation ceiling is enforced by reservation, because counting after +the call is a race.** Core starts a coordinator *inside* the call that would tell the daemon it did — `start_owner` for a fresh create (`control.ex:908`), `start_resume_owner` for a resume that is not a replay (`control.ex:318`, `:321`) — so a daemon that counts when the call returns has already let it @@ -934,8 +944,17 @@ leaked until the daemon restarts: | Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | | Either call **crashing or timing out**, so the daemon has no result at all | **Held, then resolved by observation**: the daemon asks core whether that session is active and converts or releases accordingly. It does not guess, and it does not leak the slot | -The last row is the one that would otherwise be missed. A call that gives the -daemon no answer may still have started a coordinator, so releasing the +**That last row is not hypothetical, and the reason is a default nobody +chose.** The daemon reaches core through `Loopex.Runtime`, whose +`control_call/3` and `dispatcher_call/3` default to a **five-second** reply +timeout (`runtime.ex:470`, `:478`). A create or resume that takes longer +returns the daemon an error while core is still starting a coordinator — so +"the call gave no answer" is an ordinary outcome of a slow root, not an +exotic one. Every daemon call that consumes a ceiling therefore carries an +explicit timeout rather than inheriting that default, and resolves its +reservation by observation when the timeout is what it gets. + +A call that gives the daemon no answer may still have started a coordinator, so releasing the reservation would let the ceiling be exceeded and converting it would spend a slot that may not exist; asking is the only honest resolution, and the daemon already has a read-only query for exactly this class of question. @@ -1380,6 +1399,13 @@ only from the exit the owner observes on its own link.** For each component: linked, so whatever that call raises, exits or returns dies with the helper and never reaches the owner. The owner needs nothing from it — not its return value, not its `DOWN` — and ignores both. + + **Killing the helper would not cancel the stop it has already delivered**, + which is the same property that makes a dead coordinator's transaction + commit and a dead relay task's mutation reach core. That is precisely why + classification comes from the **exit reason on the owner's own link** and + never from what became of the helper: the helper is a way to make a call + without risking the caller, not a handle on the call. 3. The owner then waits on the link it already holds: ```elixir @@ -2693,6 +2719,12 @@ next daemon removes before binding. refusal, and asserts core was **not called** — proved by that session having no coordinator and no new journal record — which a post-call count would have failed by starting a sixty-fifth. +- **Two concurrent attaches at the attachment ceiling.** A daemon at 511 + attachments receives two `session.attach` calls at once. The case asserts + exactly one succeeds and the other is refused, and that core holds **512** + attachments afterwards rather than 513 — the same reserve-before-the-call + rule as the activation ceiling, proved where it would otherwise have been + assumed. - **Every branch releases or converts its reservation.** One case per row of the resolution table: a fresh create, a replayed create against an active and a dormant session, a fresh resume, a replayed resume, a refusal, and a From e34a62ac971375265c75f5890ffda95cda4ad6e8 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:08:04 -0700 Subject: [PATCH 102/585] plan(M5): add the tracing capability to the fixed set and its classes F2. The tracing capability existed in the inventory and nowhere else. It is now in the fixed-set table as start order 3 -- ten linked processes with transfers, nine without -- in the start and stop orders, reverse cleanup, the bounds table, the fatal map as `capability_lost`, the exit-class list, the stale-marker class list, the one-class-per-component witness, ADR 0032's `daemon.stopping` reason set and its vector list, and the boundary row. Its fail-stop reasoning is the registry's: a sender that cannot confirm its trace exclusion refuses rather than resolves, so every model invocation would fail for a reason no client can fix. F1. ADR 0032-technical said "beyond the four this milestone makes" and "M5's core changes stay at four" in one paragraph while saying five in another; both now say five. Every ordinal in that file was grepped rather than read past. F3. The reservation table's no-answer row could not be performed for a create: the reservation is keyed by the create `command_id` because no session ID exists yet, and core's existence query takes a session ID. A create now resolves by replaying under its original `command_id`, which returns the historical result without starting a coordinator (control.ex:901-907), reading the session ID from it and asking about that -- under the same reservation key, so no second slot is charged. The table splits the row in two and the witness runs both. F4. The fence's transaction identity is named argument by argument: `Store.advance_owner/6` (store.ex:820-827) with a **derived** `tx_id` by the discipline `owner_identity/3` already uses (session_coordinator.ex:1346, :1490-1498), `expected_owner_epoch` and `expected_journal_version` read fresh from `ownership_head/3` (:1337-1343), and a fresh incarnation in the form `fresh_incarnation/2` mints. The proposed incarnation is stated as a fence marker the next activation supersedes, since `discover_and_advance_owner/1` builds its candidate from the head it reads at that moment (:1186-1196, :1345-1359). F5. Generation 2's result DTOs are exact: `daemon.status` gains one row per key with its type, and the prose summary table that duplicated all four methods is deleted -- two descriptions of one wire is how they drift. --- ...tachment-residency-and-replay-technical.md | 30 ++-- docs/plans/M5-technical.md | 137 ++++++++++++------ docs/plans/M5.md | 8 +- 3 files changed, 112 insertions(+), 63 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 66866e0a3..4dbf63c25 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -191,9 +191,14 @@ no content, no durable session state. | result | `placement_identity` | binary identity | required | | result | `daemon_incarnation` | binary identity | required | | result | `socket_path` | string | required | -| result | `attachments` | integer, and `attachment_limit` beside it | required | -| result | `active_sessions` | integer, and `activation_limit` beside it | required | -| result | `index_entries` | integer, and `index_limit` beside it | required | +| result | `attachments` | integer | required | +| result | `attachment_limit` | integer, 512 | required | +| result | `active_sessions` | integer | required | +| result | `activation_limit` | integer, 64 | required | +| result | `activations_used` | integer, activations spent in this daemon lifetime | required | +| result | `index_entries` | integer | required | +| result | `index_limit` | integer, 4,096 | required | +| result | `index_full` | bool | required | | result | `uptime_ms` | `u64` | required | **`session.acquire_control`** @@ -258,18 +263,17 @@ added keys are enumerated so the digest covers them: ADR 0023's own framing and input ceilings are unchanged; these are additions beside them, and **all five** digest inputs therefore change in generation 2. -| Method | Required fields | Result | -| --- | --- | --- | -| `session.list` | `limit` (1 to 256), optional `after_session_id` | A page of at most `limit` index entries ordered by session ID bytes ascending and starting strictly after `after_session_id`; each entry carries the session identity, the placement identity recorded for it, `residency` of `active` or `dormant`, and `controlled` as a boolean, never content and never durable session state; `next_after_session_id` is present exactly when more entries exist, and `index_full` is present and true exactly when the index is at its 4,096-entry ceiling, so a client is told the listing may be incomplete rather than reading an omission as an absence | -| `daemon.status` | none | Placement identity, daemon incarnation, socket path, attachment, active-session and index counts against their limits, uptime | -| `session.acquire_control`, `session.release_control` | `session_id`, `request_id` and the lease fields ADR 0033 fixes | Lease result naming the writer epoch and the remaining lease term | +The tables above are the contract for both directions; an earlier revision +kept a second, prose summary of the same four methods beside them, which is +exactly how two descriptions of one wire drift apart. It is gone, and the +per-method tables are the only statement of what a request and a result +carry. -Generation 2 also adds **one notification record family**, `daemon.stopping`, -which no client requests and every client may receive: +**The `daemon.stopping` record, field by field:** | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:relay_lost`, `fatal:listener_lost`. A lease owner's death is not among them: it closes one session's controller attachment with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost`, `fatal:listener_lost` — nine in a daemon with artifact transfers and eight without, one per linked component of the fixed set. A lease owner's death is not among them: it closes one session's controller attachment with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | @@ -496,11 +500,11 @@ counts activations per daemon lifetime, for the same reason — it counts what the daemon did. Two alternatives were rejected, and both would be **a further core change** -beyond the four this milestone makes. A lifecycle notification from core to the daemon +beyond the five this milestone makes. A lifecycle notification from core to the daemon would be a new core-to-host signal, with its own delivery and ordering questions, added for a listing field. A monitorable coordinator handle handed out to the daemon would export core's supervision topology across the boundary -and invite the daemon to reason about it. M5's core changes stay at four, and +and invite the daemon to reason about it. M5's core changes stay at five, and neither of these is among them. The lease-owner fatal rule in ADR 0033 is untouched by this and stays. The diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 46704c962..6ff34b04d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -719,7 +719,7 @@ in full, and this list is derived from it rather than summarising it: - **while running**, one per linked component in the fixed set: `store_lost`, `store_capacity_exceeded`, `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, - `relay_lost` and `listener_lost`. A lease owner's death is **not** in this + `capability_lost`, `relay_lost` and `listener_lost`. A lease owner's death is **not** in this list: it is session-scoped, closes that session's controller with `control_owner_lost`, and the daemon keeps running; @@ -954,10 +954,19 @@ exotic one. Every daemon call that consumes a ceiling therefore carries an explicit timeout rather than inheriting that default, and resolves its reservation by observation when the timeout is what it gets. -A call that gives the daemon no answer may still have started a coordinator, so releasing the -reservation would let the ceiling be exceeded and converting it would spend a -slot that may not exist; asking is the only honest resolution, and the daemon -already has a read-only query for exactly this class of question. +A call that gives the daemon no answer may still have started a coordinator, so +releasing the reservation would let the ceiling be exceeded and converting it +would spend a slot that may not exist; asking is the only honest resolution. + +**For a resume the daemon can ask directly; for a create it cannot**, and an +earlier revision of this table missed the difference. A create's reservation +is keyed by the create `command_id`, because no session ID exists when it is +taken, and core's existence query takes a **session ID**. So the create's +resolution is one step longer: replay the create under its original +`command_id`, which returns the historical result without starting a +coordinator (`control.ex:901-907`), take the session ID from it, and then ask +about that ID. The replay is idempotent by construction and carries the same +reservation key, so it charges no second slot. `loopex attach --take-over` against a dormant session therefore acquires successfully and is refused at attach, holding a lease it no longer wants. @@ -1163,23 +1172,29 @@ So `apps/loopex_daemon` has one top-level process, `Loopex.Daemon.Owner`, a `GenServer` that traps exits and holds the links itself — the same pattern `RuntimeOwner` already uses, for the same reason. -**It links a fixed set of nine processes — eight without artifact +**It links a fixed set of ten processes — nine without artifact transfers — and a bounded, dynamic population of lease owners beside them.** -Earlier drafts said four, then seven, each time having counted the components -the daemon *thinks* about rather than the processes that actually exist. The -fixed set is this: +Earlier drafts said four, then seven, then nine, each time having counted the +components the daemon *thinks* about rather than the processes that actually +exist. The fixed set is this: | Start order | Linked process | Where it comes from | Optional? | | --- | --- | --- | --- | | 1 | The credential **routing registry** | The daemon's own, as the host ADR 0034 names | no | | 2 | The credential **custody process** | The daemon's own, as the host ADR 0034 names | no | -| 3 | The Store adapter | `start_edge(Store.Local, …)` | no | -| 4 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | -| 5 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | -| 6 | The local executor | `start_edge(Local, …)` | no | -| 7 | The runtime root | `start_edge(Loopex, …)` | no | -| 8 | The **admission relay** | The daemon's own; every core call the daemon makes is routed through it | no | -| 9 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | +| 3 | The **tracing capability** | The daemon's own, as the host ADR 0034 names; it holds the runtime reference and resolves the current tracer for `exclude_self/1` | no | +| 4 | The Store adapter | `start_edge(Store.Local, …)` | no | +| 5 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | +| 6 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | +| 7 | The local executor | `start_edge(Local, …)` | no | +| 8 | The runtime root | `start_edge(Loopex, …)` | no | +| 9 | The **admission relay** | The daemon's own; every ticketed mutation is routed through it | no | +| 10 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | + +The tracing capability starts with the other two host-owned processes and +before composition, for the reason all three share: model options carry their +references, and options are built before the runtime exists. It is handed the +runtime reference as soon as the composition function returns one. **The admission relay is new in this revision, and it exists because of a window nothing else closes.** Core has no writer epoch — the lease is the @@ -1277,8 +1292,8 @@ have settled has no owner at all. The two populations are not the same set, and tying one to the other's number would have made the bound wrong the first time an operator took control of a dormant session. -**The registry and the custody process are first, and that is forced rather -than chosen.** ADR 0034 makes the *host* own both, and for a daemon the host +**The registry, the custody process and the tracing capability are first, and +that is forced rather than chosen.** ADR 0034 makes the *host* own both, and for a daemon the host is the daemon. The runtime's model configuration carries the registry handle and the token in `options`, so both processes must exist before the composition function builds that configuration — which means before the @@ -1291,7 +1306,8 @@ runtime last within that chain, because it depends on all of them. **The stop order is the reverse, with one deliberate exception.** Reversed: listener, then **every lease owner**, then the **relay**, then runtime, -executor, workspace lease, transfers, custody, registry — and then **the +executor, workspace lease, transfers, then the tracing capability, custody and +the registry — and then **the Store, last of all**, out of reverse order. The lease owners go before the relay because the relay is what holds their tickets, and stopping it first would discard a ticket an owner could still be waiting on. They are stopped @@ -1322,7 +1338,7 @@ runs no dialyzer, and `RuntimeOwner` itself already destructures the field, at not, and the real argument is the simpler one above. **There is no restart strategy, because there are no restarts.** Every one of -the fixed nine — eight without transfers — is `start_link`ed by the owner, +the fixed ten — nine without transfers — is `start_link`ed by the owner, as is each lease owner beside them, and the owner's `handle_info({:EXIT, pid, reason}, state)` clause is the failure rule. That clause is also the **reader** the fatal-class map needs — it matches the pid @@ -1837,8 +1853,8 @@ the owner fixes. order puts the executor, the workspace lease and the transfers owner between the runtime and the Store, and each is stopped in turn — the executor first, since stopping it is what sets its Port-owning workers - terminating the captured process groups. Then custody and the registry, - which hold nothing durable. Then the Store, whose `terminate/2` releases the writer marker — + terminating the captured process groups. Then the tracing capability, + custody and the registry, which hold nothing durable. Then the Store, whose `terminate/2` releases the writer marker — see the marker invariant in ADR 0031. The socket path is already gone, left in place by step 3 for the next marker holder to remove, so the last act is the halt: **`0`**, or the class, @@ -1863,7 +1879,7 @@ the owner fixes. | The executor | What remains of **`teardown_ms`** | Nothing, in the executor itself: it neither traps exits nor defines `terminate/2`, so this stop returns quickly. What takes the time is the Port-owning workers it sets going, which the owner does not hold and cannot wait for | | The workspace lease | What remains of `teardown_ms` | Nothing: it has no `terminate/2` and holds no file — the lease *is* the live process, so stopping it revokes it | | The transfers owner | What remains of `teardown_ms` | Closing the open transfer descriptors its `terminate/2` holds (`transfers.ex:146-149`) | - | Custody, then the registry | What remains of `teardown_ms` | Nothing durable | + | The tracing capability, then custody, then the registry | What remains of `teardown_ms` | Nothing durable | | **The Store** | A **fixed 30 s**, its own phase | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | **"What remains" is one deadline, not one budget each.** The owner computes @@ -2080,14 +2096,33 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: So quiesce installs a fence the **Store** enforces, using machinery that already exists. After terminating an unsettled coordinator it commits an - **`advance_owner` transaction** for that session — the type the Store - already defines, binding `expected_owner_epoch` and - `expected_journal_version` and proposing a new incarnation - (`store.ex:168-178`, linearized at `state/local/state.ex:241-254`). Once it - commits, the session's `owner_epoch` has moved, and any older - `session_commit` the Store linearizes afterwards is refused - **`:stale_owner_epoch`** by the rule that already governs every commit - (`state.ex:548-551`). + **`advance_owner` transaction** for that session (`store.ex:168-178`, + built by `Store.advance_owner/6` at `store.ex:820-827`, linearized at + `state/local/state.ex:241-254`). Once it commits, the session's + `owner_epoch` has moved, and any older `session_commit` the Store + linearizes afterwards is refused **`:stale_owner_epoch`** by the rule that + already governs every commit (`state.ex:548-551`). + + **That transaction has six arguments and the plan names where each comes + from**, because a fence built from guesses is a fence that refuses the + wrong thing: + + | Argument | Where quiesce gets it | + | --- | --- | + | `session_id` | The session being fenced | + | `mutation_domain` | The ownership domain, as every owner transaction uses | + | `tx_id` | **Derived, not random**, by the discipline the coordinator already uses: `owner_identity/3` hashes a namespace, a succession identity and an attempt into a stable ID (`session_coordinator.ex:1346`, `:1490-1498`). Quiesce derives its own from the drain's identity — the session and the `command_id` it minted for that session's abort — so the fence has a preallocated, recoverable ID rather than a fresh guess, which is what the durability rule requires of any effect identity | + | `expected_owner_epoch`, `expected_journal_version` | Read **fresh** from `Store.ownership_head/3`, exactly as the coordinator reads them (`session_coordinator.ex:1337-1343`), so the fence binds the state it is actually fencing | + | `proposed_owner_incarnation_id` | A fresh incarnation, in the same form the coordinator mints (`fresh_incarnation/2`, `:1500`) | + + **The proposed incarnation is a fence marker, not an owner**, and nothing + inherits it. The next activation of that session builds its own candidate + from the head it reads at that moment — + `discover_and_advance_owner/1` reads `ownership_head/1` and then + `build_owner_candidate/2` (`session_coordinator.ex:1186-1196`, + `:1345-1359`) — so the fence's incarnation is simply the head that the next + activation supersedes. Fencing therefore costs the next activation one + ordinary epoch step and nothing else. That turns an unanswerable question into a decided one. An old transaction either wins the race to linearization — in which case it commits, is @@ -2306,7 +2341,8 @@ is fine — the Store was already stopped in step 6, and its `terminate/2` ran then. On the **fatal** path it was not fine, and an earlier draft left a real hole: for the classes where the Store is still alive (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, -`custody_lost`, `relay_lost`, `listener_lost`), nothing stopped the Store, so the halt +`custody_lost`, `capability_lost`, `relay_lost`, `listener_lost`), nothing +stopped the Store, so the halt left the marker file behind on a daemon that had shut down deliberately. The fail-stop path above therefore stops the Store on every fatal class **except** the two store classes, where it is already gone. @@ -2340,6 +2376,7 @@ die without a name for it. | `executor_lost` | The local executor exited | `fatal:executor_lost` | | `registry_lost` | The credential routing registry exited | `fatal:registry_lost` | | `custody_lost` | The credential custody process exited | `fatal:custody_lost` | +| `capability_lost` | The tracing capability exited | `fatal:capability_lost` | | `runtime_lost` | The runtime root exited | `fatal:runtime_lost` | | `relay_lost` | The admission relay exited, taking every outstanding admission ticket with it | `fatal:relay_lost` | | `listener_lost` | The listener exited | `fatal:listener_lost` | @@ -2362,10 +2399,12 @@ apart in an earlier revision and the numbers are gone for that reason. There is one row per linked process, and the transfers row exists only in a daemon that has one. -**`registry_lost` and `custody_lost` are fail-stop like every other row, and -that follows from ADR 0034 rather than adding to it.** That ADR makes a dead -registry answer `:unavailable` for every later resolution *until the host -recomposes*; in a daemon, recomposing is restarting the process. A daemon that +**`registry_lost`, `custody_lost` and `capability_lost` are fail-stop like +every other row, and that follows from ADR 0034 rather than adding to it.** +That ADR makes a dead registry answer `:unavailable` for every later +resolution *until the host recomposes*, and makes a sender that cannot +confirm its trace exclusion refuse rather than resolve; in a daemon, +recomposing is restarting the process. A daemon that kept running would serve a runtime whose every model invocation refuses for a reason no client can fix, which is exactly the shape the fail-stop rule exists for. @@ -2403,7 +2442,7 @@ path does — a `daemon/` subdirectory the owner created is removed — no lease yet, since none is started before a session is activated — and **every pid the composition function returned is stopped in reverse start order** — runtime, executor, workspace lease, transfers where it exists -— then custody and the registry, and the Store last, so its `terminate/2` +— then the tracing capability, custody and the registry, and the Store last, so its `terminate/2` releases the marker. Each of those stops is the same call and the same discipline as a shutdown @@ -2552,7 +2591,8 @@ next daemon removes before binding. opening that root with nothing to recover; eight of them in a daemon with transfers enabled and seven without — `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, - `relay_lost`, `listener_lost`, beside the two store classes. The set is closed for the + `capability_lost`, `relay_lost`, `listener_lost`, beside the two store + classes. The set is closed for the fixed set, so one of those dying without a class is a failing case rather than a silent `:shutdown`. A lease owner is deliberately not in this case: its own witness is below, and it asserts the daemon **keeps running**. @@ -2656,8 +2696,9 @@ next daemon removes before binding. five-hundred-and-thirteenth owner was started and that releasing one lease lets the next acquisition through. - **The credential processes are fatal like every other component.** The - registry and the custody process are each killed in their own case; the - daemon exits `registry_lost` and `custody_lost` respectively, sends that + registry, the custody process and the tracing capability are each killed in + their own case; the daemon exits `registry_lost`, `custody_lost` and + `capability_lost` respectively, sends that `fatal:` on the wire, and leaves no stale marker. - **The stop timeout is exercised, not assumed.** A session is made to hold the runtime's teardown past the shared teardown deadline. The case asserts the @@ -2728,8 +2769,12 @@ next daemon removes before binding. - **Every branch releases or converts its reservation.** One case per row of the resolution table: a fresh create, a replayed create against an active and a dormant session, a fresh resume, a replayed resume, a refusal, and a - call that never answers. Each asserts the daemon's remaining slot count - afterwards, so a branch that leaked a reservation shows up as a daemon that + call that never answers — the last one twice, once for a resume, resolved by + asking about the session ID the daemon holds, and once for a **create**, + resolved by replaying under the original `command_id`, reading the session + ID from the historical result and asking about that; the create case asserts + the replay started no coordinator and charged no second slot. Each asserts + the daemon's remaining slot count afterwards, so a branch that leaked a reservation shows up as a daemon that refuses early rather than as a silent drift. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves @@ -2762,14 +2807,14 @@ owned by core, the adapter or the executor appears as a **group with its owner**, because their counts are those components' business and naming them individually would make this table a copy that rots. -**The daemon's fixed processes — nine, eight without transfers:** +**The daemon's fixed processes — ten, nine without transfers:** | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | | **Daemon owner** | The `loopex daemon` command process, `GenServer.start/3` — **unlinked**, monitored immediately | Nothing; the command process holds a monitor | Itself; it halts the VM | The command process halts non-zero with `owner_lost`; the signal handler's backstop is the second route | | Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | | Credential **custody process** (ADR 0034), one for the one composed model configuration | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal | -| **Tracing capability** (ADR 0034) | Daemon owner, beside the other two | Daemon owner | Orderly step 6 | Treated as the registry is: daemon-fatal, since a sender that cannot exclude itself must not resolve | +| **Tracing capability** (ADR 0034) | Daemon owner, third, before composition | Daemon owner | Orderly step 6 | `capability_lost`, daemon-fatal: a sender that cannot confirm its trace exclusion refuses rather than resolves, so every model invocation would fail for a reason no client can fix | | **Store adapter** (ADR 0031) | The composition function, in the owner's process | Daemon owner | Orderly step 6, **last**, in its own fixed 30 s phase | `store_lost`, or `store_capacity_exceeded` on its own capacity refusal | | **Artifact transfers owner** | The composition function | Daemon owner | Orderly step 6 | `transfers_lost`. **Absent** where transfers are disabled | | **Workspace lease** | The composition function | Daemon owner | Orderly step 6 | `workspace_lease_lost` | @@ -2822,7 +2867,7 @@ survive arrives as `runtime_lost`. | **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies; its in-flight admission set goes with it, and the relay's ticket for any mutation it had authorized does not | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller attachment closes with `control_owner_lost`; observers stay attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch, its first grant waiting until the relay's outstanding tickets for that session settle | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | -| **Registry ↔ sender ↔ custody** | The **host** owns the registry and custody; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | +| **Registry ↔ sender ↔ custody** | The **host** owns the registry, custody and the tracing capability; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline, or a trace exclusion that cannot be confirmed | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | | **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the derived drain budget, tells clients, unlinks the socket only while it can still show it holds the marker, and then stops its linked processes in reverse order — lease owners, the relay, runtime, edges, and the Store last in its own fixed 30 s phase — each stop driven by a monitored helper calling `GenServer.stop/3` while the owner waits on its own link until the shared teardown deadline and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 3a7bc6472..20542f5fd 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -574,10 +574,10 @@ supervisor.** Its top-level component is one `GenServer` that traps exits and `start_link`s a **fixed set** of them: the five the composition function assembles in its caller's process — the Store adapter, the runtime root, the artifact transfers owner where enabled, the workspace lease and the local -executor — plus four of the daemon's own, the credential routing registry and -custody process ADR 0034 gives the host, the **admission relay** that holds a -ticket for every core call the daemon makes, and the listener. Nine where -transfers are enabled, eight where they are not. **Beside them it links one +executor — plus five of the daemon's own: the credential routing registry, the +custody process and the tracing capability ADR 0034 gives the host, the +**admission relay** that holds a ticket for every lease-authorized mutation, +and the listener. Ten where transfers are enabled, nine where they are not. **Beside them it links one lease owner per session under lease or acquisition**, started at the first lease operation rather than at activation, retired when the lease is free and nothing is outstanding, and capped at the 512 ADR 0032 already fixes. That one From 3966bc43a33426d98e1e38b3519ef2ff92347b30 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:08:41 -0700 Subject: [PATCH 103/585] plan(M5): split the no-answer reservation row by call kind The F3 table edit was lost when an earlier script aborted before writing: the prose and the witness carried the create/resume distinction while the resolution table still had one combined row. The row is now two, with the create resolved by replaying under its original command_id. --- docs/plans/M5-technical.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 6ff34b04d..d8cc00bf1 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -942,7 +942,8 @@ leaked until the daemon restarts: | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | | Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | | Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | -| Either call **crashing or timing out**, so the daemon has no result at all | **Held, then resolved by observation**: the daemon asks core whether that session is active and converts or releases accordingly. It does not guess, and it does not leak the slot | +| A **resume** crashing or timing out, so the daemon has no result | **Held, then resolved by observation**: the daemon holds the session ID, so it asks core about that session and converts or releases accordingly | +| A **create** crashing or timing out | **Held, then resolved by replay**: no session ID exists yet, so the daemon replays `session.create` under the same `command_id` — which returns the historical result and starts no coordinator (`control.ex:901-907`) — reads the session ID from it, and then resolves as a resume does. The replay carries the same reservation key, so it charges no second slot | **That last row is not hypothetical, and the reason is a default nobody chose.** The daemon reaches core through `Loopex.Runtime`, whose From 812abf9e41dd70c16a51548e3c521578270e7668 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:14:07 -0700 Subject: [PATCH 104/585] plan(M5): give every core change a core witness M. Three of core's five changes were witnessed only downstream, and three of their properties cannot be reached from there: quiesce's `absent` branch needs a `Control` entry whose coordinator has already died (control.ex:821-823), `exclude_self/1`'s fail-closed path needs the tracer mid-restart, and `Control` pruning an excluded sender needs that sender's DOWN. All three are core-internal states a daemon cannot construct through the socket. Each core change now names a core witness with its cases and lane, all fast: `apps/loopex/test/runtime_quiesce_test.exs` (new) for the two-phase admission order, the empty-set zero budget, the `absent` branch and the deadline fence with the paused-transaction case; the existing `apps/loopex/test/cancellation_test.exs` for the abort-path split, which is the file that already drives an abort against a receipt arriving mid- reduction; and the existing `apps/loopex/test/trace_session_test.exs`, extended, for exclusion across a tracer restart, the fail-closed path and the set returning to baseline. The downstream witnesses stay with their own job stated -- the daemon suite proves the drain happens in a real stop, the adapter suite proves a real invocation is untraceable -- and neither is asked to reach the branches above. Outcome 4's witness column and the closure matrix row carry the same list. L1: `fatal:owner_lost` becomes the bare `owner_lost`, matching the stderr convention two paragraphs away; nothing writes a `fatal:` reason except the wire, and this class reaches no client. L2: "host-custody cases" becomes "host-owned-process cases" in all three places, since the tracing capability is host-started too -- and the per-host case tables gain it, including the daemon's stop-and-failed-start case. --- ...andoff-over-bootstrap-channel-technical.md | 10 +++--- docs/plans/M5-technical.md | 36 +++++++++++++++++-- docs/plans/M5.md | 4 +-- 3 files changed, 40 insertions(+), 10 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 0d2295ad8..2688128bb 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -754,7 +754,7 @@ Three proofs are new: three functions exist with their exact identities and that a one-byte canary credential appears in no captured message or entry, so neither of the first two can pass vacuously. -- **Host custody, proved at each host rather than in the adapter.** The +- **The host-owned processes, proved at each host rather than in the adapter.** The adapter's test tree cannot prove a claim about the CLI's or the daemon's composition, and an earlier draft filed all three there. Each case lives where its subject lives, named to the file and the case so the closure @@ -762,9 +762,9 @@ Three proofs are new: | Host | File | Cases | Lane | | --- | --- | --- | --- | - | Reference CLI | `apps/loopex_cli/test/credential_custody_test.exs` | `reads the credential variable exactly once at composition`; `deletes the credential variable from the VM environment`; `custody state is redacted in a forced crash report` | fast | - | App-server host | `apps/loopex_app_server/test/credential_custody_test.exs` | the same three | fast | - | Daemon | `apps/loopex_daemon/test/credential_custody_test.exs` | the same three, plus `custody and registry are stopped with the daemon and on a failed start` | fast | + | Reference CLI | `apps/loopex_cli/test/credential_custody_test.exs` | `reads the credential variable exactly once at composition`; `deletes the credential variable from the VM environment`; `custody state is redacted in a forced crash report`; `the tracing capability is composed and reaches the current tracer` | fast | + | App-server host | `apps/loopex_app_server/test/credential_custody_test.exs` | the same four | fast | + | Daemon | `apps/loopex_daemon/test/credential_custody_test.exs` | the same four, plus `registry, custody and capability are stopped with the daemon and on a failed start` | fast | Each proves that composition reads the variable exactly once, deletes it from the VM's environment, and that the holding process's `format_status/1` @@ -775,7 +775,7 @@ Three proofs are new: The parent-environment and concurrent-independence proofs and the resolution failure cases belong in `credential_plane_test.exs` beside the cases they generalise; the drift case and the trace-exclusion case stay in the adapter's -tree with it. The **host-custody cases do not**: each lives at its own host, +tree with it. The **host-owned-process cases do not**: each lives at its own host, as the bullet above assigns them — `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/` — because the adapter's tree cannot prove a claim about another application's composition. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d8cc00bf1..0205c6cb1 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -145,9 +145,9 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-custody cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/1` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/1` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -304,6 +304,34 @@ Every other tracked file under `docs/operator/` and deliberately, and the derived checklist in Outcome 5's evidence row is what makes that auditable rather than asserted. + +**Every core change has a core witness, named here to file, case and lane.** +Three of the five were witnessed only downstream — in the daemon's lifetime +suite and the adapter's credential suite — and three of their properties +cannot be reached from there at all: quiesce's `absent` branch needs a +`Control` entry whose coordinator has already died (`control.ex:821-823`), +`exclude_self/1`'s fail-closed path needs the tracer mid-restart, and +`Control` pruning an excluded sender needs that sender's `DOWN`. All three are +core-internal states a daemon cannot construct through the socket. + +| Core change | Core witness | Cases | Lane | +| --- | --- | --- | --- | +| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` | as that file already states | fast | +| Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | +| **`quiesce/2`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too` | fast | +| **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | +| **`Loopex.Trace.exclude_self/1` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | + +The paused-transaction case in `runtime_quiesce_test.exs` is the one that +needs the adapter's fault probe, injecting at `:before_linearization` +(`local.ex:252`); it stays a core test because what it proves is core's +fence, not the adapter's behaviour. + +**The downstream witnesses stay**, and their job is different: the daemon's +lifetime suite proves the drain happens in the stop sequence a real operator +triggers, and the adapter's credential suite proves a real invocation is not +traceable. Neither can reach the branches above, and neither is asked to. + **Test honesty.** Future test bodies are written with their implementation; a missing witness is never a pass. **Every witness this pair or an ADR in this set describes names three things when it is written: the exact file, the case @@ -2628,7 +2656,9 @@ next daemon removes before binding. - **`owner_lost`, by the monitor and not by a later signal.** The owner is killed while the daemon is otherwise healthy and **nothing else happens**: no signal is sent. The case asserts the process halts non-zero with - `fatal:owner_lost` on `stderr` within a bounded time of the kill, which is + `owner_lost` on `stderr` within a bounded time of the kill — the bare class, + since nothing writes a `fatal:` reason anywhere but the wire and there is no + client to tell — which is the command process's monitor doing it. A second case kills the owner and *then* sends `SIGTERM`, asserting the same class by whichever route wins, so the two cannot both fail silently. diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 20542f5fd..cc786d397 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -57,9 +57,9 @@ second loop and no new durable command. | 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | -| 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | +| 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the credential is named by an opaque token bound at composition, whose **resolution** is what happens per invocation, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, ADR 0034's host-custody cases at `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the credential is named by an opaque token bound at composition, whose **resolution** is what happens per invocation, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, ADR 0034's host-owned-process cases at `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). From 8bafacf73f85880c81a0edce59bff5b282ce6ff0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:16:58 -0700 Subject: [PATCH 105/585] plan(M5): pause the fence witness through core's own test store The paused-transaction case for quiesce's fence named the shipped adapter's fault probe from core's test tree, which cannot see that module: core depends on the protocol and telemetry only, and the dependency direction forbids a test-only edge to a store implementation. Core's controllable store already holds a transaction pending outside its process for exactly this order and refuses a stale owner advance, so both passages name it and its seam, and leave the adapter's probe to the adapter's suite. --- docs/plans/M5-technical.md | 26 +++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0205c6cb1..2715628cc 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -322,10 +322,18 @@ core-internal states a daemon cannot construct through the socket. | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/1` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | -The paused-transaction case in `runtime_quiesce_test.exs` is the one that -needs the adapter's fault probe, injecting at `:before_linearization` -(`local.ex:252`); it stays a core test because what it proves is core's -fence, not the adapter's behaviour. +The paused-transaction case in `runtime_quiesce_test.exs` pauses the +transaction through core's own controllable store, not the shipped adapter: +`apps/loopex` depends on nothing but the protocol and telemetry +(`apps/loopex/mix.exs:34-36`), the dependency direction forbids a test-only +edge to a store implementation, and `Loopex.M1RuntimeTestStore` already holds +a transaction pending outside its process for exactly this order +(`hold_next_record_before_linearization/3`, +`apps/loopex/test/support/m1_runtime_helper.exs:40-46`) and refuses a stale +`advance_owner` with `:stale_owner_epoch` (`:598-599`). It stays a core test +because what it proves is core's fence; the shipped adapter's own +`:before_linearization` probe (`local.ex:252`) is the same seam for the +adapter's suite, not for this one. **The downstream witnesses stay**, and their job is different: the daemon's lifetime suite proves the drain happens in the stop sequence a real operator @@ -2518,9 +2526,13 @@ next daemon removes before binding. - **The fence is a Store fence, proved against a transaction in flight.** This is the case a terminated coordinator alone would fail. A session's terminal transaction is **paused inside the Store, before linearization**, - using the adapter's existing fault probe — `checkpoint(state.fault_probe, - transition, :before_linearization)` at `local.ex:252` is exactly that - injection point. With it paused, the coordinator is killed, so the caller of + using core's controllable store, `Loopex.M1RuntimeTestStore`, whose + `hold_next_record_before_linearization/3` keeps the caller pending outside + the store process for exactly this order + (`apps/loopex/test/support/m1_runtime_helper.exs:40-46`); the shipped + adapter's `checkpoint(state.fault_probe, transition, :before_linearization)` + at `local.ex:252` is the same seam, but core's tree cannot reach that + module. With it paused, the coordinator is killed, so the caller of that transaction is dead while the transaction itself is still pending. Quiesce then runs its deadline path: it terminates the coordinator, waits for the `DOWN`, and commits the `advance_owner` fence for that session. The From efb2a181592e874595e9cc517a40e01e5ff00e60 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:39:17 -0700 Subject: [PATCH 106/585] plan(M5): sweep the last socket-unlink residue P0-1. Six sites still said a departing daemon unlinks, against the rule at M5-technical:1610-1642, ADR 0031-technical:79 and ADR 0032-technical:108: M5.md outcome 1, the two-ways paragraph and the store-loss paragraph; M5-technical's supervisor-alternative bullets, the step-6 sentence, the fifth-component argument and the signals boundary row. All now say the listener closes and the pathname is left for the next verified marker holder. Swept by grep across docs/, not by reading around the known sites. --- docs/plans/M5-technical.md | 16 +++++++++------- docs/plans/M5.md | 10 +++++----- 2 files changed, 14 insertions(+), 12 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 2715628cc..24848043e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -711,8 +711,9 @@ two different roots hold two different markers and have no exclusion between them at all. An override that let them name one path would put two daemons with equal claim on one file, which no rule in this plan can adjudicate. Inside one root there is exactly one marker holder, so there is exactly one -daemon entitled to bind or unlink. An override therefore moves where the rule -applies, never which root it applies within. +daemon entitled to bind, and exactly one entitled to remove a pathname a +predecessor left. An override therefore moves where the rule applies, never +which root it applies within. **Readiness.** Exactly one line on `stdout`, and nothing else on that stream. It is **one JSON object on one line**, not a space-separated phrase, because a @@ -1195,7 +1196,7 @@ shutdown, and three facts in the code force it. the owner's linked edges, so its exit arrives at the owner as `{:EXIT, _owned_pid, reason}` and the owner runs `cleanup/1` **immediately** — stopping every owned edge including the Store, and releasing the marker — - before the daemon has told a single client or unlinked the socket. + before the daemon has told a single client or closed its listener. - And an OTP `Supervisor` cannot serve here either, which an earlier draft of this section got wrong. `Loopex.Runtime.start_link/1` returns `{:ok, %Loopex.Runtime{}}` — a **struct**, not `{:ok, pid}` — so the runtime @@ -1357,8 +1358,9 @@ same result. The Store is moved to the end because its `terminate/2` releases the writer marker, and the marker must outlive every operation the owner can end; custody and registry hold nothing durable, so stopping them before it costs -nothing and keeps the one exception to one line. The socket is unlinked -earlier still, for the reason the socket-ownership rule below gives. +nothing and keeps the one exception to one line. The socket **pathname is +left where it is**, on this path and every other, for the reason the +socket-ownership rule below gives. The composition function therefore returns **every pid it linked**, not only the ones the daemon names in prose: a map carrying `store`, `runtime` (the @@ -1572,7 +1574,7 @@ accounting runs before the strategy clause and the supervisor terminates with reason `:shutdown`, so the child's real reason is logged and discarded — exactly the information the daemon exists to report. It cannot host the runtime at all, because of the struct return above. And its own termination -would leave the socket unlinked and no client told, so a fifth component +would leave the listener open and no client told, so a fifth component would have been needed to do the work steps 3 and 4 describe — which is the owner, arrived at by a longer road. @@ -2912,7 +2914,7 @@ survive arrives as `runtime_lost`. | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry, custody and the tracing capability; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline, or a trace exclusion that cannot be confirmed | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the derived drain budget, tells clients, unlinks the socket only while it can still show it holds the marker, and then stops its linked processes in reverse order — lease owners, the relay, runtime, edges, and the Store last in its own fixed 30 s phase — each stop driven by a monitored helper calling `GenServer.stop/3` while the owner waits on its own link until the shared teardown deadline and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the derived drain budget, tells clients, closes the listener while **leaving the socket pathname for the next verified marker holder**, and then stops its linked processes in reverse order — lease owners, the relay, runtime, edges, and the Store last in its own fixed 30 s phase — each stop driven by a monitored helper calling `GenServer.stop/3` while the owner waits on its own link until the shared teardown deadline and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` left by any exit path | Only a daemon that has acquired and verified the marker removes it, at startup, before binding; no daemon removes one on its way out, so no predecessor can delete a successor's socket | The loser of two simultaneous starts exits without touching the socket; a client meeting a stale path is refused rather than hung | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index cc786d397..7a4e1b1d1 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -54,7 +54,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the socket unlinked while the marker is still held, the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -361,8 +361,8 @@ A daemon ends in one of two ways and the plan keeps them apart, because the code does. **A daemon-initiated stop** is a drain and then a teardown: refuse new connections and new admissions; **quiesce the runtime within the composed cleanup grace**; attempt one best-effort stop record per open connection and -close it; unlink the socket while the marker is still held; stop the lease -owners and then the runtime, which ends crash-equivalently whatever the drain +close it; close the listener and **leave the socket pathname**, which no exit +path removes; stop the lease owners and then the runtime, which ends crash-equivalently whatever the drain did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. @@ -423,8 +423,8 @@ it does not. append error by terminating itself, and its `terminate/2` releases the marker on the way out, so by the time the daemon observes anything the store is gone and the marker is already released. It is a fail-stop: refuse service, close -every connection with the reason, stop the executor, unlink the socket, exit -non-zero. There is no "stop the Store last" step to run when the Store is what +every connection with the reason, stop the executor, leave the socket +pathname where it is, exit non-zero. There is no "stop the Store last" step to run when the Store is what died — though on a fatal class where the Store is still alive the daemon does stop it, because the halt runs no `terminate/2` and the marker would otherwise be left behind. The From b92cf9d6c6cce79f6d81dc43a3ebf1d703db09e8 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:42:02 -0700 Subject: [PATCH 107/585] plan(M5): quiesce returns four keys and derives its own budget P0-2. The signature returns `settled`, `unsettled`, **`absent`** and `budget_ms`, and its argument is the daemon's teardown deadline rather than a drain budget. `absent` is neither settled nor unsettled and had a witness and a classification paragraph but no place in the result. P0-4. The drain budget cannot be computed by the daemon: each `g_i` is the grace that session **committed** (session_coordinator.ex:422), while `--cleanup-grace-ms` is the default a new session is composed with (control.ex:890-891), so a root carrying sessions composed earlier holds graces the daemon has never seen. Core derives the budget and returns it as `budget_ms`; the daemon reports that figure in its stop line and in `daemon.status`, and the operator bound says the drain term is read from what the daemon reports rather than computed from a flag. P0-3. The fence `tx_id` derived from the abort's `command_id`, which does not exist for an `absent` session. Core now mints one `drain_id` per `quiesce/2` call with the generator it already uses (session_directory.ex:545-548), and every fence derives its `tx_id` from `(drain_id, session_id)`. Recoverability is stated as the rule actually asks: the derivation is total, and `drain_id` is reported on the stop line, so nothing new is journaled for the drain's own sake -- the fence transactions are the durable record and each carries its derived ID. P1-20. The fence has three outcomes, not two: it commits; it is refused `:stale_owner_epoch` because the old transaction linearized first, in which case the session is classified from the journal and was never fenced; or it answers `commit_unknown`, in which case it is retried under the same derived `tx_id` until the deadline and then reported `unsettled` with `fence: :unknown`. The "no transaction can still commit" claim is weakened to what the mechanism gives, and the three cases join the core witness. P1-17. `concurrent_attachments_test.exs` does not exist; it is marked new and its cases named. --- docs/plans/M5-technical.md | 127 ++++++++++++++++++++++++++++--------- docs/plans/M5.md | 17 +++-- 2 files changed, 109 insertions(+), 35 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 24848043e..0e08b4751 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -280,11 +280,16 @@ because both are facts an operator cannot derive from the software and a reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop**: the - derived session drain, plus the fixed five-second budget covering every - non-Store action after it, plus the fixed 30-second Store phase — and, with it, that a shorter external - service-manager timeout turns the stop into a **forced shutdown**, where - work that would have settled does not and the writer marker may be left for - the next daemon's verified recovery. It must also distinguish the **usual + drain budget core derives, plus the fixed five-second budget covering every + non-Store action after it, plus the fixed 30-second Store phase — and, with + it, that the drain budget is **not** read off the daemon's own + `--cleanup-grace-ms`, because each session drains under the grace it + committed and a root may carry sessions composed earlier, so the page must + point an operator at the figure the daemon **reports** in its stop line and + in `daemon.status` rather than at one they can compute from flags. And that + a shorter external service-manager timeout turns the stop into a **forced + shutdown**, where work that would have settled does not and the writer + marker may be left for the next daemon's verified recovery. It must also distinguish the **usual millisecond** Store release from that 30-second **safety ceiling**, so the number is read as a bound on the worst case rather than as the cost of every stop. Nothing is written until the implementation exists; this row is what @@ -316,9 +321,9 @@ core-internal states a daemon cannot construct through the socket. | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` | as that file already states | fast | +| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/2`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too` | fast | +| **`quiesce/2`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale classifies the session from the journal`; `a fence answering commit_unknown is retried under the same derived tx_id and reported unsettled with fence: :unknown`; `every fence in one drain derives its id from the same drain_id` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/1` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | @@ -1716,17 +1721,28 @@ state. The contract is three clocks: | Clock | What it bounds | Where the number comes from | | --- | --- | --- | | **`g`**, each session's committed `cleanup_grace_ms` | The cancellation of that session's effects, and nothing else | The session's own composition; already used by `Loopex.Executor.cancellation_bounds/1` | -| **`drain_ms`** | The whole drain, across every session | Derived: `max` over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` (`apps/loopex/lib/loopex/executor.ex:456-474`, where `cli_backstop_ms` is defined as `observe + reserve + terminal` and documented as "the sum a process-liveness backstop must cover"). `g` itself is never a deadline | +| **`budget_ms`**, the drain budget | The whole drain, across every session | Derived **by core, inside `quiesce/2`**, and **returned** in its result: `max` over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` (`apps/loopex/lib/loopex/executor.ex:456-474`, where `cli_backstop_ms` is `observe + reserve + terminal`, documented as "the sum a process-liveness backstop must cover"). The daemon does not compute it, because it does not hold the `g_i` | | **`teardown_ms`, fixed at `5_000`** | **One absolute deadline covering every non-Store action after the drain** — the `daemon.stopping` writes, closing the connections, closing the listener, the lease owners, the relay, the runtime, the executor, the workspace lease, transfers, custody and the registry | A plan decision, and the rationale is that each of those is a bounded write or a stop of a process with no `terminate/2` to run: milliseconds apiece, so five seconds is a ceiling none of them should approach and an upper bound an operator can add up | | **The Store phase** | The Store's stop alone | A **fixed 30 s**, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of `g` and of `teardown_ms` | -`drain_ms` is derived rather than chosen because the cancellation it waits on +The budget is derived rather than chosen because the cancellation it waits on is already bounded by core: `cli_backstop_ms` is the number core itself says a liveness backstop must cover for a session with that grace, so a drain that waits exactly that long waits neither less than the cancellation needs nor longer than core can justify. Taking the maximum over the drained sessions — not the sum — is what keeps the bound flat as sessions multiply. +**And core derives it because the daemon cannot.** Each `g_i` is the grace +that session **committed**, read from its durable state +(`session_coordinator.ex:422`); the daemon's `--cleanup-grace-ms` is the +default a *new* session is composed with (`control.ex:890-891`), not a fact +about sessions already in the root. A root carrying sessions created under an +earlier composition therefore holds graces the daemon has never seen. An +earlier revision had the daemon compute the budget from its own option, which +would have been wrong for exactly the roots a daemon is for. So `quiesce/2` +derives it from the durable graces and **returns** it as `budget_ms`, and the +daemon reports that figure rather than one it assumed. + **The Store phase is fixed, not `max(g, 30_000)`.** The previous revision's `max` made an operator's grace able to *lengthen* the Store phase, which is the one phase whose length has nothing to do with any session. Thirty seconds @@ -1757,14 +1773,17 @@ budget of its own to spend. **So the operator-facing bound is stated, once, and it adds up:** -> **Maximum graceful stop = `drain_ms` + 5 s + 30 s.** - -That maximum is as large as the composed grace makes it: `drain_ms` is -derived from `cli_backstop_ms`, which grows with `g`, so an operator who -composes a grace of days has told the daemon it may drain for days. The bound -is a statement about *this* daemon's configuration rather than a constant, and -the operator documentation says so where it says what to set -`TimeoutStopSec` to. A service manager that kills the daemon sooner than that +> **Maximum graceful stop = `budget_ms` + 5 s + 30 s.** + +**`budget_ms` is not knowable from the daemon's flags alone**, and the +operator page says so rather than implying a constant. The composed +`--cleanup-grace-ms` bounds the sessions this daemon *creates*; a root +carrying sessions created earlier may drain longer, because each session +drains under the grace it committed. What an operator can rely on is that the +figure actually used is **reported**: the daemon's stop line carries the +`budget_ms` core returned, and `daemon.status` carries the budget the daemon +would use if it were asked to stop now. A `TimeoutStopSec` is therefore set +from an observed figure rather than a guessed one. A service manager that kills the daemon sooner than that turns the stop into a forced shutdown — the journal is still crash-equivalent, but work that would have settled does not, and the marker may be left for the next daemon's verified stale-writer recovery. The operator documentation states the bound @@ -1819,8 +1838,9 @@ the owner fixes. clients yet and nothing is closed: the connections stay open across the drain, because a client that is about to be told something true is better served by being told it than by an early close. -2. **The runtime is quiesced within `drain_ms`.** The owner calls core's - `quiesce/2` with that derived deadline and waits for its answer, which +2. **The runtime is quiesced within the budget core derives.** The owner + calls core's `quiesce/2`, passing its own teardown deadline so core will + not overrun what the daemon has left, and waits for its answer, which names the sessions that settled and the sessions that did not — and, by the time it answers, every session it could not settle has already been fenced and terminated inside core. This is the drain; what it does, and what it @@ -1996,10 +2016,24 @@ on 2026-09-20 and gave it one. The mechanism is a **fourth core change**, beside concurrent attachment, the existence query and the trace exclusion: ```elixir -Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: - {:ok, %{settled: [session_id], unsettled: [session_id]}} +Loopex.Runtime.quiesce(runtime, teardown_deadline_ms) :: + {:ok, %{ + settled: [session_id], + unsettled: [session_id], + absent: [session_id], + budget_ms: non_neg_integer() + }} ``` +**Four keys, and two of them are answers to questions the daemon cannot +ask.** `absent` names the sessions `Control` still held as active whose +coordinator was already gone, which is neither settled nor unsettled and must +not be counted as either. `budget_ms` is the drain budget **core derived and +used**, returned because the daemon cannot compute it — the argument below. +The single argument is the daemon's own clock, not a drain budget: it is the +teardown deadline the daemon must still meet afterwards, so core can refuse to +exceed what the caller has left. + **Three parts, in order, and the first two are one thing split in half.** 1. **Phase one: every live coordinator admits the abort, and then stops.** @@ -2048,6 +2082,8 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: (`apps/loopex/lib/loopex/executor.ex:456-474`), and over an **empty** set of drained sessions that maximum is **`0`**: a daemon with nothing active drains instantly rather than waiting out a number derived from nothing. + Core **returns** the figure it used as `budget_ms`, because a daemon that + cannot compute it cannot report it either. Inside the budget each session's cancellation runs under its own `g`, through `Loopex.Executor.cancel/4` (core), exactly as the coordinator @@ -2150,10 +2186,33 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: | --- | --- | | `session_id` | The session being fenced | | `mutation_domain` | The ownership domain, as every owner transaction uses | - | `tx_id` | **Derived, not random**, by the discipline the coordinator already uses: `owner_identity/3` hashes a namespace, a succession identity and an attempt into a stable ID (`session_coordinator.ex:1346`, `:1490-1498`). Quiesce derives its own from the drain's identity — the session and the `command_id` it minted for that session's abort — so the fence has a preallocated, recoverable ID rather than a fresh guess, which is what the durability rule requires of any effect identity | + | `tx_id` | **Derived, not random**, by the discipline the coordinator already uses: `owner_identity/3` hashes a namespace, a succession identity and an attempt into a stable ID (`session_coordinator.ex:1346`, `:1490-1498`). Quiesce derives its own from **`(drain_id, session_id)`** — see below | | `expected_owner_epoch`, `expected_journal_version` | Read **fresh** from `Store.ownership_head/3`, exactly as the coordinator reads them (`session_coordinator.ex:1337-1343`), so the fence binds the state it is actually fencing | | `proposed_owner_incarnation_id` | A fresh incarnation, in the same form the coordinator mints (`fresh_incarnation/2`, `:1500`) | + **`drain_id` is one identity per `quiesce/2` call, and it has to be, because + the abort's `command_id` is not available for every fenced session.** An + earlier revision derived the fence's `tx_id` from that abort — which works + for a session that was drained and fails for an `absent` one, where no + abort is admitted at all. So core mints **one** `drain_id` when the call + begins, with the generator it already uses for identifiers of its own + (`:crypto.strong_rand_bytes(16)` rendered base16, + `session_directory.ex:545-548`), and every fence in that drain derives its + `tx_id` from `(drain_id, session_id)`. One identity, every session, drained + or absent. + + **What makes that recoverable, which is the property the durability rule + actually asks for.** The rule is that a preallocated ID be *recoverable + from the owning command or operation identity* — not that the identity + itself be durable. Here the owning operation is one drain, and two things + make its fences recoverable without journaling anything new: the derivation + is total, so given `drain_id` every fence ID in that drain can be + recomputed; and `drain_id` is **reported** on the daemon's stop line beside + the budget, so an operator reconciling a root has the one value the + derivation needs. Nothing about the drain is written to the journal for its + own sake — the fence transactions are the durable record, and each carries + its own derived ID. + **The proposed incarnation is a fence marker, not an owner**, and nothing inherits it. The next activation of that session builds its own candidate from the head it reads at that moment — @@ -2163,12 +2222,22 @@ Loopex.Runtime.quiesce(runtime, drain_deadline_ms) :: activation supersedes. Fencing therefore costs the next activation one ordinary epoch step and nothing else. - That turns an unanswerable question into a decided one. An old transaction - either wins the race to linearization — in which case it commits, is - observed, and the session's durable state includes it — or it loses, and is - refused as stale. Either way, when `quiesce/2` returns, **no transaction - for an unsettled session can still commit**, and the daemon's report is - true when it is read rather than true when it was written. + That turns an unanswerable question into a decided one, and the decision + has exactly three outcomes — an earlier revision claimed only the first + two and overstated what the mechanism gives: + + | Outcome | What it means | How the session is reported | + | --- | --- | --- | + | The fence **commits** | The epoch has moved; any older `session_commit` linearized afterwards is refused `:stale_owner_epoch` | `unsettled`, fenced | + | The fence is **refused `:stale_owner_epoch`** | The old transaction linearized **first** and committed. The fence lost the race, which means there is nothing left to fence: the session's durable state already includes that commit | Classified **from the journal**, as whatever that commit made it — settled by its own terminal if it carried one. It is not reported as fenced, because it was not | + | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | Retried with the **same derived `tx_id`**, which is idempotent by construction, until the drain deadline; if it is still unknown then, the session is reported `unsettled` with `fence: :unknown` | + + So the claim the plan makes is the one the mechanism supports: when + `quiesce/2` returns, every session it reports as fenced has had its epoch + moved, and every session it reports otherwise is classified from what the + journal actually holds. What it does **not** claim is that no transaction + anywhere can still commit — a fence that is itself `commit_unknown` is + precisely the case where the daemon says so rather than pretending. **The classification quiesce returns has three lists, not two**, because `Control` can hold an entry whose coordinator is already dead: its `DOWN` @@ -2212,7 +2281,7 @@ of `max(10_000, grace_ms + 2_000)` from that same grace still. **What queues while the owner waits for it.** The owner is blocked in the -`quiesce/2` call for at most `drain_ms`, and while it is blocked it is not +`quiesce/2` call for at most the budget core derives, and while it is blocked it is not reading its mailbox: a linked component's `{:EXIT, …}` waits, as does a second signal. That is safe in one direction and deliberate in the other. The wait is bounded, so nothing waits indefinitely; and when the call returns, the owner diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 7a4e1b1d1..385364edb 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -394,9 +394,12 @@ the second loop this milestone forbids, and it could not admit a durable command on its own authority at all. **A graceful stop has a stated maximum**, because an operator configuring a -service manager needs one: the derived drain budget, plus **five seconds** for -every non-Store action after it — the stop records, the closes, and every stop -but the Store's — plus a fixed **thirty-second** Store phase. A +service manager needs one: the drain budget **core derives and reports**, plus +**five seconds** for every non-Store action after it — the stop records, the +closes, and every stop but the Store's — plus a fixed **thirty-second** Store +phase. The drain term is core's because each session drains under the grace it +committed, which a daemon reading its own flag would not know for a session +composed earlier. A service manager that kills the daemon sooner turns the stop into a forced shutdown — the journal stays crash-equivalent, but work that would have settled does not, and the writer marker may be left for the next daemon's @@ -929,9 +932,11 @@ it displaced and why: maintainer settled the **protocol generation naming** — both generations on `loopex.experimental/N`, which renames the released generation-1 string under the 0.x experimental policy — and made the **daemon operator page's stop bound -a closure obligation**: that page must state the maximum graceful stop, what a -shorter service-manager timeout turns a stop into, and the usual millisecond -Store release against its thirty-second ceiling. Both are written into the +a closure obligation**: that page must state the maximum graceful stop, that its drain term is the +figure the daemon reports rather than one an operator computes from +`--cleanup-grace-ms`, what a shorter service-manager timeout turns a stop +into, and the usual millisecond Store release against its thirty-second +ceiling. Both are written into the sections they govern. Drafting that page now was rejected, because it would document a component that does not exist; the obligation is what carries it to closure instead. From 140959032dfc7bb3ca4b67f67932977da20f612b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:46:18 -0700 Subject: [PATCH 108/585] plan(M5): one exclusion call with two inputs; resolve by replay P0-6. The trace exclusion was stated three ways -- "no function-level list can work", "both mechanisms", and a budget entry calling the MFA list dropped. It is now one core API, `Loopex.Trace.exclude_self(capability, functions: [mfa])`, installing both the match-specification clear ADR 0030 names and the process flag its callees need. The **adapter supplies its own MFAs**, so core never names an adapter function and the dependency direction is intact -- stated in one sentence where the API is defined. The list is exactly three, `route_credential/2` included because it carries the token, and the same three are used everywhere. What was dropped is sink-time redaction and the module-wide codec exclusion, not the MFA list; the budget says so. The core witness gains a case asserting the named MFAs produce no raw message before any process flag is set. P0-5. Resolution by observation used an observer that cannot discriminate. A resume's no-answer was resolved by the existence query, which answers `present` for any resume target whether or not this resume activated it -- the two answers that must differ are identical. It now replays under the original `command_id` and reads `disposition`/`residency`, as the create row does. An attach's no-answer had no observer at all, core exposing no attachment count: the reservation is keyed by the **connection**, which ADR 0032 binds to at most one attachment (0032-technical:126-129), so the daemon closes that connection and its ordinary teardown detaches what it held. ADR 0032 now states that an attachment never outlives its connection, which is what makes a connection a sufficient handle. The witness is rewritten so both branches can differ: two resume sub-cases that the existence query would answer identically, and an attach case asserting core holds one fewer attachment with no count ever read. --- ...tachment-residency-and-replay-technical.md | 7 +- ...andoff-over-bootstrap-channel-technical.md | 111 ++++++++------- docs/plans/M5-technical.md | 127 ++++++++++++------ docs/plans/M5.md | 35 ++--- 4 files changed, 171 insertions(+), 109 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 4dbf63c25..bc8b6c179 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -126,7 +126,12 @@ unchanged: every existing-session mutation in generation 2 carries a schema digest of its own. A connection is one attachment after `session.attach`; generation 2 permits a connection to hold at most one attachment at a time and a client process to hold as many -connections as the residency limits admit. +connections as the residency limits admit. **An attachment never outlives its +connection**: closing a connection — because the client went away, because the +daemon is stopping, or because the daemon gave up on a request that never +answered — detaches the core attachment that connection held. That is what +makes a connection a sufficient handle on an attachment, and it is why a +daemon needs no attachment count from core to release what it reserved. The core EventDispatcher and Control retain multiple live attachment IDs and incarnations for one session. A new distinct attachment does not implicitly diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 2688128bb..b0a667d3b 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -282,21 +282,18 @@ boundary, not an absolute: already protects that process — the sender installs its own group-leader sink so no IO request can carry anything out of it, it is unregistered, and it reports only an atom or a `{:error, atom}` pair to the guardian. -- **What keeps credential bytes out of a trace: the credential-bearing - *process* is excluded before it resolves anything.** ADR 0030 requires the - key-bearing call to be excluded by match specification *before* delivery - (`0030-…-technical.md:27`), and this pair has now twice failed to satisfy - it. The first attempt was sink-time redaction, which is too late because - tracing delivers the raw call tuple to the tracer first (`trace.ex:331`, - `:152`, `:219`). The second was an excluded-MFA list naming this adapter's - own functions — and that fails for a reason worth recording, because it is - the reason no function-level list can work here: - - **A function that carries the credential calls functions it does not own.** - `ProviderCodec.send/3` hands the encoded credential frame to - `:gen_tcp.send/2`. A trace session that names `:gen_tcp` explicitly sees the - frame, whatever this adapter's modules are excluded. Reproduced, with a - canary standing in for the credential: +- **What keeps credential bytes out of a trace: one core call that does two + things.** ADR 0030 requires the key-bearing call to be excluded by match + specification *before* delivery (`0030-…-technical.md:33-35`). That is + necessary and it is not sufficient, and this pair states both halves + together rather than replacing one with the other: + + **A match specification alone cannot hold, because a function that carries + the credential calls functions it does not own.** `ProviderCodec.send/3` + hands the encoded credential frame to `:gen_tcp.send/2`; a trace session + that names `:gen_tcp` explicitly sees the frame, whatever this adapter's + own functions are excluded. Reproduced, with a canary standing in for the + credential: ``` :trace.function(session, {:gen_tcp, :send, 2}, true, [:local]) @@ -308,29 +305,42 @@ boundary, not an absolute: future one, is outside the list again. An enumeration of callees is not a contract anyone can keep. - **So the exclusion is by process, and it is mandatory.** The sender — the - short-lived process that resolves the credential and writes the frame — - calls a core API **before it resolves anything**: + **So the core API takes both, and the adapter supplies the function list.** + The sender — the short-lived process that resolves the credential and writes + the frame — calls, **before it resolves anything**: ```elixir - Loopex.Trace.exclude_self(tracer) # returns only once the exclusion is installed + Loopex.Trace.exclude_self(capability, functions: [{module, function, arity}]) ``` - It returns `:ok` once this process is excluded from **every** live trace + One call, two inputs, one core change. Core installs **both**: the + match-specification clear for each named `{module, function, arity}`, after + the module pattern, exactly as ADR 0030's sentence describes; and the + process flag for the caller, which is what reaches the callees a match + specification cannot name. + + **The adapter supplies its own MFAs, and that is what keeps the dependency + direction intact.** Core never names an adapter function — it takes a list + from the caller and installs it — so nothing in `loopex` knows that + `Loopex.LLM.ReqLLM.ProviderBridge` exists. The inventory of key-bearing + functions belongs to the component that has them, which is this adapter, and + it is listed below. + + It returns `:ok` once the caller is excluded from **every** live trace session and recorded as excluded for every future one. Only then does the sender route the token, receive the credential and write the frame. Nothing the sender does after that point can appear in a trace, whatever modules or functions a host names — including `:gen_tcp`, including modules nobody has thought of. - **The mechanism, probed at both toolchain pairs before it was written + **The process half, probed at both toolchain pairs before it was written down.** A process flagged by inheritance (`:set_on_spawn` from a traced parent) calls `:trace.process(session, self(), false, [:all])`; the call returns `1`, the flags are gone, and its subsequent `:gen_tcp.send/2` with the canary produces **no trace message at all**, while a non-excluded - control process's identical call produces one. That is pre-delivery in the - strictest sense: there is no message for a sink to redact, and ADR 0030's - rule is satisfied by a stronger mechanism than the one its prose names. + control process's identical call produces one. There is no message for a + sink to redact — which is the property ADR 0030 asks for, reached for the + callees as well as for the named calls. **The VM does not make it sticky, and neither the tracer nor a pid in options can hold it.** The same probe shows a later @@ -375,7 +385,7 @@ boundary, not an absolute: excludes the tracer and the dispatcher by role (`trace.ex:411`), and a tracer that has just restarted asks Control rather than starting empty. - **It fails closed.** `exclude_self/1` returns only once the exclusion is + **It fails closed.** `exclude_self/2` returns only once both exclusions are installed, and it carries an **explicit** bound rather than inheriting a `GenServer.call` default — a hidden five seconds here would be a silent deadline inside the invocation's, exactly the fault the registry and custody @@ -396,29 +406,30 @@ boundary, not an absolute: unreachable, and the two are distinguished at composition rather than at the call. - **Core change 3 is both mechanisms, not one instead of the other.** ADR 0030 - says the key-bearing call "is excluded by match specification" - (`0030-…-technical.md:27`), and an earlier revision of this pair replaced - that with process flags while claiming ADR 0030 was honoured — which is not - a thing a plan gets to do to an accepted decision. So: - - - **A match-specification exclusion for the direct key-bearing calls**, the - functions that receive the resolved bytes themselves — - `receive_custody_reply/2` and `write_credential_frame/2` — installed as - ADR 0030's own sentence describes, by clearing those `{module, function, - arity}` identities after the module pattern. This is the mechanism ADR - 0030 names, implemented rather than reinterpreted. - - **And the process exclusion**, for everything those functions *call*: - `ProviderCodec.send/3`, `encode/2` and its private path, `:gen_tcp.send/2` - and whatever a future codec calls beneath them. This is the protection ADR - 0030 did not foresee, because a match specification names functions and - the leak is through callees. - - Neither is sufficient alone: the match specification cannot reach a callee, - and an earlier revision's claim that process exclusion alone "satisfies" ADR - 0030 was substituting a different mechanism for a named one. The - module-wide exclusion of `ProviderCodec` is dropped, since the process - exclusion covers its calls without costing every other frame's tracing. + **The MFAs this adapter supplies, exactly three.** They are the functions + that hold the resolved bytes or the token, and the list is passed to + `exclude_self/2` by the adapter itself: + + | MFA | What it holds | + | --- | --- | + | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | The registry handle and the token | + | `Loopex.LLM.ReqLLM.ProviderBridge.receive_custody_reply/2` | The resolved credential | + | `Loopex.LLM.ReqLLM.ProviderBridge.write_credential_frame/2` | The resolved credential | + + Three, not two: `route_credential/2` carries the token, which the closed + reason set treats as credential-adjacent and which this pair refuses to put + in a trace entry either. The same three are named wherever this set counts + them. + + **What each half buys, so neither is mistaken for the other.** The match + specification stops those three producing a raw message at all, which is + what ADR 0030 asks for by name. The process flag stops everything they call + — `ProviderCodec.send/3`, `encode/2` and its private path, `:gen_tcp.send/2`, + and whatever a future codec calls beneath them — which a match specification + cannot reach, because it names functions and the leak is through callees. + Neither is sufficient alone, and the module-wide exclusion of + `ProviderCodec` an earlier revision proposed is dropped: the process flag + covers its calls without costing every other frame's tracing. **What is kept as defence in depth**, explicitly labelled so nobody mistakes it for the mechanism: the **keyed shape**. The three bridge functions carry @@ -445,7 +456,7 @@ boundary, not an absolute: through `:application.get_key(application, :modules)` and `Loopex.LLM.ReqLLM.ProviderBridge` lives in `loopex_llm_reqllm`. - The third is the ordering: `exclude_self/1` is asserted to return **before** + The third is the ordering: `exclude_self/2` is asserted to return **before** the token is routed, and a session started concurrently with it is asserted to produce no message from the sender either way round. @@ -456,7 +467,7 @@ boundary, not an absolute: pid in options would fail. **The set returns to baseline**: after a run of invocations, the excluded-pid set `Control` holds is asserted empty again, proving the monitors remove what the senders left. And **it fails closed**: - with the tracer made unavailable at the instant `exclude_self/1` is called, + with the tracer made unavailable at the instant `exclude_self/2` is called, the invocation is asserted to refuse `:unavailable` and **no credential is resolved**, while a composition with no tracing capability at all is asserted to resolve normally. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0e08b4751..1fdcef304 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace.exclude_self/1`, which keeps a credential-bearing process out of every trace session, live and future, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create result's `disposition` and `residency` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create result's `disposition` and `residency` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -147,7 +147,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/1` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -315,7 +315,7 @@ Three of the five were witnessed only downstream — in the daemon's lifetime suite and the adapter's credential suite — and three of their properties cannot be reached from there at all: quiesce's `absent` branch needs a `Control` entry whose coordinator has already died (`control.ex:821-823`), -`exclude_self/1`'s fail-closed path needs the tracer mid-restart, and +`exclude_self/2`'s fail-closed path needs the tracer mid-restart, and `Control` pruning an excluded sender needs that sender's `DOWN`. All three are core-internal states a daemon cannot construct through the socket. @@ -325,7 +325,7 @@ core-internal states a daemon cannot construct through the socket. | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | | **`quiesce/2`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale classifies the session from the journal`; `a fence answering commit_unknown is retried under the same derived tx_id and reported unsettled with fence: :unknown`; `every fence in one drain derives its id from the same drain_id` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | -| **`Loopex.Trace.exclude_self/1` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | +| **`Loopex.Trace.exclude_self/2` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | The paused-transaction case in `runtime_quiesce_test.exs` pauses the transaction through core's own controllable store, not the shipped adapter: @@ -984,8 +984,9 @@ leaked until the daemon restarts: | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | | Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | | Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | -| A **resume** crashing or timing out, so the daemon has no result | **Held, then resolved by observation**: the daemon holds the session ID, so it asks core about that session and converts or releases accordingly | -| A **create** crashing or timing out | **Held, then resolved by replay**: no session ID exists yet, so the daemon replays `session.create` under the same `command_id` — which returns the historical result and starts no coordinator (`control.ex:901-907`) — reads the session ID from it, and then resolves as a resume does. The replay carries the same reservation key, so it charges no second slot | +| A **resume** crashing or timing out | **Held, then resolved by replay**: replayed under its original `command_id`, whose `disposition`/`residency` say whether the original call activated the session. The existence query cannot answer this — it says `present` either way | +| A **create** crashing or timing out | **Held, then resolved by replay**: replayed under the same `command_id`, which returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | +| An **attach** crashing or timing out | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment (`0032-…-technical.md:126-129`), so the daemon closes that connection and its ordinary teardown detaches whatever core attachment it held. Nothing is observed, because nothing needs to be | **That last row is not hypothetical, and the reason is a default nobody chose.** The daemon reaches core through `Loopex.Runtime`, whose @@ -997,19 +998,40 @@ exotic one. Every daemon call that consumes a ceiling therefore carries an explicit timeout rather than inheriting that default, and resolves its reservation by observation when the timeout is what it gets. -A call that gives the daemon no answer may still have started a coordinator, so -releasing the reservation would let the ceiling be exceeded and converting it -would spend a slot that may not exist; asking is the only honest resolution. - -**For a resume the daemon can ask directly; for a create it cannot**, and an -earlier revision of this table missed the difference. A create's reservation -is keyed by the create `command_id`, because no session ID exists when it is -taken, and core's existence query takes a **session ID**. So the create's -resolution is one step longer: replay the create under its original -`command_id`, which returns the historical result without starting a -coordinator (`control.ex:901-907`), take the session ID from it, and then ask -about that ID. The replay is idempotent by construction and carries the same -reservation key, so it charges no second slot. +**A call that gives the daemon no answer may still have started a coordinator +or an attachment**, so releasing the reservation would let the ceiling be +exceeded and converting it would spend a slot that may not exist. What +resolves it differs by call, and an earlier revision used one resolution for +all three — core's existence query — which cannot discriminate for two of +them. + +**Create: replay under the original `command_id`.** No session ID exists when +the reservation is taken, so the existence query cannot even be asked. The +replay returns the historical result without starting a coordinator +(`control.ex:901-907`) and now carries `disposition` and `residency`, which +say directly whether the original call started anything. The replay is +idempotent and carries the same reservation key, so it charges no second slot. + +**Resume: replay under the original `command_id` too — not the existence +query.** The existence query answers `present` for *any* session a resume +could target, whether or not this resume activated it, so it cannot tell the +two apart: the two answers that must differ are identical. The replay can, +because core's resume result carries the same two fields: `:historical` with +`residency: :active` means the original call did activate it, `:historical` +with `residency: :dormant` means it did not, and the daemon converts or +releases on that. + +**Attach: close the connection and release with it.** Core exposes no +attachment count, so there is nothing to observe — and nothing needs to be. +ADR 0032 binds a connection to **at most one attachment at a time** +(`0032-…-technical.md:126-129`), so the attachment reservation is keyed by +the **connection**, not the session. A connection whose `session.attach` never +answered is closed by the daemon, and its teardown detaches whatever core +attachment that connection holds — the same path every connection close +takes, whether it closed because a client went away or because the daemon gave +up on it. The reservation is released with the connection. That is the whole +resolution: one rule already in the design, applied to a case that otherwise +needed an observer core does not have. `loopex attach --take-over` against a dormant session therefore acquires successfully and is refused at attach, holding a lease it no longer wants. @@ -1225,7 +1247,7 @@ exist. The fixed set is this: | --- | --- | --- | --- | | 1 | The credential **routing registry** | The daemon's own, as the host ADR 0034 names | no | | 2 | The credential **custody process** | The daemon's own, as the host ADR 0034 names | no | -| 3 | The **tracing capability** | The daemon's own, as the host ADR 0034 names; it holds the runtime reference and resolves the current tracer for `exclude_self/1` | no | +| 3 | The **tracing capability** | The daemon's own, as the host ADR 0034 names; it holds the runtime reference and resolves the current tracer for `exclude_self/2` | no | | 4 | The Store adapter | `start_edge(Store.Local, …)` | no | | 5 | The artifact transfers owner | `start_edge(Transfers, …)` | **yes** — only when transfers are enabled | | 6 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | @@ -2880,16 +2902,33 @@ next daemon removes before binding. attachments afterwards rather than 513 — the same reserve-before-the-call rule as the activation ceiling, proved where it would otherwise have been assumed. -- **Every branch releases or converts its reservation.** One case per row of - the resolution table: a fresh create, a replayed create against an active - and a dormant session, a fresh resume, a replayed resume, a refusal, and a - call that never answers — the last one twice, once for a resume, resolved by - asking about the session ID the daemon holds, and once for a **create**, - resolved by replaying under the original `command_id`, reading the session - ID from the historical result and asking about that; the create case asserts - the replay started no coordinator and charged no second slot. Each asserts - the daemon's remaining slot count afterwards, so a branch that leaked a reservation shows up as a daemon that - refuses early rather than as a silent drift. +- **Every branch releases or converts its reservation, and the no-answer + cases are written so the two outcomes can differ.** One case per row: a + fresh create, a replayed create against an active and a dormant session, a + fresh resume, a replayed resume, a refusal, and then the three no-answer + rows, each constructed so that a resolution which could not discriminate + would fail: + + *Resume, no answer, two sub-cases.* One where the original resume **did** + activate the session and one where it **did not** — the same session ID, the + same query answer `present` in both. The case asserts the daemon converts in + the first and releases in the second, which it can only do from the replayed + result's `disposition` and `residency`. A resolution by existence query + would give the same answer to both and is thereby excluded. + + *Create, no answer.* The replay is asserted to start no coordinator and + charge no second slot, and the slot count afterwards distinguishes a fresh + original from a replayed one. + + *Attach, no answer.* The daemon is asserted to **close that connection**, + and core is asserted to hold one fewer attachment afterwards — the + connection's teardown having detached it — with the reservation released. + No attachment count is read from core at any point, because none exists to + read. + + Each case asserts the daemon's remaining slot count afterwards, so a branch + that leaked a reservation shows up as a daemon that refuses early rather + than as a silent drift. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting @@ -3018,18 +3057,22 @@ daemon is a host and a host is an application. One daemon owner process, one new the two callers that need the edges assembled, `RuntimeOwner` and the daemon's owner, and which direct code cannot replace because the alternative is a second copy of the whole wiring layer. One socket listener, one narrow -core concurrent-attachment change, **one process-level trace exclusion, -`Loopex.Trace.exclude_self/1`** — which unifies nothing and is not asked for -by this milestone's features at all: it exists because accepted ADR 0030 -already requires that a key-bearing call be excluded before delivery, and the -implementation did not do it. Direct code cannot supply it, because exclusion -has to happen inside the tracer that owns the session. Two smaller forms were -tried and dropped: redaction at the sink is too late, the raw call having -already reached the tracer, and a list of excluded `{module, function, arity}` -identities cannot cover what an excluded function *calls* — a traced -`:gen_tcp.send/2` shows the credential frame however this adapter's own -modules are patterned. One pid excluded from every session, live and future, -is both smaller and total. **Two plain fields on the runtime-side create and resume results** — which unify +core concurrent-attachment change, **one trace-exclusion call, +`Loopex.Trace.exclude_self(capability, functions: [mfa])`** — which unifies +nothing and is not asked for by this milestone's features at all: it exists +because accepted ADR 0030 already requires that a key-bearing call be excluded +before delivery, and the implementation did not do it. Direct code cannot +supply it, because exclusion has to happen inside the tracer that owns the +session. It is **one** core change with two inputs rather than two changes: +the caller passes its own key-bearing identities and core installs both the +match-specification clear ADR 0030 names and the process flag its callees +need. What *was* dropped is **sink-time redaction**, which is too late — the +raw call having already reached the tracer — and the module-wide exclusion of +a codec, which cost every other frame's tracing. The match-specification list +is not dropped; it is half the call, and the process flag is the other half, +because a list of `{module, function, arity}` identities cannot cover what an +excluded function *calls*: a traced `:gen_tcp.send/2` shows the credential +frame however this adapter's own functions are patterned. **Two plain fields on the runtime-side create and resume results** — which unify nothing and add no wire surface: they exist because core computes `fresh?` at `control.ex:895` and then throws it away four lines later, leaving every caller unable to tell a fresh create from a replay. Direct code cannot supply diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 385364edb..742a46ae9 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -40,9 +40,9 @@ v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above the core. Core gains exactly five narrow things: support for several independent attachments to one session; one read-only query that answers whether a session -ID exists durably in the root; `Loopex.Trace.exclude_self/1`, which keeps a -credential-bearing process out of every trace session, live and future, before -any message is delivered, and which accepted ADR 0030 already requires; `quiesce/2`, the bounded settle an orderly stop +ID exists durably in the root; `Loopex.Trace.exclude_self/2`, which installs +both the match-specification exclusion accepted ADR 0030 names and the +process-level exclusion its callees need, before any message is delivered; `quiesce/2`, the bounded settle an orderly stop drains through; and two plain fields on the **runtime-side** create and resume results, telling a host whether the create it just made was fresh or a replay and whether the session is active or dormant — the public protocol result is @@ -739,8 +739,8 @@ lease — and the companion's rejoin order says where each part goes. 1. **Core's five changes, and the residency above them.** The narrow core change that lets distinct attachments to one session coexist without implicit replacement; the read-only session-existence query the daemon's - acquire and activation paths need; `Loopex.Trace.exclude_self/1`, the - process-level trace exclusion that accepted ADR 0030 already requires, + acquire and activation paths need; `Loopex.Trace.exclude_self/2`, the + two-part trace exclusion that accepted ADR 0030 already requires, which lands with workstream 5's credential work because that is what it protects; and the bounded `quiesce/2` the orderly stop drains through, which lands before workstream @@ -970,17 +970,20 @@ host that named the adapter would create one more message holding the credential. M5 therefore **implements what the accepted ADR already requires**, as core's -third change in this milestone — and implements it **as both mechanisms**, -because neither alone is enough. The match specification ADR 0030 names -excludes the key-bearing bridge calls themselves. It cannot reach what they -*call*: an excluded function calls functions it does not own, and a trace -session naming `:gen_tcp` sees the credential frame `ProviderCodec.send/3` -hands it, whatever this adapter's own modules are patterned. So `Loopex.Trace` -also gains `exclude_self/1` and an excluded-pid set held in `Control` and -reached through a capability the host composes, since the tracer is the -runtime's last child and is resolved dynamically: the credential-bearing -process excludes itself before it resolves anything, from every live session -and every future one, and no trace configuration can name it back in. Both the +third change in this milestone — and implements it as **one call installing +both mechanisms**, because neither alone is enough. The match specification +ADR 0030 names excludes the key-bearing bridge calls themselves; it cannot +reach what they *call*, and a trace session naming `:gen_tcp` sees the +credential frame `ProviderCodec.send/3` hands it whatever this adapter's own +functions are patterned. So `Loopex.Trace` gains +`exclude_self(capability, functions: [mfa])`: the **caller supplies its own** +key-bearing identities — core never names an adapter function, which is what +keeps the dependency direction intact — and core installs the +match-specification clear for them and the process flag for the caller, in +that one call. The excluded-pid set is held in `Control` and reached through a +capability the host composes, since the tracer is the runtime's last child and +is resolved dynamically. The credential-bearing process excludes itself before +it resolves anything, and no trace *configuration* can name it back in. Both the leak and the mechanism were reproduced by probe at both toolchain pairs before this was written down. ADR 0030 is **not** edited — an accepted ADR changes through its own amendment path — and its prose is honoured once this change lands. This is a From 050538c4c7d6c96550c2979b9ab2ac2035eaaa29 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:50:46 -0700 Subject: [PATCH 109/585] plan(M5): close the P1 and P2 findings from the fresh review P1-7 daemon `test_helper.exs` excludes all four tags this application carries, shown as code, on both existing helpers' precedent. P1-8 `listener_lost` leaves the vector list with its reason: the listener is what would have written it. P1-9 the three witnesses that read daemon counters are restated as in-VM cases, saying explicitly that no wire method reports them and no DTO field is added. P1-10 eight/seven becomes nine/eight. P1-12 and P1-18 the ticket set cites 0033-technical:188-191 and says `session.release_control` is lease-authorized but unticketed because it starts no core call. P1-11 every 512 citation re-derived against the file rather than trusted: attachments per daemon 0032-technical:854 with its limit key at :263; 512 MiB at :154 and :850; the lease-owner cap at :333-335 with its refusal at :247. The reviewer's line numbers were stale, as mine had been. P1-13 the writer_epoch exception is stated for readers of the DTO tables, not for the digest: `schema_digest/0` hashes generation, method names, record-family names, error-code names and limits (session.ex:192-199, :53-61) and no request field, so the digest would not have caught it -- the old justification was false in the direction that matters. P1-14 `control.ex:901-907` has two direct `{:ok, session_id}` branches (:903-904, :906-907); the third starts an owner at :909-918 and replies `{:noreply, next}`, the ok arriving via `owner_ready_reply/4` at :532. The resume citations are corrected to `completed_resume_reply/2` at :526-527. P1-15 the daemon installs on `SIGTERM` only, with the reasoning: a service is not run at a prompt, a daemon dying on `SIGHUP` when its terminal closes is a defect, and taking `SIGQUIT` would remove the operator's one stop-and-dump signal. The witness list says there is no case for a signal nobody handles. P1-16 ADR 0032's Concept says five core changes. P2-24 citation slips: `local.ex:167` for the marker release (three sites), `store.ex:169-179`, and the malformed `state/local/state.ex` path expanded. --- ...-daemon-attachment-residency-and-replay.md | 6 +- docs/plans/M5-technical.md | 158 +++++++++++------- 2 files changed, 105 insertions(+), 59 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 6991bcadc..e0d38ff84 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -57,8 +57,10 @@ connection closes whatever happened, so a client may learn of a shutdown only by its socket closing. It adds no durable method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core -has no durable stop command, and M5's core changes are concurrent attachment -and a read-only existence query, neither of which is a durable command. Ending a client's involvement is releasing control and +has no durable stop command, and M5's five core changes — concurrent +attachment, a read-only existence query, the trace exclusion, the bounded +`quiesce/2`, and the create and resume results' two new fields — are none of +them durable commands. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by acquiring control and attaching. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 1fdcef304..0de47117e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -28,7 +28,7 @@ decision named only in prose declares nothing. | Decision | Acceptance point | What its acceptance settles | | --- | --- | --- | | [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | -| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or either core change lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | +| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or any of those core changes lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | | [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as an opaque token bound at composition beside the registry handle and **resolved per invocation**, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; custody and registry ownership, rotation, the guardian-enforced deadline, `:unavailable` on lost custody or registry with no reconstruction, and every failure outcome; no credential environment read anywhere in the adapter's library tree, with `provider_bridge` reading none at all and the launcher's ADR 0019 scrubbing enumeration kept exactly where it is, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component of the fixed set (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`, `listener_lost`), plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -203,12 +203,20 @@ script runs, on the Linux lane only, for `loopex_daemon`: Two cases carry that tag and both must execute: a connection from a foreign uid refused before initialize, and one from the daemon's own uid accepted. -They are excluded from an ordinary run at the source, on the app-server's -precedent: `apps/loopex_daemon/test/test_helper.exs` ends -`ExUnit.start(exclude: [:cross_uid])`, exactly as -`apps/loopex_app_server/test/test_helper.exs` excludes `:node_client` and -`:real_provider` so an ordinary `mix test` needs neither Node nor a -credential. The fast check therefore never runs these two, and they run only +They are excluded from an ordinary run at the source, on the precedent both +existing helpers set: `apps/loopex_daemon/test/test_helper.exs` ends + +```elixir +ExUnit.start(exclude: [:cross_uid, :real_provider, :node_client, :long_bound]) +``` + +— all four, because this application carries cases of all four kinds: the two +`cross_uid` cases here, the real-provider workflow, the Node client, and the +long-duration bound proofs the fast check excludes. That is the same shape as +`apps/loopex_executor_local/test/test_helper.exs`, which excludes +`:real_provider` and `:long_bound`, and `apps/loopex_app_server/test/test_helper.exs`, +which excludes `:node_client` and `:real_provider` so an ordinary `mix test` +needs neither Node nor a credential. The fast check therefore never runs these two, and they run only when the release check asks for them by name. **The suite judge's rule is not enough here, so the script asserts the exact @@ -374,9 +382,15 @@ freeze; all surfaces remain experimental. The socket reuses ADR 0023's framing, handshake, limits, and its admission, snapshot, event and progress records unchanged. Its **request** records are reused with one addition, not unchanged: every existing-session mutation in generation 2 carries -`writer_epoch`. Saying "records reused unchanged" without that exception would -be wrong in the one place a reader checks it, at the schema digest, which is -precisely why generation 2 needs its own. Generation 2 is additive +`writer_epoch`. The exception is stated because a **reader of the DTO tables** +would otherwise take "records reused unchanged" literally and build a request +without that field. It is **not** stated because the digest would catch it: +`schema_digest/0` hashes the generation, the ordered method *names*, the +ordered record-family *names*, the ordered error-code *names* and the limits +(`session.ex:192-199`, with the family list at `:53-61`) — no request field +appears in it, so an added field changes no digest. An earlier revision said +the digest was the place a reader checks it, which was false in the one +direction that matters: the digest would have let this through. Generation 2 is additive over generation 1's method set under the exact-generation rule: a generation-1 client sees no daemon method and no lease field, the daemon refuses a generation-1-only initialize, and the foreground server keeps serving @@ -834,16 +848,18 @@ fifth M5 change.** The daemon has two duties that pull against each other: charge a *fresh* create against the activation ceiling, because a fresh create starts a coordinator; and repair a directory entry for a session whose create is *replayed*, without activating anything. Today it cannot do either -reliably, because core answers both the same way. All three branches at -`control.ex:901-907` reply `{:ok, session_id}` — the session is already -active; the command was seen before, so no owner is started; or it is fresh -and an owner starts — and the value carries no trace of which. +reliably, because every path answers the same way. Two branches reply +`{:ok, session_id}` directly — the session is already active (`control.ex:903-904`), +or the command was seen before so no owner is started (`:906-907`). The third +starts one (`:909-918`) and replies **`{:noreply, next}`**, the `{:ok, +session_id}` arriving later through `owner_ready_reply/4` (`:532`). Three +paths, one indistinguishable value. Core already computes what is missing, and uses it: `create_command_absent?/2` -binds `fresh?` at `control.ex:895`, and the `cond` at `:903-907` reads it to -decide whether to `start_owner`. What is discarded is the distinction in the -**reply** — all three branches answer `{:ok, session_id}` — so the fifth change -is to stop discarding it there. **Core's runtime-side create and resume results — the +binds `fresh?` at `control.ex:895`, and the `cond` at `:902-919` reads it to +decide whether to `start_owner`. What is discarded is the distinction in what +the caller finally receives — the same `{:ok, session_id}` however it got +there — so the fifth change is to stop discarding it there. **Core's runtime-side create and resume results — the Elixir function the daemon calls, not the released public protocol result — carries two plain fields beside the session ID:** @@ -860,8 +876,9 @@ answers the same through `start_resume_owner`, and the daemon charges an activation for resume as it does for create — so a client retrying a resume under its original `command_id` would be charged twice. Core already knows the difference and already exposes it in one mode: `completed_resume_reply/2` -answers `{:ok, {:replayed, session_id}}` for the **prepared** mode at -`control.ex:526` and a bare `{:ok, session_id}` for the plain one at `:527`. +answers `{:ok, {:replayed, session_id}}` for the **prepared** mode +(`control.ex:526`) and a bare `{:ok, session_id}` for the plain one (`:527`), +and `owner_ready_reply/4` does the same for a started owner (`:529-532`). Rather than make the daemon use a mode it does not otherwise want, the plain resume result carries the same `disposition` and `residency` the create result does. That is one shape for both, not two. @@ -1280,9 +1297,12 @@ as though it does: nothing else.** ADR 0033 lists them: `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, `session.respond_interaction`, `session.admit_resources` and - `session.activate_skill` — every generation-2 call that carries - `writer_epoch` and is admitted only from the recorded holder - (`0033-…-technical.md:170-178`). **Reads are not ticketed.** An earlier + `session.activate_skill` — the **eight** calls that carry `writer_epoch` and + are admitted only from the recorded holder + (`0033-…-technical.md:188-191`). **`session.release_control` is not among + them**, and the distinction is worth one line: it carries `writer_epoch` and + is lease-authorized, but it starts no core call, so there is nothing for a + ticket to account for. **Reads are not ticketed either.** An earlier revision said "every core call the daemon makes", which would have included `Loopex.Runtime.next_event/1` — an `:infinity` dispatcher call by construction (`runtime.ex:236-244`) — so a quiet observer sitting on a read @@ -1346,7 +1366,7 @@ implementation: | When does one start? | On the **first lease operation for that session after successful existence validation** — an `session.acquire_control`, whether or not the session is active. Not at activation: an earlier revision said activation, which was wrong twice over, since dormant recovery acquires *before* it resumes and `loopex attach --take-over` may acquire and release a session it never activates | | When does one retire? | When the lease is free — released or expired — **and** no acquisition is waiting **and** the relay holds no outstanding ticket for that session. All three, because any one of them alone would retire an owner whose state something still depends on | | When does one stop unconditionally? | At daemon exit, in the stop sequence below | -| How many can exist at once? | One per session under lease or acquisition, capped at **512, the per-daemon attachment ceiling ADR 0032 already fixes** (`0032-…-technical.md:720`), reused rather than invented, with the cap itself stated at `0032-…-technical.md:222`; a lease operation that would exceed it refuses with `control_capacity_reached`. The population is **independent of the activation ceiling**, which counts something else entirely | +| How many can exist at once? | One per session under lease or acquisition, capped at **512, the per-daemon attachment ceiling ADR 0032 already fixes** (`0032-…-technical.md:854`), reused rather than invented, with the cap and its refusal stated at `0032-…-technical.md:333-335` and `:247`; a lease operation that would exceed it refuses with `control_capacity_reached`. The population is **independent of the activation ceiling**, which counts something else entirely | | What does its death mean? | That **session's** collaboration state, not the daemon's — the one exception to fail-stop uniformity, below | **Why not the activation ceiling.** An earlier revision bounded the population @@ -1640,7 +1660,7 @@ that ends "then stop the Store" cannot run when the Store is what died. holds the marker.** The socket path is not the daemon's by possession; it is the daemon's *because it holds the writer marker*, which is what ADR 0032 already says. The permission therefore **ends when the marker does**, and the -marker is released by the Store's `terminate/2` (`local.ex:166`) — which can +marker is released by the Store's `terminate/2` (`local.ex:167`) — which can happen without the daemon being asked and without the daemon noticing. An earlier revision tried to keep the unlink by putting a precondition in @@ -1702,9 +1722,24 @@ concern and `SIGTERM` is the escript's**. A daemon started without that launcher has no `SIGINT` behaviour to specify, and the plan says so rather than implying one. -For `SIGTERM`, `SIGHUP` and `SIGQUIT` the daemon does what the CLI already +**The daemon installs on `SIGTERM` and on nothing else**, which is smaller +than the CLI's set and deliberately so. `LoopexCli.Interrupt` installs on +`SIGTERM`, `SIGHUP` and `SIGQUIT` because it owns a terminal session: a +closing terminal sends `SIGHUP` to its foreground group and `SIGQUIT` is the +other keyboard interrupt, and a command run at a prompt should end on both. A +daemon is not run at a prompt. It is started by a service manager or a +launcher, both of which stop a service with `SIGTERM`, and a daemon that also +died on `SIGHUP` would exit when the terminal that happened to start it +closed — which for a background service is a defect rather than a courtesy. +`SIGQUIT`'s default is a core dump, and taking it over to do a graceful stop +would take away the one signal an operator has for "stop and leave me a dump". +So the daemon handles `SIGTERM`, leaves `SIGHUP` and `SIGQUIT` at their +defaults, and the witnesses cover `SIGTERM` and the launcher's forwarded +`SIGINT` only. + +For `SIGTERM` the daemon does what the CLI already does, and reuses the same mechanism rather than inventing one: -`:os.set_signal(signal, :handle)` (`interrupt.ex:782`), a `:gen_event` handler +`:os.set_signal(:sigterm, :handle)` (the call `interrupt.ex:782` makes per signal), a `:gen_event` handler added to `:erl_signal_server` (`interrupt.ex:806` and `:818`), and the **default handler removed** (`interrupt.ex:870-873`) because the runtime's default stops the emulator immediately, which would end the process before any @@ -1961,7 +1996,7 @@ the owner fixes. | The workspace lease | What remains of `teardown_ms` | Nothing: it has no `terminate/2` and holds no file — the lease *is* the live process, so stopping it revokes it | | The transfers owner | What remains of `teardown_ms` | Closing the open transfer descriptors its `terminate/2` holds (`transfers.ex:146-149`) | | The tracing capability, then custody, then the registry | What remains of `teardown_ms` | Nothing durable | - | **The Store** | A **fixed 30 s**, its own phase | Its `terminate/2`, which releases the writer marker (`local.ex:166`) | + | **The Store** | A **fixed 30 s**, its own phase | Its `terminate/2`, which releases the writer marker (`local.ex:167`) | **"What remains" is one deadline, not one budget each.** The owner computes an absolute instant once — `System.monotonic_time(:millisecond) + @@ -2193,9 +2228,9 @@ exceed what the caller has left. So quiesce installs a fence the **Store** enforces, using machinery that already exists. After terminating an unsettled coordinator it commits an - **`advance_owner` transaction** for that session (`store.ex:168-178`, + **`advance_owner` transaction** for that session (`store.ex:169-179`, built by `Store.advance_owner/6` at `store.ex:820-827`, linearized at - `state/local/state.ex:241-254`). Once it commits, the session's + `apps/loopex_store_local/lib/loopex/store/local/state.ex:241-254`). Once it commits, the session's `owner_epoch` has moved, and any older `session_commit` the Store linearizes afterwards is refused **`:stale_owner_epoch`** by the rule that already governs every commit (`state.ex:548-551`). @@ -2722,8 +2757,8 @@ next daemon removes before binding. that component's class, to send that component's `fatal:` on the wire where a socket still exists, and — for the classes where the Store is still alive — **to leave no stale marker**, proved by the next daemon - opening that root with nothing to recover; eight of them in a daemon with - transfers enabled and seven without — `runtime_lost`, `transfers_lost`, + opening that root with nothing to recover; nine of them in a daemon with + transfers enabled and eight without — `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`, `listener_lost`, beside the two store classes. The set is closed for the @@ -2757,7 +2792,10 @@ next daemon removes before binding. which process it signals. A third asserts the install order: a `SIGTERM` delivered before startup completes ends a daemon that holds no marker and has bound no socket, proved by a following daemon starting with nothing to - recover. + recover. There is **no `SIGHUP` or `SIGQUIT` case**, because the daemon + installs on neither: the case list matches the handler set, and a case for a + signal nobody handles would be a case for the default behaviour of the + emulator. - **`owner_lost`, by the monitor and not by a later signal.** The owner is killed while the daemon is otherwise healthy and **nothing else happens**: no signal is sent. The case asserts the process halts non-zero with @@ -2817,20 +2855,25 @@ next daemon removes before binding. call was never made, and that a replacement grant waits on it rather than proceeding into a gap. - **Owners exist for dormant sessions, and the population is not the - activation count.** A dormant session is acquired for recovery without being - resumed: the case asserts an owner exists for it, that the **activation - count is unchanged**, and that after `session.release_control` — with no - acquisition waiting and no ticket outstanding — the owner **retires**, - proved by the daemon reporting one fewer live owner while the session stays - reachable. A second case runs `loopex attach --take-over` against a dormant - session, which acquires, is refused at attach, releases and exits, and - asserts the owner that existed for the acquisition is gone afterwards and no - activation was spent. -- **The concurrent-owner cap is the attachment ceiling, not a new number.** A - daemon driven to 512 concurrent lease owners refuses the next lease - operation with `control_capacity_reached`, and the case asserts no - five-hundred-and-thirteenth owner was started and that releasing one lease - lets the next acquisition through. + activation count.** These are **in-VM cases**, not socket cases, and the + plan says so rather than implying a surface: the daemon's live-owner + population and its activation count are internal, no wire method reports + either, and **no DTO field is added to make them observable**. The cases run + against the daemon's own processes in the same VM. A dormant session is + acquired for recovery without being resumed: the case asserts an owner + process exists for it, that the activation count the daemon holds is + unchanged, and that after `session.release_control` — with no acquisition + waiting and no ticket outstanding — the owner process **is gone**. A second + case runs the `--take-over` sequence against a dormant session, which + acquires, is refused at attach, releases and exits, and asserts the owner + process is gone afterwards and no activation was spent. +- **The concurrent-owner cap is the attachment ceiling, not a new number** — + again in-VM for the count, and on the wire for the refusal. A daemon driven + to 512 concurrent lease owners refuses the next lease operation with + `control_capacity_reached`, which **is** a wire code; the case asserts that + refusal on the socket, and asserts in-VM that no five-hundred-and-thirteenth + owner process was started and that releasing one lease lets the next + acquisition through. - **The credential processes are fatal like every other component.** The registry, the custody process and the tracing capability are each killed in their own case; the daemon exits `registry_lost`, `custody_lost` and @@ -2926,9 +2969,10 @@ next daemon removes before binding. No attachment count is read from core at any point, because none exists to read. - Each case asserts the daemon's remaining slot count afterwards, so a branch - that leaked a reservation shows up as a daemon that refuses early rather - than as a silent drift. + Each case asserts the daemon's remaining slot count **in-VM**, reading the + reservation state directly rather than through any wire method — no DTO + field exposes it, and none is added — so a branch that leaked a reservation + shows up as a daemon that refuses early rather than as a silent drift. - **Reverse cleanup.** A startup made to fail after the marker is acquired — at the socket permission check and at the index bound, separately — leaves no marker held and no socket file behind, proved by a second daemon starting @@ -3011,7 +3055,7 @@ survive arrives as `runtime_lost`. | Boundary | Owner | What fails | Who observes it, and how | What the client sees | Durable / not durable | | --- | --- | --- | --- | --- | --- | -| **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the **daemon owner process** holds the Store's link and pid | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:166`). The owner's `{:EXIT, store_pid, reason}` clause receives it **with the store's real reason**, which is what distinguishes `store_capacity_exceeded` from `store_lost` | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | +| **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the **daemon owner process** holds the Store's link and pid | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:167`). The owner's `{:EXIT, store_pid, reason}` clause receives it **with the store's real reason**, which is what distinguishes `store_capacity_exceeded` from `store_lost` | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | | **Store ↔ daemon (startup)** | The adapter | Marker held, unverifiable, log too large | `WriterLock.acquire` refuses with `store_writer_active` / `store_writer_unverifiable`; `Log.open` refuses `store_log_too_large` (`log.ex:80-84`) | Nothing — no socket exists yet | **Not durable:** nothing was written. Reverse cleanup leaves no marker | | **Core ↔ daemon: existence query** | `loopex` answers; the daemon asks | Root unreadable, malformed ID, unrecognised answer | The query's own closed result set — `present`, `absent`, `invalid_id`, `store_unavailable`, `unexpected` (this plan's new core operation) | The matching refusal, four of them distinct; nothing created, nothing attached, no lease | **Not durable:** the query writes nothing, proved by a byte-identical root | | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | @@ -3130,12 +3174,12 @@ line; M5 introduces none of its own. | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | | Attachments per session | 64 | ADR 0032 | -| Attachments per daemon | 512 | ADR 0032, `:720` | +| Attachments per daemon | 512 | ADR 0032, `:854`, with the limit key at `:263` | | Core event-count queue per attachment | 1,024 events | ADR 0032 | | Daemon socket output buffer per connection | 4 MiB encoded | ADR 0032 | | Resident window per session | 4,096 events and 16 MiB encoded | ADR 0032 | -| Aggregate retained encoded events per daemon | 512 MiB | ADR 0032, `:147` and `:716` | -| Concurrent lease owners | 512, the attachment number reused rather than a second limit | ADR 0032, `:222` | +| Aggregate retained encoded events per daemon | 512 MiB | ADR 0032, `:154` and `:850` | +| Concurrent lease owners | 512, the attachment number reused rather than a second limit | ADR 0032, `:333-335`, with its refusal at `:247` | | Idle time before an attachment is evicted and its window and buffer released | 10 minutes; it never stops a coordinator | ADR 0032 | | Sessions activated per daemon lifetime | 64; the 65th activation refused, the remedy being to restart the daemon. It is per lifetime rather than concurrent because nothing deactivates a coordinator, which is recorded as a limitation | ADR 0032 | | Recorded session index entries per root | 4,096; a root whose directory holds more refused at daemon start. The ceiling is on recorded entries and never on reachability: a session reached by ID beyond it is activated and not recorded, and the listing carries `index_full` | ADR 0032 | @@ -3157,9 +3201,9 @@ line; M5 introduces none of its own. **Three rows say 512 and they are three different bounds**, which is worth one sentence because "one number, one ADR" would otherwise read as one limit: 512 -*attachments* per daemon (ADR 0032 `:720`), 512 *MiB* of retained encoded +*attachments* per daemon (ADR 0032 `:854`), 512 *MiB* of retained encoded events across every buffer and window (`:147`, `:716`), and at most 512 -concurrent *lease owners* (`:222`), the last deliberately reusing the +concurrent *lease owners* (`:333-335`), the last deliberately reusing the attachment number rather than introducing a third limit that could drift from it. From 6e611ed42c69722a966814ec14bd97ed6add8ea5 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:52:54 -0700 Subject: [PATCH 110/585] plan(M5): qualify the exclusion claim, rename core's residency field P1-19. `Control` is a `:permanent` child under `:rest_for_one` (runtime/supervisor.ex:69-72, :92), so its restart clears the excluded-pid set -- and restarts the tracer with it, ending every live session. The claim is now qualified rather than repeated: flags already installed on live sessions persist, being VM state rather than Control's; only sessions started after the restart consult the set, and they find it empty; and a sender whose `exclude_self/2` finds Control unavailable fails closed. The absolute form is kept for what it is about -- trace *configuration* -- and not extended to a supervision event. P2-25. Core's result field is `control_entry: :active | :dormant`, not `residency`, and the rename is explained where the field is introduced: `residency` is a daemon fact on the wire about this daemon's lifetime, while this field says what `Control` holds at the instant of the call, and the two diverge exactly in the `absent` case. Every use follows. P2-21. Ten of the twelve heavy provider modules reference the credential variable -- verified by grep, 12 `async: false` and 10 referencing -- and all twelve are serial; three sites say so. P2-22. ADR README: 0034 fixes one token per composed model configuration, bound at composition and resolved per call. P2-23. The release script re-derives the executed count on the shape that lane's toolchain prints, since the summary format is the current pair's and the release check runs the older pair too -- a parser fixed to one shape would read zero on the other, which is the false negative the assertion exists to prevent. --- ...andoff-over-bootstrap-channel-technical.md | 17 ++++++++ docs/adr/README.md | 3 +- docs/plans/M5-technical.md | 41 +++++++++++++------ docs/plans/M5.md | 15 ++++--- 4 files changed, 57 insertions(+), 19 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index b0a667d3b..4a06e582b 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -384,6 +384,23 @@ boundary, not an absolute: it skips every pid Control holds, the same place `excluded?/3` already excludes the tracer and the dispatcher by role (`trace.ex:411`), and a tracer that has just restarted asks Control rather than starting empty. + - **A `Control` restart is the one gap, and the claim is qualified rather + than repeated.** `Control` is a `:permanent` child under `:rest_for_one` + (`runtime/supervisor.ex:69-72`, `:92`), so its restart clears the set — + and also restarts every child after it, the tracer included, which ends + every live session. What that means precisely: the **process flags already + installed on live sessions persist**, being state in the VM's trace + sessions rather than in `Control`; only sessions started **after** the + restart consult the set, and those find it empty. A sender that resolved + before the restart is therefore still excluded for the session it was + excluded from, and a sender that starts after it excludes itself again, as + every sender does. The remaining case is a sender whose `exclude_self/2` + call **finds `Control` unavailable** — mid-restart — and that one fails + closed like any other unconfirmed exclusion: it refuses the invocation + rather than resolving. So the absolute form — "no trace configuration can + name it back in" — holds for configuration, which is what it is about, and + the plan does not extend it to a supervision event that ends the sessions + anyway. **It fails closed.** `exclude_self/2` returns only once both exclusions are installed, and it carries an **explicit** bound rather than inheriting a diff --git a/docs/adr/README.md b/docs/adr/README.md index 356262568..6255f5deb 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -182,5 +182,6 @@ decides that a typed decision model — one that returns probabilities and confidences rather than text — may be an input to a host's policy decision and a journaled plain-data fact, and may never be the decision. It depends on 0034 and on a prerequisite amendment to it, because a second provider needs one -credential token per provider where 0034 fixes one per call. No part of it +credential token per provider where 0034 fixes one per **composed model +configuration** — bound at composition, resolved per call. No part of it runs inside M5. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0de47117e..0402c17e7 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create result's `disposition` and `residency` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create and resume results' `disposition` and `control_entry` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -235,7 +235,12 @@ appears only in its opening banner — and it pipes each lane's suite summary to M5 changes the script in two ways: - it reads `scripts/suite-summary.sh`'s result line instead of discarding it, - which is what lets any lane assert a count at all; and + which is what lets any lane assert a count at all — and it **re-derives the + count on the shape that lane's toolchain prints**, because the summary + line's format is the current pair's, and the release check runs the older + pair too; a script that parsed one shape would silently read zero on the + other, which is exactly the false negative an executed-count assertion + exists to prevent; and - it branches on platform for this one lane. On Linux it runs `mix test --only cross_uid` and asserts **exactly two** executed. On any other platform it runs nothing for that lane, prints @@ -866,7 +871,17 @@ carries two plain fields beside the session ID:** | Field | Values | What the daemon does with it | | --- | --- | --- | | `disposition` | `:fresh` \| `:historical` | Charge an activation for `:fresh`; charge nothing for `:historical` | -| `residency` | `:active` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | +| `control_entry` | `:active` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | + +**It is `control_entry`, not `residency`, and the rename is the point.** +`residency` is a **daemon** fact on the wire — what `session.list` reports +about a session in *this daemon's* lifetime — while this field says what +`Loopex.Runtime.Control` holds for that session at the instant of the call. +The two coincide today and would not always: a session `Control` still lists +as active may have no live coordinator, which is precisely the `absent` case +`quiesce/2` reports. Giving both the same name would have invited a daemon to +forward one as the other. `residency` stays daemon-only; `control_entry` is +core's. **The same two fields belong on the runtime-side `resume` result**, which my own pass over this section found and the finding did not name. `resume` has @@ -880,7 +895,7 @@ answers `{:ok, {:replayed, session_id}}` for the **prepared** mode (`control.ex:526`) and a bare `{:ok, session_id}` for the plain one (`:527`), and `owner_ready_reply/4` does the same for a started owner (`:529-532`). Rather than make the daemon use a mode it does not otherwise want, the plain -resume result carries the same `disposition` and `residency` the create result +resume result carries the same `disposition` and `control_entry` the create result does. That is one shape for both, not two. **The public protocol result is unchanged.** Generation 1 and generation 2 @@ -995,13 +1010,13 @@ leaked until the daemon restarts: | Result of the call | Slot | | --- | --- | | Create, `disposition: :fresh` | **Converted** — a coordinator started | -| Create, `:historical` with `residency: :active` | Released — that session was counted when it was activated | -| Create, `:historical` with `residency: :dormant` | Released — a replay starts nothing | +| Create, `:historical` with `control_entry: :active` | Released — that session was counted when it was activated | +| Create, `:historical` with `control_entry: :dormant` | Released — a replay starts nothing | | Resume, `disposition: :fresh` | **Converted** — a coordinator started | | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | | Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | | Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | -| A **resume** crashing or timing out | **Held, then resolved by replay**: replayed under its original `command_id`, whose `disposition`/`residency` say whether the original call activated the session. The existence query cannot answer this — it says `present` either way | +| A **resume** crashing or timing out | **Held, then resolved by replay**: replayed under its original `command_id`, whose `disposition`/`control_entry` say whether the original call activated the session. The existence query cannot answer this — it says `present` either way | | A **create** crashing or timing out | **Held, then resolved by replay**: replayed under the same `command_id`, which returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | | An **attach** crashing or timing out | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment (`0032-…-technical.md:126-129`), so the daemon closes that connection and its ordinary teardown detaches whatever core attachment it held. Nothing is observed, because nothing needs to be | @@ -1025,7 +1040,7 @@ them. **Create: replay under the original `command_id`.** No session ID exists when the reservation is taken, so the existence query cannot even be asked. The replay returns the historical result without starting a coordinator -(`control.ex:901-907`) and now carries `disposition` and `residency`, which +(`control.ex:901-907`) and now carries `disposition` and `control_entry`, which say directly whether the original call started anything. The replay is idempotent and carries the same reservation key, so it charges no second slot. @@ -1034,8 +1049,8 @@ query.** The existence query answers `present` for *any* session a resume could target, whether or not this resume activated it, so it cannot tell the two apart: the two answers that must differ are identical. The replay can, because core's resume result carries the same two fields: `:historical` with -`residency: :active` means the original call did activate it, `:historical` -with `residency: :dormant` means it did not, and the daemon converts or +`control_entry: :active` means the original call did activate it, `:historical` +with `control_entry: :dormant` means it did not, and the daemon converts or releases on that. **Attach: close the connection and release with it.** Core exposes no @@ -2916,12 +2931,12 @@ next daemon removes before binding. create disposition. A session whose directory entry was never written is recovered by replaying `session.create` with the original `command_id`: the case asserts core answers `disposition: :historical` with - `residency: :dormant`, that **no activation is charged**, that no + `control_entry: :dormant`, that **no activation is charged**, that no coordinator starts, and that the daemon repairs the directory entry and index row from that answer alone. A genuinely fresh create asserts `disposition: :fresh`, one activation charged, and a live coordinator. A third asserts the pair for a session that is already active — - `:historical` with `residency: :active` — and that the daemon repairs + `:historical` with `control_entry: :active` — and that the daemon repairs nothing, because an activated session already recorded both. - **At the ceiling, every create is refused.** A daemon at its 64th activation refuses `session.create` with `activation_ceiling_reached` **whether the @@ -2956,7 +2971,7 @@ next daemon removes before binding. activate the session and one where it **did not** — the same session ID, the same query answer `present` in both. The case asserts the daemon converts in the first and releases in the second, which it can only do from the replayed - result's `disposition` and `residency`. A resolution by existence query + result's `disposition` and `control_entry`. A resolution by existence query would give the same answer to both and is thereby excluded. *Create, no answer.* The replay is asserted to start no coordinator and diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 742a46ae9..5d7833911 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -31,8 +31,10 @@ closure authorizes. M5 also settles one debt M4's verification work left explicitly open. The provider adapter resolves its credential by reading a process-wide environment variable inside each call, which is both a weaker property than the rest of -its credential plane and the reason twelve heavy provider test modules cannot -run concurrently. M5 moves that handoff onto the private per-invocation +its credential plane and the reason the twelve heavy provider test modules +declare `async: false` — **ten of the twelve** reference the credential +variable directly, and the other two are serial beside them for their own +reasons. M5 moves that handoff onto the private per-invocation channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's @@ -283,7 +285,7 @@ behaves, what bounds it, and what every failure does. The maintainer set this as reasons. A credential that must sit in the parent VM's environment for the duration of every call is a weaker property than one that exists only on a private channel to the child that needs it; and that shared slot is what makes -the twelve heavy provider test modules serial, which leaves the provider suite +ten of the twelve heavy provider test modules serial, which leaves the provider suite as the fast check's critical path. The change stays inside the credential plane: what a child may receive, from whom and when does not widen, and every negative proof M0 to M2 established is carried to the new mechanism rather @@ -859,7 +861,7 @@ that adds the tests it names. | 3 | Open | No controller lease, writer epoch or takeover exists above core | | 4 | Open | Core replaces an existing same-session attachment today; no independent concurrent attachments, resident window, socket output buffer or eviction exists | | 5 | Open | No two-process workflow, daemon operator guide or `0.2.0` source archive exists | -| 6 | Open | The adapter resolves the credential from the parent VM's environment inside each call, and the twelve heavy provider modules declare `async: false` for that reason | +| 6 | Open | The adapter resolves the credential from the parent VM's environment inside each call; ten of the twelve heavy provider modules reference that variable and all twelve declare `async: false` | **Revision of 2026-09-14 (first).** On the independent review of `dc81212360327caa7e8b0ed371cb5ed531b960d9`, the maintainer narrowed this plan @@ -983,7 +985,10 @@ match-specification clear for them and the process flag for the caller, in that one call. The excluded-pid set is held in `Control` and reached through a capability the host composes, since the tracer is the runtime's last child and is resolved dynamically. The credential-bearing process excludes itself before -it resolves anything, and no trace *configuration* can name it back in. Both the +it resolves anything, and no trace *configuration* can name it back in — a +`Control` restart is the one event that clears the set, and it restarts the +tracer with it, so what it clears is a set no live session is still consulting; +a sender that meets `Control` mid-restart fails closed rather than resolving. Both the leak and the mechanism were reproduced by probe at both toolchain pairs before this was written down. ADR 0030 is **not** edited — an accepted ADR changes through its own amendment path — and its prose is honoured once this change lands. This is a From e094f491d6c3952fe47163dea500a1bd7ce22e53 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 11:54:36 -0700 Subject: [PATCH 111/585] plan(M5): apply class 25, unobservable resolution, to my own claims The new pass class caught three of this round's own sentences. The attachment-ceiling witness asserted "core holds 512 attachments afterwards" -- a count core does not expose, which is the same defect P0-5 removed from the attach resolution. It now separates the two surfaces: the wire assertion is one result and one refusal, and the count is read in-VM from core's attachment registry, said out loud. The quiesce witness's "its coordinator is gone, proved by the pid being dead" and the create replay's "started no coordinator" are labelled in-VM with what is actually read -- a pid the case holds, a supervisor's children -- rather than implying a field. The attach no-answer case now names two surfaces that differ in the two cases: the client's connection closed versus open on the wire, and core's attachment registry one lower in-VM. ADR 0034's three capability witnesses each name their surface and both answers: the tracer's message stream with a non-excluded control process so the case cannot pass by tracing nothing; Control's set asserted non-empty while a sender lives and empty after it exits, which separates working monitors from a set never populated; and the fail-closed case asserting the child received no credential frame where the absent-capability case asserts it received one. And quiesce's three lists are given a landing place, since a list in a return value is not a surface: the counts go in the stop line on stderr beside `budget_ms` and `drain_id`, and nothing goes on the wire, because clients are told `operator_stop` rather than a census. --- ...andoff-over-bootstrap-channel-technical.md | 34 ++++++++----- docs/plans/M5-technical.md | 48 ++++++++++++------- 2 files changed, 55 insertions(+), 27 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 4a06e582b..5ab1a9612 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -477,17 +477,29 @@ boundary, not an absolute: the token is routed, and a session started concurrently with it is asserted to produce no message from the sender either way round. - Three more cover what the capability is for. **A tracer restart keeps the - exclusion**: the tracer is killed, the supervisor restarts it, a new session - starts, and a sender that excluded itself before the restart is asserted to - produce no message under the new session — which a design holding a tracer - pid in options would fail. **The set returns to baseline**: after a run of - invocations, the excluded-pid set `Control` holds is asserted empty again, - proving the monitors remove what the senders left. And **it fails closed**: - with the tracer made unavailable at the instant `exclude_self/2` is called, - the invocation is asserted to refuse `:unavailable` and **no credential is - resolved**, while a composition with no tracing capability at all is - asserted to resolve normally. + Three more cover what the capability is for, and each names the surface it + reads and the two answers that must differ on it. + + **A tracer restart keeps the exclusion.** Surface: the tracer's own message + stream. The tracer is killed, the supervisor restarts it, a new session + starts, and a long-lived sender that excluded itself before the restart is + asserted to produce **no** message under the new session while a + non-excluded control process in the same session produces one. A design + holding a tracer pid in options fails the first half; a case without the + control process could pass by tracing nothing. + + **The set returns to baseline.** Surface: `Control`'s excluded-pid set, read + **in-VM** — no wire method reports it and none is added. Asserted non-empty + while a sender is alive and empty after it exits, which is what separates + "the monitors work" from "the set was never populated". + + **It fails closed.** Surface: the invocation's own result, plus the child's + record of what it received. With the tracer made unavailable at the instant + `exclude_self/2` is called, the invocation is asserted to refuse + `:unavailable` and the child is asserted to have received **no** credential + frame; with the capability explicitly absent, the same invocation is + asserted to succeed and the child to receive one. Two configurations, two + different answers on the same two surfaces. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0402c17e7..ee81834c2 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -2317,8 +2317,17 @@ exceed what the caller has left. correct for residency and misleading for a drain. Such a session is **`absent`**: quiesce admits no abort for it, runs no cancellation, and fences it exactly as it fences an unsettled one, because an old transaction - from that dead coordinator is precisely the case the fence exists for. The - daemon reports it as not drained rather than counting it settled. + from that dead coordinator is precisely the case the fence exists for. + + **Where "reports" lands, since a list in a return value is not a surface.** + The daemon has two places to put what quiesce answers, and it uses both: + the counts — settled, unsettled, absent — go in the **stop line on + `stderr`** beside `budget_ms` and `drain_id`, which is what an operator + reading a stopped service's log sees; and nothing goes on the wire, because + by the time quiesce returns the clients have not yet been told anything and + what they are told is `operator_stop`, not a census. A session in `absent` + is therefore distinguishable from one in `settled` exactly where the + difference is actionable, and nowhere it would be noise. **Quiesce is not called through the facade's default timeout.** `control_call/3` and `dispatcher_call/3` both default to `5_000` (`runtime.ex:470`, `:478`), and @@ -2733,8 +2742,9 @@ next daemon removes before binding. *It does not.* A daemon with an effect held past the drain budget and an unresolved mutation receives `SIGTERM`. The case asserts the session is in the `unsettled` list; that its coordinator is **gone before `quiesce/2` - returned**, proved by the pid being dead at the instant the daemon reports - it; and then the negative + returned**, read **in-VM** as that coordinator's pid being dead at the + instant the daemon reports it — `Process.alive?` on a pid the case holds, + not a wire field; and then the negative that matters: **no terminal is claimed for the work that did not settle** — no `cancelled`, no `outcome_unknown` for it. The ambiguous mutation stays `commit_unknown`, each client is sent the stop reason on a transport that @@ -2955,11 +2965,13 @@ next daemon removes before binding. no coordinator and no new journal record — which a post-call count would have failed by starting a sixty-fifth. - **Two concurrent attaches at the attachment ceiling.** A daemon at 511 - attachments receives two `session.attach` calls at once. The case asserts - exactly one succeeds and the other is refused, and that core holds **512** - attachments afterwards rather than 513 — the same reserve-before-the-call - rule as the activation ceiling, proved where it would otherwise have been - assumed. + attachments receives two `session.attach` calls at once. On the wire the + case asserts exactly one result and one refusal — two answers that plainly + differ. The count is **in-VM**: core exposes no attachment count, so the + case reads core's own attachment registry in the same VM and asserts + **512**, not 513. Saying "proved by core holding 512" without saying where + that number is read would have been the same unobservable claim this round + removed elsewhere. - **Every branch releases or converts its reservation, and the no-answer cases are written so the two outcomes can differ.** One case per row: a fresh create, a replayed create against an active and a dormant session, a @@ -2974,15 +2986,19 @@ next daemon removes before binding. result's `disposition` and `control_entry`. A resolution by existence query would give the same answer to both and is thereby excluded. - *Create, no answer.* The replay is asserted to start no coordinator and - charge no second slot, and the slot count afterwards distinguishes a fresh + *Create, no answer.* The replay is asserted **in-VM** to start no + coordinator — no new pid under core's session supervisor — and to charge no + second slot, and the slot count afterwards distinguishes a fresh original from a replayed one. - *Attach, no answer.* The daemon is asserted to **close that connection**, - and core is asserted to hold one fewer attachment afterwards — the - connection's teardown having detached it — with the reservation released. - No attachment count is read from core at any point, because none exists to - read. + *Attach, no answer.* Two surfaces, and they differ in the two cases. On the + wire, the client's connection is asserted **closed** — an EOF a test can + observe — where a connection whose attach answered stays open. In-VM, core's + attachment registry is asserted to hold one fewer entry afterwards, the + connection's teardown having detached it, and the daemon's reservation count + to be back where it started. Nothing reads an attachment count *from core's + public surface*, because none exists there; the case reads core's own state + in the same VM and says so. Each case asserts the daemon's remaining slot count **in-VM**, reading the reservation state directly rather than through any wire method — no DTO From 6340eec71edec3223309e68ed6aef95effdaed44 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 12:06:09 -0700 Subject: [PATCH 112/585] plan(M5): give core change 1 an attachment release path N-1, and it is a real gap rather than a wording defect. `grep -rn detach apps/loopex/lib/` returns two comments: core has no detach. The dispatcher monitors the attaching process only while its snapshot scan is in flight and demonitors it when the scan finishes (event_dispatcher.ex:455); `disconnect/2` marks an attachment disconnected and empties its queue but leaves the entry (:879-886); and the only path that removes an entry is same-session supersession (:812-823) -- which M5's concurrent-attachment change removes, because coexisting attachments are the point. As written, M5 would have left core with no release path at all. Core change 1 is therefore two halves of one change: supersession stops removing attachments, and the dispatcher keeps its monitor after install and drops the attachment on that process's DOWN. The daemon needs no new API, attaching from its per-connection process, so a closed connection releases its attachment. An explicit `detach/1` is recorded as rejected: it needs a call on every exit path, including the ones where the caller is already gone -- the case a monitor handles for free. Stated in M5.md's core-change list, the ownership table, ADR 0032 (which now rests on the monitor and names event_dispatcher.ex:455 as what changes), the attach reservation rule and its table row, the attach boundary row, and the witnesses -- a core case in concurrent_attachments_test.exs for the monitor itself and the daemon case asserting the dispatcher's count drops after the connection process exits. Flagged in the progress notes as found by the fresh review. --- ...tachment-residency-and-replay-technical.md | 34 ++++++++++++-- docs/plans/M5-technical.md | 47 ++++++++++--------- docs/plans/M5.md | 38 +++++++++++---- 3 files changed, 83 insertions(+), 36 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index bc8b6c179..fcfc47cb8 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -126,13 +126,37 @@ unchanged: every existing-session mutation in generation 2 carries a schema digest of its own. A connection is one attachment after `session.attach`; generation 2 permits a connection to hold at most one attachment at a time and a client process to hold as many -connections as the residency limits admit. **An attachment never outlives its -connection**: closing a connection — because the client went away, because the -daemon is stopping, or because the daemon gave up on a request that never -answered — detaches the core attachment that connection held. That is what -makes a connection a sufficient handle on an attachment, and it is why a +connections as the residency limits admit. + +**An attachment never outlives the process that attached it, and M5 is what +makes that true.** The mechanism is a monitor, not a detach call. Today the +dispatcher monitors the attaching process only while its snapshot scan is in +flight and **demonitors it the moment the scan finishes** +(`event_dispatcher.ex:455`), after which nothing watches that process at all; +`disconnect/2` marks an attachment disconnected and empties its queue but +leaves the entry in place (`:879-886`); and the one path that actually removes +an entry is same-session **supersession** (`:812-823`) — which M5's +concurrent-attachment change removes, because coexisting attachments are the +point. + +So that change has two halves and this pair states both: supersession stops +removing attachments, **and the dispatcher keeps its monitor after install and +removes the attachment on that process's `DOWN`**. Without the second half M5 +would leave core with no release path at all, and every attachment ever made +would live until the runtime stopped. + +For the daemon this needs no API: it attaches from its **per-connection +process**, so a connection that closes — because the client went away, because +the daemon is stopping, or because the daemon gave up on a request that never +answered — ends that process, and the `DOWN` releases the attachment. That is +what makes a connection a sufficient handle on an attachment, and it is why a daemon needs no attachment count from core to release what it reserved. +An explicit `detach/1` on the public API was the alternative and is rejected: +it would add a call every caller must remember on every exit path, including +the paths where the caller is already gone, which is exactly the case a +monitor handles for free. + The core EventDispatcher and Control retain multiple live attachment IDs and incarnations for one session. A new distinct attachment does not implicitly detach another session attachment or cancel its pending read. Repetition of diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index ee81834c2..8ecbe69d8 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create and resume results' `disposition` and `control_entry` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create and resume results' `disposition` and `control_entry` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -334,7 +334,7 @@ core-internal states a daemon cannot construct through the socket. | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | +| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | | **`quiesce/2`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale classifies the session from the journal`; `a fence answering commit_unknown is retried under the same derived tx_id and reported unsettled with fence: :unknown`; `every fence in one drain derives its id from the same drain_id` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | @@ -1018,7 +1018,7 @@ leaked until the daemon restarts: | Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | | A **resume** crashing or timing out | **Held, then resolved by replay**: replayed under its original `command_id`, whose `disposition`/`control_entry` say whether the original call activated the session. The existence query cannot answer this — it says `present` either way | | A **create** crashing or timing out | **Held, then resolved by replay**: replayed under the same `command_id`, which returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | -| An **attach** crashing or timing out | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment (`0032-…-technical.md:126-129`), so the daemon closes that connection and its ordinary teardown detaches whatever core attachment it held. Nothing is observed, because nothing needs to be | +| An **attach** crashing or timing out | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment, and core change 1 monitoring the attaching process. The daemon closes that connection, its process ends, and the dispatcher's `DOWN` handler drops the attachment. Nothing is observed, because nothing needs to be | **That last row is not hypothetical, and the reason is a default nobody chose.** The daemon reaches core through `Loopex.Runtime`, whose @@ -1028,7 +1028,7 @@ returns the daemon an error while core is still starting a coordinator — so "the call gave no answer" is an ordinary outcome of a slow root, not an exotic one. Every daemon call that consumes a ceiling therefore carries an explicit timeout rather than inheriting that default, and resolves its -reservation by observation when the timeout is what it gets. +reservation by the rule its own row names when the timeout is what it gets. **A call that gives the daemon no answer may still have started a coordinator or an attachment**, so releasing the reservation would let the ceiling be @@ -1053,17 +1053,18 @@ because core's resume result carries the same two fields: `:historical` with with `control_entry: :dormant` means it did not, and the daemon converts or releases on that. -**Attach: close the connection and release with it.** Core exposes no -attachment count, so there is nothing to observe — and nothing needs to be. -ADR 0032 binds a connection to **at most one attachment at a time** -(`0032-…-technical.md:126-129`), so the attachment reservation is keyed by -the **connection**, not the session. A connection whose `session.attach` never -answered is closed by the daemon, and its teardown detaches whatever core -attachment that connection holds — the same path every connection close -takes, whether it closed because a client went away or because the daemon gave -up on it. The reservation is released with the connection. That is the whole -resolution: one rule already in the design, applied to a case that otherwise -needed an observer core does not have. +**Attach: end the connection process and the attachment goes with it.** Core +exposes no attachment count, so there is nothing to observe — and nothing +needs to be. ADR 0032 binds a connection to **at most one attachment at a +time** (`0032-…-technical.md:126-129`), the daemon attaches from its +**per-connection process**, and core change 1 makes the dispatcher monitor +that process and drop its attachment on `DOWN`. So the reservation is keyed by +the connection, and a connection whose `session.attach` never answered is +closed by the daemon — the same path every connection close takes, whether the +client went away or the daemon gave up on it — its process ends, and the +attachment is released by the monitor. The reservation is released with it. +Nothing new is called and nothing is observed; the release path is the one +core change 1 adds, and it is named in the inventory rather than assumed. `loopex attach --take-over` against a dormant session therefore acquires successfully and is refused at attach, holding a lease it no longer wants. @@ -2993,12 +2994,14 @@ next daemon removes before binding. *Attach, no answer.* Two surfaces, and they differ in the two cases. On the wire, the client's connection is asserted **closed** — an EOF a test can - observe — where a connection whose attach answered stays open. In-VM, core's - attachment registry is asserted to hold one fewer entry afterwards, the - connection's teardown having detached it, and the daemon's reservation count - to be back where it started. Nothing reads an attachment count *from core's - public surface*, because none exists there; the case reads core's own state - in the same VM and says so. + observe — where a connection whose attach answered stays open. In-VM, the + dispatcher's attachment count is asserted to drop **after the connection + process exits**, and the daemon's reservation count to be back where it + started. The code path that produces that drop is core change 1's monitor, + which the inventory names as new work; a core witness in + `apps/loopex/test/concurrent_attachments_test.exs` proves the monitor + itself, and this case proves the daemon rides it. Nothing reads an + attachment count from core's *public* surface, because none exists there. Each case asserts the daemon's remaining slot count **in-VM**, reading the reservation state directly rather than through any wire method — no DTO @@ -3089,7 +3092,7 @@ survive arrives as `runtime_lost`. | **Store ↔ daemon** | `loopex_store_local` owns the marker and the log; the **daemon owner process** holds the Store's link and pid | Append error, including the capacity refusal | The Store stops **itself** (`local.ex:251-270` answers `{:stop, reason, commit_unknown, state}`) and releases the marker in `terminate/2` (`local.ex:167`). The owner's `{:EXIT, store_pid, reason}` clause receives it **with the store's real reason**, which is what distinguishes `store_capacity_exceeded` from `store_lost` | `daemon.stopping` with `store_lost` or `store_capacity_exceeded`, one bounded attempt, then the socket closes | **Durable:** whatever committed. **Not:** the failed append; the in-flight transaction is `commit_unknown` and reconciles later | | **Store ↔ daemon (startup)** | The adapter | Marker held, unverifiable, log too large | `WriterLock.acquire` refuses with `store_writer_active` / `store_writer_unverifiable`; `Log.open` refuses `store_log_too_large` (`log.ex:80-84`) | Nothing — no socket exists yet | **Not durable:** nothing was written. Reverse cleanup leaves no marker | | **Core ↔ daemon: existence query** | `loopex` answers; the daemon asks | Root unreadable, malformed ID, unrecognised answer | The query's own closed result set — `present`, `absent`, `invalid_id`, `store_unavailable`, `unexpected` (this plan's new core operation) | The matching refusal, four of them distinct; nothing created, nothing attached, no lease | **Not durable:** the query writes nothing, proved by a byte-identical root | -| **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow | Core's existing attach transaction and stale-handle checks; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | +| **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow, **an attachment whose holder is gone** | Core's existing attach transaction and stale-handle checks; **and core change 1's monitor on the attaching process, which is what releases an attachment when its holder exits — the daemon attaches from its per-connection process, so a closed connection releases its attachment with no call**; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | | **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies; its in-flight admission set goes with it, and the relay's ticket for any mutation it had authorized does not | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller attachment closes with `control_owner_lost`; observers stay attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch, its first grant waiting until the relay's outstanding tickets for that session settle | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 5d7833911..25d51b22a 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -40,15 +40,21 @@ channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above -the core. Core gains exactly five narrow things: support for several independent -attachments to one session; one read-only query that answers whether a session -ID exists durably in the root; `Loopex.Trace.exclude_self/2`, which installs +the core. Core gains exactly five narrow things: support for several +independent attachments to one session — which is two halves of one change, +since it stops same-session supersession from removing an attachment and +therefore has to add what removes one instead, a monitor on the attaching +process that releases its attachment when that process ends; one read-only +query that answers whether a session ID exists durably in the root; `Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion accepted ADR 0030 names and the process-level exclusion its callees need, before any message is delivered; `quiesce/2`, the bounded settle an orderly stop -drains through; and two plain fields on the **runtime-side** create and resume results, -telling a host whether the create it just made was fresh or a replay and -whether the session is active or dormant — the public protocol result is -unchanged. It gains no lease, no transport, no +drains through; and two plain fields on the **runtime-side** create and resume +results — `disposition`, saying whether the call was fresh or a replay, and +`control_entry`, saying whether core's `Control` holds that session as active +or dormant at the instant of the call. `control_entry` is deliberately not +called `residency`: that word is a **daemon** fact on the wire, about this +daemon's lifetime, and the two differ exactly when `Control` still lists a +session whose coordinator has died. The public protocol result is unchanged. It gains no lease, no transport, no second loop and no new durable command. @@ -943,8 +949,22 @@ sections they govern. Drafting that page now was rejected, because it would document a component that does not exist; the obligation is what carries it to closure instead. -**One `0.1.0` defect was found during that review and is recorded rather than -patched.** On 2026-09-20, checking what the generation rename would cost, the +**A core gap was found by the fresh review and closed in the design.** Core's +concurrent-attachment change removes same-session supersession — and +supersession is the **only** path that removes an attachment today: +the dispatcher demonitors the attaching process the moment its snapshot scan +finishes, and `disconnect/2` marks an attachment disconnected without removing +it. Made as written, that change would have left core with no attachment +release path at all, and every attachment ever made would have lived until the +runtime stopped. Core change 1 therefore has two halves: supersession stops +removing, and the dispatcher keeps its monitor and removes on the attaching +process's `DOWN`. An explicit detach API was the alternative and was rejected, +since it needs a call on every exit path including the ones where the caller +is already gone. The daemon needs nothing new: it attaches from its +per-connection process. + +**One `0.1.0` defect was found during an earlier review and is recorded rather +than patched.** On 2026-09-20, checking what the generation rename would cost, the released protocol surface was found to disagree with itself: `session.ex:32` serves `loopex.session.v1-experimental` and the conformance module pins that string, while the two digest-pinned manifests published for independent From 50aa17e6b7823b2ab4ff3ccc1e7a6eb8b602b628 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 12:08:25 -0700 Subject: [PATCH 113/585] plan(M5): quiesce takes no deadline; fix the stop line and status N-0 the Outcome-1 evidence row's store-loss clause says the pathname is left in place. Remaining `unlink` hits across docs/ are all correct: the rule statement and its history, the startup "never reads, unlinks or binds" precondition, the owner started **unlinked**, and ADR 0031/0032 stating that no daemon unlinks on its way out. N-2 `quiesce/1` takes the runtime and nothing else. Passing the daemon's teardown deadline contradicted the rule that the teardown clock starts when the call *returns* -- a deadline cannot both bound the drain and begin after it. Core owns the drain clock, derives the budget and returns it; every `quiesce/2` mention is now the real arity, 28 across four files. N-3 ADR 0034's Concept no longer says ADR 0030 "claims a match-specification exclusion the tracer does not have" or that exclusion is "by process, not by function": M5 implements the match specification, and the exclusion is by function and by process together in one call. N-4 the vocabulary rule covers what a **fatal** exit may say; an orderly stop adds one census line naming `drain_id`, `budget_ms` and the three counts. The idle-shutdown witness asserts `stderr` carries nothing but that line and no fatal class in it. N-4b the witness preamble labels real-process and in-VM cases instead of claiming all are real processes. N-5 `daemon.status` does not report the budget, in the operator obligation or the bound: it would have to answer "what budget would you use", which the daemon cannot compute, on a key ADR 0032's DTO tables do not define. The stop line carries it, and a `TimeoutStopSec` is set from what a previous stop reported. N-6 the release script reads the summary line without assuming one toolchain's shape, the format differing between the two supported pairs -- the earlier "the release check runs the older pair too" was false, the floor run being `check.sh`. N-7 the reservation resolves "by the rule its own row names". N-8 `control.ex:909-918`, the `true ->` arm at :909 calling `start_owner` at :910. N-10 `listener_lost` has no wire reason, and the map says why. --- ...tachment-residency-and-replay-technical.md | 2 +- ...-daemon-attachment-residency-and-replay.md | 2 +- ...edential-handoff-over-bootstrap-channel.md | 18 +-- docs/plans/M5-technical.md | 124 ++++++++++-------- docs/plans/M5.md | 14 +- 5 files changed, 91 insertions(+), 69 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index fcfc47cb8..08fd63520 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -730,7 +730,7 @@ an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and none of M5's five core changes (concurrent attachment, the read-only existence -query, the trace exclusion, `quiesce/2`, and the create and resume results' +query, the trace exclusion, `quiesce/1`, and the create and resume results' `disposition` and `residency` fields) stops a coordinator, so a deactivation call would be a further core change this milestone does not make. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index e0d38ff84..e0542eb66 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -59,7 +59,7 @@ method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core has no durable stop command, and M5's five core changes — concurrent attachment, a read-only existence query, the trace exclusion, the bounded -`quiesce/2`, and the create and resume results' two new fields — are none of +`quiesce/1`, and the create and resume results' two new fields — are none of them durable commands. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by acquiring control and diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 20fe9a8ee..8eb5af6cc 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -96,8 +96,9 @@ is written — and it is the same class of act as writing the credential frame, protected the same way ADR 0019 already protects that sender. The registry lookup before it carries no credential, so routing adds no second place a secret can be seen. What keeps those bytes out of a trace is stated against -the implementation rather than against ADR 0030's prose, which claims a -match-specification exclusion the tracer does not have: the adapter is in no +the implementation rather than against an assumption about it, and ADR 0030's +match-specification exclusion is **implemented by M5 rather than assumed +present**: the adapter is in no default trace namespace, so the credential work is untraced under every default configuration; and where a host explicitly names the adapter module, the credential-bearing functions are **excluded before a trace message is @@ -107,12 +108,13 @@ because the raw call reaches the tracer first; it stays as defence in depth, resting on a bound *shape* — those bytes always travel under a credential-named key and are placeholdered at any size, which size alone would not give, since the pass leaves a short binary verbatim and a credential may -be one byte. The exclusion is by **process**, not by function: the sender excludes itself -from every trace session before it resolves anything, because a function that -carries the credential calls functions it does not own — a traced -`:gen_tcp.send/2` shows the frame whatever this adapter's modules are -patterned. M5 proves it at the tracer rather than at the sink, in a case that -names `:gen_tcp` on purpose. ADR 0030 is not edited: its prose is honoured +be one byte. The exclusion is **by function and by process together**, in one call: the +match specification ADR 0030 names, for the functions that hold the bytes, and +a process-level exclusion the sender installs on itself before it resolves +anything — because a function that carries the credential calls functions it +does not own, and a traced `:gen_tcp.send/2` shows the frame whatever this +adapter's own functions are patterned. M5 proves both at the tracer rather +than at the sink, in a case that names `:gen_tcp` on purpose. ADR 0030 is not edited: its prose is honoured once this lands. **Everywhere else the boundary is where the adapter's claims stop.** Inside it diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8ecbe69d8..0eeb06a8e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/2` that settles every active coordinator or names what it could not**, **the runtime-side create and resume results' `disposition` and `control_entry` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not**, **the runtime-side create and resume results' `disposition` and `control_entry` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -142,7 +142,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/2` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), unlinks and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -235,12 +235,11 @@ appears only in its opening banner — and it pipes each lane's suite summary to M5 changes the script in two ways: - it reads `scripts/suite-summary.sh`'s result line instead of discarding it, - which is what lets any lane assert a count at all — and it **re-derives the - count on the shape that lane's toolchain prints**, because the summary - line's format is the current pair's, and the release check runs the older - pair too; a script that parsed one shape would silently read zero on the - other, which is exactly the false negative an executed-count assertion - exists to prevent; and + which is what lets any lane assert a count at all — and it reads that line + **without assuming one toolchain's shape**, because the summary format + differs between the two supported pairs and a parser fixed to one of them + would silently read zero on the other, which is exactly the false negative + an executed-count assertion exists to prevent; and - it branches on platform for this one lane. On Linux it runs `mix test --only cross_uid` and asserts **exactly two** executed. On any other platform it runs nothing for that lane, prints @@ -298,8 +297,8 @@ reviewer can check against this sentence at closure. it, that the drain budget is **not** read off the daemon's own `--cleanup-grace-ms`, because each session drains under the grace it committed and a root may carry sessions composed earlier, so the page must - point an operator at the figure the daemon **reports** in its stop line and - in `daemon.status` rather than at one they can compute from flags. And that + point an operator at the figure the daemon **reports in its stop line** + rather than at one they can compute from flags. And that a shorter external service-manager timeout turns the stop into a **forced shutdown**, where work that would have settled does not and the writer marker may be left for the next daemon's verified recovery. It must also distinguish the **usual @@ -336,7 +335,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/2`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale classifies the session from the journal`; `a fence answering commit_unknown is retried under the same derived tx_id and reported unsettled with fence: :unknown`; `every fence in one drain derives its id from the same drain_id` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale classifies the session from the journal`; `a fence answering commit_unknown is retried under the same derived tx_id and reported unsettled with fence: :unknown`; `every fence in one drain derives its id from the same drain_id` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | @@ -856,8 +855,9 @@ is *replayed*, without activating anything. Today it cannot do either reliably, because every path answers the same way. Two branches reply `{:ok, session_id}` directly — the session is already active (`control.ex:903-904`), or the command was seen before so no owner is started (`:906-907`). The third -starts one (`:909-918`) and replies **`{:noreply, next}`**, the `{:ok, -session_id}` arriving later through `owner_ready_reply/4` (`:532`). Three +starts one — the `true ->` arm at `:909`, calling `start_owner` at `:910` — +and replies **`{:noreply, next}`**, the `{:ok, session_id}` arriving later +through `owner_ready_reply/4` (`:532`). Three paths, one indistinguishable value. Core already computes what is missing, and uses it: `create_command_absent?/2` @@ -879,7 +879,7 @@ about a session in *this daemon's* lifetime — while this field says what `Loopex.Runtime.Control` holds for that session at the instant of the call. The two coincide today and would not always: a session `Control` still lists as active may have no live coordinator, which is precisely the `absent` case -`quiesce/2` reports. Giving both the same name would have invited a daemon to +`quiesce/1` reports. Giving both the same name would have invited a daemon to forward one as the other. `residency` stays daemon-only; `control_entry` is core's. @@ -978,7 +978,7 @@ in its own process. **The activation ceiling is enforced by reservation, because counting after the call is a race.** Core starts a coordinator *inside* the call that would tell the -daemon it did — `start_owner` for a fresh create (`control.ex:908`), +daemon it did — `start_owner` for a fresh create (`control.ex:909-918`), `start_resume_owner` for a resume that is not a replay (`control.ex:318`, `:321`) — so a daemon that counts when the call returns has already let it happen. Two consequences, both real: at 63 activations two concurrent calls @@ -1794,7 +1794,7 @@ state. The contract is three clocks: | Clock | What it bounds | Where the number comes from | | --- | --- | --- | | **`g`**, each session's committed `cleanup_grace_ms` | The cancellation of that session's effects, and nothing else | The session's own composition; already used by `Loopex.Executor.cancellation_bounds/1` | -| **`budget_ms`**, the drain budget | The whole drain, across every session | Derived **by core, inside `quiesce/2`**, and **returned** in its result: `max` over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` (`apps/loopex/lib/loopex/executor.ex:456-474`, where `cli_backstop_ms` is `observe + reserve + terminal`, documented as "the sum a process-liveness backstop must cover"). The daemon does not compute it, because it does not hold the `g_i` | +| **`budget_ms`**, the drain budget | The whole drain, across every session | Derived **by core, inside `quiesce/1`**, and **returned** in its result: `max` over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` (`apps/loopex/lib/loopex/executor.ex:456-474`, where `cli_backstop_ms` is `observe + reserve + terminal`, documented as "the sum a process-liveness backstop must cover"). The daemon does not compute it, because it does not hold the `g_i` | | **`teardown_ms`, fixed at `5_000`** | **One absolute deadline covering every non-Store action after the drain** — the `daemon.stopping` writes, closing the connections, closing the listener, the lease owners, the relay, the runtime, the executor, the workspace lease, transfers, custody and the registry | A plan decision, and the rationale is that each of those is a bounded write or a stop of a process with no `terminate/2` to run: milliseconds apiece, so five seconds is a ceiling none of them should approach and an upper bound an operator can add up | | **The Store phase** | The Store's stop alone | A **fixed 30 s**, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of `g` and of `teardown_ms` | @@ -1812,7 +1812,7 @@ default a *new* session is composed with (`control.ex:890-891`), not a fact about sessions already in the root. A root carrying sessions created under an earlier composition therefore holds graces the daemon has never seen. An earlier revision had the daemon compute the budget from its own option, which -would have been wrong for exactly the roots a daemon is for. So `quiesce/2` +would have been wrong for exactly the roots a daemon is for. So `quiesce/1` derives it from the durable graces and **returns** it as `budget_ms`, and the daemon reports that figure rather than one it assumed. @@ -1836,7 +1836,7 @@ stopped here only the transfers owner runs a `terminate/2` at all — so the budget is a ceiling for a set of actions that are each milliseconds. It is recorded in the limits table with that rationale. -**The deadline starts the instant `quiesce/2` returns**, and it covers +**The deadline starts the instant `quiesce/1` returns**, and it covers **every** non-Store action from that point: the stop records, the connection closes, the listener close, and every stop from the lease owners through the registry. An earlier revision's formula covered only the stops, which left the @@ -1853,10 +1853,13 @@ operator page says so rather than implying a constant. The composed `--cleanup-grace-ms` bounds the sessions this daemon *creates*; a root carrying sessions created earlier may drain longer, because each session drains under the grace it committed. What an operator can rely on is that the -figure actually used is **reported**: the daemon's stop line carries the -`budget_ms` core returned, and `daemon.status` carries the budget the daemon -would use if it were asked to stop now. A `TimeoutStopSec` is therefore set -from an observed figure rather than a guessed one. A service manager that kills the daemon sooner than that +figure actually used is **reported on the stop line**: `budget_ms`, as core +returned it, beside `drain_id` and the three counts. It is deliberately **not** +on `daemon.status`, and that took correcting — a status field would have to +answer "what budget *would* you use", which the daemon cannot compute, on a +key ADR 0032's DTO tables do not define. A `TimeoutStopSec` is therefore set +from the figure a previous stop reported rather than from one the daemon +guesses in advance. A service manager that kills the daemon sooner than that turns the stop into a forced shutdown — the journal is still crash-equivalent, but work that would have settled does not, and the marker may be left for the next daemon's verified stale-writer recovery. The operator documentation states the bound @@ -1912,10 +1915,11 @@ the owner fixes. drain, because a client that is about to be told something true is better served by being told it than by an early close. 2. **The runtime is quiesced within the budget core derives.** The owner - calls core's `quiesce/2`, passing its own teardown deadline so core will - not overrun what the daemon has left, and waits for its answer, which - names the sessions that settled and the sessions that did not — and, by the - time it answers, every session it could not settle has already been fenced + calls core's `quiesce/1` — which takes no deadline, core owning the drain + clock entirely — and waits for its answer, which names the sessions that + settled, those that did not, those that were already gone, and the budget + core used — and, by the time it answers, every session it could not settle + has already been fenced and terminated inside core. This is the drain; what it does, and what it cannot do, is set out below. 3. **Clients are told, and the listener closes. The socket path is left @@ -1936,7 +1940,7 @@ the owner fixes. because there is no attachment left to close. 5. **The runtime stops.** After the drain there is little left to end — every coordinator quiesce could not settle was fenced and terminated inside core - before `quiesce/2` returned — so this step ends the tree rather than the + before `quiesce/1` returned — so this step ends the tree rather than the work. The helper calls `Supervisor.stop(runtime_supervisor, :normal, remaining)` on the pid the composition function handed it, where `remaining` is what is left of the @@ -2089,7 +2093,7 @@ on 2026-09-20 and gave it one. The mechanism is a **fourth core change**, beside concurrent attachment, the existence query and the trace exclusion: ```elixir -Loopex.Runtime.quiesce(runtime, teardown_deadline_ms) :: +Loopex.Runtime.quiesce(runtime) :: {:ok, %{ settled: [session_id], unsettled: [session_id], @@ -2098,14 +2102,20 @@ Loopex.Runtime.quiesce(runtime, teardown_deadline_ms) :: }} ``` -**Four keys, and two of them are answers to questions the daemon cannot -ask.** `absent` names the sessions `Control` still held as active whose -coordinator was already gone, which is neither settled nor unsettled and must -not be counted as either. `budget_ms` is the drain budget **core derived and -used**, returned because the daemon cannot compute it — the argument below. -The single argument is the daemon's own clock, not a drain budget: it is the -teardown deadline the daemon must still meet afterwards, so core can refuse to -exceed what the caller has left. +**One argument, four keys, and no deadline crosses the boundary.** An earlier +revision passed the daemon's teardown deadline in, which contradicted the rule +two paragraphs later that the teardown clock starts when `quiesce/1` +*returns*: a deadline cannot both bound the drain and begin after it. It takes +the runtime and nothing else. Core derives the budget, enforces it, and +returns it as `budget_ms`; the daemon's own five seconds start when the call +comes back. A long derived budget is not a hazard the argument would have +fixed either — it is what the operator bound above already reports, and what a +service manager's own timeout is set against. + +Of the four keys, two answer questions the daemon cannot ask. `absent` names +the sessions `Control` still held as active whose coordinator was already +gone, which is neither settled nor unsettled and must not be counted as +either. `budget_ms` is the drain budget core derived and used. **Three parts, in order, and the first two are one thing split in half.** @@ -2263,7 +2273,7 @@ exceed what the caller has left. | `expected_owner_epoch`, `expected_journal_version` | Read **fresh** from `Store.ownership_head/3`, exactly as the coordinator reads them (`session_coordinator.ex:1337-1343`), so the fence binds the state it is actually fencing | | `proposed_owner_incarnation_id` | A fresh incarnation, in the same form the coordinator mints (`fresh_incarnation/2`, `:1500`) | - **`drain_id` is one identity per `quiesce/2` call, and it has to be, because + **`drain_id` is one identity per `quiesce/1` call, and it has to be, because the abort's `command_id` is not available for every fenced session.** An earlier revision derived the fence's `tx_id` from that abort — which works for a session that was drained and fails for an `absent` one, where no @@ -2306,7 +2316,7 @@ exceed what the caller has left. | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | Retried with the **same derived `tx_id`**, which is idempotent by construction, until the drain deadline; if it is still unknown then, the session is reported `unsettled` with `fence: :unknown` | So the claim the plan makes is the one the mechanism supports: when - `quiesce/2` returns, every session it reports as fenced has had its epoch + `quiesce/1` returns, every session it reports as fenced has had its epoch moved, and every session it reports otherwise is classified from what the journal actually holds. What it does **not** claim is that no transaction anywhere can still commit — a fence that is itself `commit_unknown` is @@ -2334,7 +2344,7 @@ exceed what the caller has left. and `dispatcher_call/3` both default to `5_000` (`runtime.ex:470`, `:478`), and a drain whose budget is derived from a session's cleanup grace will routinely exceed that — a five-second reply timeout would abandon a drain that was -working and leave the daemon tearing down underneath it. `quiesce/2` therefore +working and leave the daemon tearing down underneath it. `quiesce/1` therefore calls with an explicit `:infinity` reply timeout and carries its **own** deadline as data: the budget is enforced inside core, where the work is, and the caller waits for the answer rather than racing it. @@ -2363,7 +2373,7 @@ of `max(10_000, grace_ms + 2_000)` from that same grace still. **What queues while the owner waits for it.** The owner is blocked in the -`quiesce/2` call for at most the budget core derives, and while it is blocked it is not +`quiesce/1` call for at most the budget core derives, and while it is blocked it is not reading its mailbox: a linked component's `{:EXIT, …}` waits, as does a second signal. That is safe in one direction and deliberate in the other. The wait is bounded, so nothing waits indefinitely; and when the call returns, the owner @@ -2569,7 +2579,7 @@ die without a name for it. | `capability_lost` | The tracing capability exited | `fatal:capability_lost` | | `runtime_lost` | The runtime root exited | `fatal:runtime_lost` | | `relay_lost` | The admission relay exited, taking every outstanding admission ticket with it | `fatal:relay_lost` | -| `listener_lost` | The listener exited | `fatal:listener_lost` | +| `listener_lost` | The listener exited | — the listener is what would have written it | **A lease owner's exit is the one that is not in this table**, and its absence is the rule rather than an omission. The owner's clause maps that pid to the @@ -2621,7 +2631,11 @@ and no artifact bytes, exactly as ADR 0030's metadata rule already forbids for a trace or a telemetry span. Nothing here is a new logging plane: the daemon has no diagnostic surface of its own beyond these lines and the records it already sends on the wire, and the fatal-class map above is the whole -vocabulary of what an exit may say. +vocabulary of what a **fatal** exit may say. An **orderly** stop adds exactly +one line and no class: a census naming `drain_id`, `budget_ms` and the three +counts quiesce returned. That line is the only thing an ordinary stop writes +to `stderr`, and it names no fatal class, which is what a reader checks it +for. **Reverse cleanup.** Startup happens inside the owner, so a failure at any step unwinds what that step and its predecessors did, in reverse — and @@ -2652,7 +2666,11 @@ leaves **no marker held** — which is what lets an operator fix the cause and try again without a recovery step — and may leave a socket pathname, which the next daemon removes before binding. -**Witnesses**, all on real operating-system processes: +**Witnesses.** Most run a real daemon operating-system process; a few read +state no surface exposes and run **in-VM**, in the same VM as the daemon or +the runtime they are about. Each is labelled, because a case that says +"asserts core holds N" without saying where N is read is the defect class this +plan spent a round removing. - **Idle shutdown.** A daemon with sessions activated and no work in flight receives `SIGTERM`, writes nothing further to `stdout`, closes every @@ -2661,9 +2679,11 @@ next daemon removes before binding. exits `0`; the foreground server then opens the same root immediately, which is what proves the marker was actually released. The case also asserts the negative that the `stopping` field exists for: **no fatal class is recorded - at any point during the stop**, and nothing appears on `stderr` — stopping - every linked process deliberately produces an exit from each, and every one of - them must be consumed rather than classified. + at any point during the stop**, and `stderr` carries **nothing but the one + census line** — `drain_id`, `budget_ms` and three counts — **with no fatal + class in it**. Stopping every linked process deliberately produces an exit + from each, and every one of them must be consumed rather than classified. + (Real process.) - **A real failure during an orderly stop is still classified, and the sequence still finishes.** The Store is made to fail while the listener is being stopped. The case asserts three things, because the second and third @@ -2734,7 +2754,7 @@ next daemon removes before binding. *It settles.* A daemon with a dispatched tool effect that **can** be cancelled inside its session's own grace receives `SIGTERM`. The case - asserts the effect settles during `quiesce/2`, that its session is in the + asserts the effect settles during `quiesce/1`, that its session is in the returned `settled` list, that the journal carries its ordinary terminal fact — `cancelled`, which is now a true statement about work that was truly cancelled — and that the `daemon.stopping` record is written **after** the @@ -2742,7 +2762,7 @@ next daemon removes before binding. *It does not.* A daemon with an effect held past the drain budget and an unresolved mutation receives `SIGTERM`. The case asserts the session is in - the `unsettled` list; that its coordinator is **gone before `quiesce/2` + the `unsettled` list; that its coordinator is **gone before `quiesce/1` returned**, read **in-VM** as that coordinator's pid being dead at the instant the daemon reports it — `Process.alive?` on a pid the case holds, not a wire field; and then the negative @@ -3073,7 +3093,7 @@ survive arrives as `runtime_lost`. | Group | Owner | Count | What its loss means to the daemon | | --- | --- | --- | --- | -| **Session coordinators** | Core's session supervisor, `restart: :temporary` | One per active session | Core's own refusal on the next command; **no signal reaches the daemon and none is owed**. `quiesce/2` terminates and fences them at the drain deadline | +| **Session coordinators** | Core's session supervisor, `restart: :temporary` | One per active session | Core's own refusal on the next command; **no signal reaches the daemon and none is owed**. `quiesce/1` terminates and fences them at the drain deadline | | **Owner groups and their workers** | Core, beneath a coordinator | Per coordinator | Core's; a trapping owner group unwinds on its own clock and the daemon does not wait | | **Event dispatcher** | The runtime root | **One per runtime**, holding the per-attachment queues — not one per attachment, which an earlier revision of this table said | Restarted by the root under `:rest_for_one`, which restarts the tracer with it | | **`Control`** | The runtime root | One per runtime | Holds the trace exclusion set and the session entries; its restart is the root's business, and it carries the tracer with it | @@ -3100,7 +3120,7 @@ survive arrives as `runtime_lost`. | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry, custody and the tracing capability; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline, or a trace exclusion that cannot be confirmed | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | | **CLI ↔ socket** | `loopex_cli` | Socket unreachable, refusal, transport loss, renewal failure | The client's own reconnect loop and its renewal timer | Reconnect at the retained cursor, deduplicating; a failed renewal drops to observer with the loss on `stderr`; a reconnecting controller must acquire again for a fresh epoch | **Durable:** nothing the client holds. The cursor is a client-side position | -| **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/2` within the derived drain budget, tells clients, closes the listener while **leaving the socket pathname for the next verified marker holder**, and then stops its linked processes in reverse order — lease owners, the relay, runtime, edges, and the Store last in its own fixed 30 s phase — each stop driven by a monitored helper calling `GenServer.stop/3` while the owner waits on its own link until the shared teardown deadline and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | +| **Daemon ↔ OS: signals** | The operator | `SIGTERM`, delivered to the handler the daemon installs before it takes the marker; a terminal `SIGINT` reaches it only as the `SIGTERM` the launcher forwards, since `:os.set_signal/2` refuses `:sigint` | The owner drains through core's `quiesce/1` within the derived drain budget, tells clients, closes the listener while **leaving the socket pathname for the next verified marker holder**, and then stops its linked processes in reverse order — lease owners, the relay, runtime, edges, and the Store last in its own fixed 30 s phase — each stop driven by a monitored helper calling `GenServer.stop/3` while the owner waits on its own link until the shared teardown deadline and kills on expiry. Classification is from the observed exit reason alone: `:normal`, `:shutdown` and the owner's own `:killed` are consumed, everything else is classified | `daemon.stopping` with `operator_stop`, then close | **Durable:** whatever committed. **Not:** work ended crash-equivalently — a claim about the journal, not about every process being gone | | **Daemon ↔ OS: kill** | The operator | `SIGKILL`, power loss | Nothing runs — no handler, no `terminate/2` | The socket closes with no record at all | **Durable:** the journal. The marker is left for the next daemon's verified stale-writer recovery | | **Daemon ↔ OS: socket file** | `loopex_daemon` | A stale `daemon.sock` left by any exit path | Only a daemon that has acquired and verified the marker removes it, at startup, before binding; no daemon removes one on its way out, so no predecessor can delete a successor's socket | The loser of two simultaneous starts exits without touching the socket; a client meeting a stale path is refused rather than hung | **Not durable:** the socket file is a path, never state | | **Daemon ↔ OS: marker** | `loopex_store_local` | Released in order, released early, or left behind | Four dispositions, and the plan states all four: `terminate/2` in an orderly stop; `terminate/2` early, before the daemon can act, on store loss; `terminate/2` on a **fatal class where the Store is still alive**, because the fail-stop path stops it before halting; and **nothing** on a `SIGKILL`, a power loss, or a Store stop that timed out and was killed | The client sees only the `daemon.stopping` reason; the marker is invisible to it | **Not durable in the journal sense:** the marker is exclusion, not truth. A surviving marker is the case ADR 0031's recovery rule answers | @@ -3155,7 +3175,7 @@ nothing and add no wire surface: they exist because core computes `fresh?` at `control.ex:895` and then throws it away four lines later, leaving every caller unable to tell a fresh create from a replay. Direct code cannot supply them, because the only alternative is inferring the answer from side effects, -which is a race. **One bounded `quiesce/2`** — which unifies nothing today and says so: +which is a race. **One bounded `quiesce/1`** — which unifies nothing today and says so: its only caller is the daemon's orderly stop, and the app-server host does not drain by hand, because `LoopexComposition.with_runtime/2` brackets a runtime that lives and dies with one client's stdin and has nothing to drain @@ -3222,7 +3242,7 @@ line; M5 introduces none of its own. | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | -| Non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/2` returns, covering the stop records, the connection and listener closes and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | +| Non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | | Store shutdown phase | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 25d51b22a..3b0b78fbe 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -47,7 +47,7 @@ therefore has to add what removes one instead, a monitor on the attaching process that releases its attachment when that process ends; one read-only query that answers whether a session ID exists durably in the root; `Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion accepted ADR 0030 names and the -process-level exclusion its callees need, before any message is delivered; `quiesce/2`, the bounded settle an orderly stop +process-level exclusion its callees need, before any message is delivered; `quiesce/1`, the bounded settle an orderly stop drains through; and two plain fields on the **runtime-side** create and resume results — `disposition`, saying whether the call was fresh or a replay, and `control_entry`, saying whether core's `Control` holds that session as active @@ -62,7 +62,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/2` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -108,7 +108,7 @@ serves generation `loopex.experimental/2` only, which adds `session.list`, the one-attachment-per-process rule to residency limits. It adds no durable method: core owns durable session truth and its M5 changes are concurrent attachment, one read-only existence query, trace exclusion, the bounded -`quiesce/2` and two fields on the runtime-side create and resume results, none of which is +`quiesce/1` and two fields on the runtime-side create and resume results, none of which is a durable command, so a daemon method that ended a session durably would have to add one, which M5 does not do. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, @@ -125,7 +125,7 @@ unresolved `commit_unknown` or an admission executing inside core, so "idle" is not "quiescent" and stopping on idleness would destroy exactly what Outcome 1 exists to prove. And there is nothing to stop it with: core owns coordinator lifetime, and M5's five core changes — concurrent attachment, a -read-only existence query, trace exclusion, the bounded `quiesce/2` and the +read-only existence query, trace exclusion, the bounded `quiesce/1` and the create and resume results' two new fields — none of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at @@ -374,7 +374,7 @@ path removes; stop the lease owners and then the runtime, which ends crash-equiv did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. -**The drain has a mechanism, and it is core's.** M5 adds `quiesce/2` to +**The drain has a mechanism, and it is core's.** M5 adds `quiesce/1` to `Loopex.Runtime`, and it has three parts. **Phase one** durably admits the existing abort command for every active session and stops there, because ADR 0023 fixes that only a durable `session.abort` cancels and nothing may infer @@ -482,7 +482,7 @@ Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan No controller lease, transport, socket or collaboration rule inside core. Its only M5 changes are independent concurrent attachment support, one read-only session-existence query, the trace exclusion that accepted ADR 0030 already -requires, the bounded `quiesce/2` an orderly stop drains through, and two +requires, the bounded `quiesce/1` an orderly stop drains through, and two plain fields on the runtime-side create and resume results — none of which is a durable command, and none of which changes a wire schema. No daemon-grade store adapter, journal format version, migration, backup tooling, compaction, @@ -751,7 +751,7 @@ lease — and the companion's rejoin order says where each part goes. two-part trace exclusion that accepted ADR 0030 already requires, which lands with workstream 5's credential work because that is what it protects; and the bounded - `quiesce/2` the orderly stop drains through, which lands before workstream + `quiesce/1` the orderly stop drains through, which lands before workstream 2's shutdown sequence because that sequence cannot be proved without it. The first two land first, because nothing about the daemon can be proved without them — and then, once the lease exists, the daemon-side residency From 9240589856316b8a5ede69cf72de1276abff65d9 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 12:09:02 -0700 Subject: [PATCH 114/585] plan(M5): three lists and budget_ms in the two remaining summaries N-9 and N-11's last sites: the Outcome-1 evidence row now names the three lists and the reported budget, and the plain-data sentence says three lists and one integer rather than two lists. The `control_entry` field and its meaning were added to M5.md in the core-change-1 commit. --- docs/plans/M5-technical.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 0eeb06a8e..87651d035 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -142,7 +142,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -2359,7 +2359,7 @@ or running a cancellation loop of its own, which is precisely the second loop this milestone forbids — and it certainly cannot admit a durable command on its own authority. Core owns coordinator lifetime, cancellation and admission, so core is where a bounded settle belongs. It returns **plain data** — session -IDs and two lists — so nothing about a coordinator crosses the boundary. +IDs, three lists and one integer — so nothing about a coordinator crosses the boundary. **What it does not promise.** A session whose cancellation cannot finish inside the derived budget is reported **unsettled**, and its coordinator is From 94ad1118331c9a05328dfe15cd0dd7ae2a2626a7 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 12:09:49 -0700 Subject: [PATCH 115/585] plan(M5): name the surface and the change behind every witness Class 25's added clause: a difference is only checkable if the code path that produces it exists today or is named as a change. The witness preamble now says which three surfaces are new work -- the dispatcher's release on DOWN, Control's excluded-pid set, and quiesce/1's three lists and budget_ms -- and that everything else is read from the journal, a supervisor's children, a pid's liveness, a socket's EOF or the daemon's own stderr. The attachment-release citation points at ADR 0032's new release rule rather than at the one-attachment sentence alone. --- docs/plans/M5-technical.md | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 87651d035..8745fe973 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1056,7 +1056,7 @@ releases on that. **Attach: end the connection process and the attachment goes with it.** Core exposes no attachment count, so there is nothing to observe — and nothing needs to be. ADR 0032 binds a connection to **at most one attachment at a -time** (`0032-…-technical.md:126-129`), the daemon attaches from its +time** (`0032-…-technical.md:127-129`, with the release rule at `:131-155`), the daemon attaches from its **per-connection process**, and core change 1 makes the dispatcher monitor that process and drop its attachment on `DOWN`. So the reservation is keyed by the connection, and a connection whose `session.attach` never answered is @@ -2671,6 +2671,18 @@ state no surface exposes and run **in-VM**, in the same VM as the daemon or the runtime they are about. Each is labelled, because a case that says "asserts core holds N" without saying where N is read is the defect class this plan spent a round removing. +**A note on how these are written, added after a review found three that +could not be checked.** Every witness here names the **surface** it reads, the +**two answers** that must differ on it, and — where the surface is new — the +**change that creates it**. A case asserting "core holds N" without saying +where N is read is not a case anybody can write; nor is one whose difference +depends on a code path that does not exist. Three of this plan's surfaces are +new work rather than existing behaviour, and each is named where it is used: +the **dispatcher's release on `DOWN`** (core change 1), **`Control`'s +excluded-pid set** (core change 3), and **`quiesce/1`'s three lists and +`budget_ms`** (core change 4). Everything else is read from something that +exists today — the journal, a supervisor's children, a pid's liveness, a +socket's EOF, or the daemon's own `stderr`. - **Idle shutdown.** A daemon with sessions activated and no work in flight receives `SIGTERM`, writes nothing further to `stdout`, closes every From fadde622ec07561848fa7e4d494fe2c19315d953 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 12:16:40 -0700 Subject: [PATCH 116/585] plan(M5): qualify the timeout rule and name the attach release surface R-1. "Every daemon call that consumes a ceiling carries an explicit timeout" was false for attach, and the exception is the interesting part. `Runtime.attach/3` takes no timeout at all (runtime.ex:198-210) and waits `:infinity` twice inside, at the dispatcher and at the install (:538, :547), precisely so a caller timeout cannot revoke a mutation it cannot see -- which the code says there in as many words. The rule now reads "and accepts one", the attach row is headed by what actually happens (a connection process ending before the call answers), "gave up" is stated as the owner ending that process from outside since the process itself is inside an `:infinity` wait, and the plan says why a bounded attach from a task and a monitor on the attacher are mutually exclusive: the attaching process *is* the release handle. R-2. The class-25 clause said three surfaces are new; it is five, one per core change -- which is not a coincidence, since a core change no witness could read would be a change nothing proves. The five are tabulated with what creates and what reads each, and the sentence becomes "everything read outside those five exists today". R-3. The minimalism budget states the concurrent-attachment change as two halves with the reason: the first alone would leave core with no release path, supersession being the only one there is today. R-4. The two in-VM reads name the dispatcher's `attachments` map (event_dispatcher.ex:154, :823) instead of "core's own attachment registry". --- docs/plans/M5-technical.md | 70 ++++++++++++++++++++++++++++---------- 1 file changed, 52 insertions(+), 18 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8745fe973..8042c9a11 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1018,7 +1018,7 @@ leaked until the daemon restarts: | Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | | A **resume** crashing or timing out | **Held, then resolved by replay**: replayed under its original `command_id`, whose `disposition`/`control_entry` say whether the original call activated the session. The existence query cannot answer this — it says `present` either way | | A **create** crashing or timing out | **Held, then resolved by replay**: replayed under the same `command_id`, which returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | -| An **attach** crashing or timing out | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment, and core change 1 monitoring the attaching process. The daemon closes that connection, its process ends, and the dispatcher's `DOWN` handler drops the attachment. Nothing is observed, because nothing needs to be | +| An **attach whose connection process ends before it answers** | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment, and core change 1 monitoring the attaching process. The daemon closes that connection, its process ends, and the dispatcher's `DOWN` handler drops the attachment. Nothing is observed, because nothing needs to be | **That last row is not hypothetical, and the reason is a default nobody chose.** The daemon reaches core through `Loopex.Runtime`, whose @@ -1026,9 +1026,21 @@ chose.** The daemon reaches core through `Loopex.Runtime`, whose timeout (`runtime.ex:470`, `:478`). A create or resume that takes longer returns the daemon an error while core is still starting a coordinator — so "the call gave no answer" is an ordinary outcome of a slow root, not an -exotic one. Every daemon call that consumes a ceiling therefore carries an -explicit timeout rather than inheriting that default, and resolves its -reservation by the rule its own row names when the timeout is what it gets. +exotic one. Every daemon call that consumes a ceiling **and accepts one** +therefore carries an explicit timeout rather than inheriting that default, and +resolves its reservation by the rule its own row names when the timeout is +what it gets. + +**`Runtime.attach/3` accepts none and needs none**, which is why the qualifier +matters. Its signature takes a runtime, a session ID and options and no +timeout at all (`runtime.ex:198-210`), and inside it waits `:infinity` twice — +at the dispatcher and again at the install (`:538`, `:547`) — **precisely so a +caller timeout cannot revoke a mutation it cannot see**, which is what the +code says there in as many words: the dispatcher has already created the +attachment and the install is registering its routing, so a caller that gave +up would be neither revoking either mutation nor able to report truthfully +that the attach failed. The attach row below is written against that reality +rather than against a timeout the call does not have. **A call that gives the daemon no answer may still have started a coordinator or an attachment**, so releasing the reservation would let the ceiling be @@ -1062,7 +1074,16 @@ that process and drop its attachment on `DOWN`. So the reservation is keyed by the connection, and a connection whose `session.attach` never answered is closed by the daemon — the same path every connection close takes, whether the client went away or the daemon gave up on it — its process ends, and the -attachment is released by the monitor. The reservation is released with it. +attachment is released by the monitor. **"Gave up" here is the owner ending +that connection process from outside**, since the process itself is inside an +`:infinity` wait and cannot give up on its own; the `DOWN` is the release +either way, which is the point of keying the reservation to the process rather +than to the call. + +**And the attach must be made from that process**, not from a task the daemon +could bound: the attaching process *is* the release handle, so a bounded +attach and a monitor on the attacher are mutually exclusive. Choosing the +monitor is what makes an unanswered attach releasable at all. The reservation is released with it. Nothing new is called and nothing is observed; the release path is the one core change 1 adds, and it is named in the inventory rather than assumed. @@ -2676,13 +2697,21 @@ could not be checked.** Every witness here names the **surface** it reads, the **two answers** that must differ on it, and — where the surface is new — the **change that creates it**. A case asserting "core holds N" without saying where N is read is not a case anybody can write; nor is one whose difference -depends on a code path that does not exist. Three of this plan's surfaces are -new work rather than existing behaviour, and each is named where it is used: -the **dispatcher's release on `DOWN`** (core change 1), **`Control`'s -excluded-pid set** (core change 3), and **`quiesce/1`'s three lists and -`budget_ms`** (core change 4). Everything else is read from something that -exists today — the journal, a supervisor's children, a pid's liveness, a -socket's EOF, or the daemon's own `stderr`. +depends on a code path that does not exist. **Five** of this plan's surfaces +are new work rather than existing behaviour — one per core change, which is +not a coincidence: a core change that no witness could read would be a change +nothing proves. Each is named where it is used: + +| Surface | Created by | Read by | +| --- | --- | --- | +| The dispatcher's release on `DOWN` | Core change 1 | The concurrent-attachment cases and the attach no-answer case | +| The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | +| `Control`'s excluded-pid set | Core change 3 | The trace-exclusion cases | +| `quiesce/1`'s three lists and `budget_ms` | Core change 4 | The drain cases and the stop line | +| `disposition` and `control_entry` | Core change 5 | The create and resume no-answer cases | + +Everything read outside those five exists today — the journal, a supervisor's +children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. - **Idle shutdown.** A daemon with sessions activated and no work in flight receives `SIGTERM`, writes nothing further to `stdout`, closes every @@ -3001,8 +3030,8 @@ socket's EOF, or the daemon's own `stderr`. attachments receives two `session.attach` calls at once. On the wire the case asserts exactly one result and one refusal — two answers that plainly differ. The count is **in-VM**: core exposes no attachment count, so the - case reads core's own attachment registry in the same VM and asserts - **512**, not 513. Saying "proved by core holding 512" without saying where + case reads **the dispatcher's `attachments` map** (`event_dispatcher.ex:154`, + `:823`) in the same VM and asserts **512**, not 513. Saying "proved by core holding 512" without saying where that number is read would have been the same unobservable claim this round removed elsewhere. - **Every branch releases or converts its reservation, and the no-answer @@ -3027,8 +3056,9 @@ socket's EOF, or the daemon's own `stderr`. *Attach, no answer.* Two surfaces, and they differ in the two cases. On the wire, the client's connection is asserted **closed** — an EOF a test can observe — where a connection whose attach answered stays open. In-VM, the - dispatcher's attachment count is asserted to drop **after the connection - process exits**, and the daemon's reservation count to be back where it + dispatcher's `attachments` map (`event_dispatcher.ex:154`, `:823`), read + in-VM, is asserted to lose that entry **after the connection process + exits**, and the daemon's reservation count to be back where it started. The code path that produces that drop is core change 1's monitor, which the inventory names as new work; a core witness in `apps/loopex/test/concurrent_attachments_test.exs` proves the monitor @@ -3166,8 +3196,12 @@ unifies and why direct code is insufficient. One application, because a daemon is a host and a host is an application. One daemon owner process, one new public composition function — which unifies the two callers that need the edges assembled, `RuntimeOwner` and the daemon's owner, and which direct code cannot replace because the alternative is a -second copy of the whole wiring layer. One socket listener, one narrow -core concurrent-attachment change, **one trace-exclusion call, +second copy of the whole wiring layer. One socket listener, **one narrow core +concurrent-attachment change with two halves** — supersession stops removing +an attachment, and the dispatcher monitors the attaching process and removes +on its `DOWN` — because the first half alone would leave core with no release +path at all, supersession being the only one there is today. **One +trace-exclusion call, `Loopex.Trace.exclude_self(capability, functions: [mfa])`** — which unifies nothing and is not asked for by this milestone's features at all: it exists because accepted ADR 0030 already requires that a key-bearing call be excluded From e3016d8596f32513f385ed298fa229ca33fe7312 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 12:21:01 -0700 Subject: [PATCH 117/585] plan(M5): fix four prose slips the attach-release edits introduced The attach paragraph pointed at the row "below" when the row is above, carried a mangled correlative in its paraphrase of the runtime's comment, and ended the wrong paragraph with a dangling "it". The witness preamble ran into the note that follows it and restated its last sentence. Words only; no mechanism, number, owner, witness or code claim changes. --- docs/plans/M5-technical.md | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8042c9a11..40bbe21a5 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1038,8 +1038,8 @@ at the dispatcher and again at the install (`:538`, `:547`) — **precisely so a caller timeout cannot revoke a mutation it cannot see**, which is what the code says there in as many words: the dispatcher has already created the attachment and the install is registering its routing, so a caller that gave -up would be neither revoking either mutation nor able to report truthfully -that the attach failed. The attach row below is written against that reality +up would be revoking neither mutation, and could not report truthfully that +the attach failed. The attach row above is written against that reality rather than against a timeout the call does not have. **A call that gives the daemon no answer may still have started a coordinator @@ -1078,12 +1078,12 @@ attachment is released by the monitor. **"Gave up" here is the owner ending that connection process from outside**, since the process itself is inside an `:infinity` wait and cannot give up on its own; the `DOWN` is the release either way, which is the point of keying the reservation to the process rather -than to the call. +than to the call. The reservation is released with the connection. **And the attach must be made from that process**, not from a task the daemon could bound: the attaching process *is* the release handle, so a bounded attach and a monitor on the attacher are mutually exclusive. Choosing the -monitor is what makes an unanswered attach releasable at all. The reservation is released with it. +monitor is what makes an unanswered attach releasable at all. Nothing new is called and nothing is observed; the release path is the one core change 1 adds, and it is named in the inventory rather than assumed. @@ -2689,9 +2689,8 @@ next daemon removes before binding. **Witnesses.** Most run a real daemon operating-system process; a few read state no surface exposes and run **in-VM**, in the same VM as the daemon or -the runtime they are about. Each is labelled, because a case that says -"asserts core holds N" without saying where N is read is the defect class this -plan spent a round removing. +the runtime they are about. Each is labelled. + **A note on how these are written, added after a review found three that could not be checked.** Every witness here names the **surface** it reads, the **two answers** that must differ on it, and — where the surface is new — the From f8147e9be17fe3ea52823ce39ba719a643a7fe63 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 12:53:22 -0700 Subject: [PATCH 118/585] plan(M5): seven bounded phases and a synchronous admission cut B2. The stop bound could not be met as written. The drain budget is the largest cancellation backstop -- 22,001 ms at the smallest admitted grace (executor.ex:456-474, computed) -- fencing began after it, and a five-second teardown was expected to absorb a sequential stop of up to 512 lease owners plus Store calls that can each block 30 s (local.ex:65, :111). The contract is now seven phases, each bounded by a number that already exists: admission cut; abort admission at 30 s run concurrently across sessions, so the phase is one Store call long rather than N; cancellation at the derived backstop; fence at 30 s, concurrent; coordinator termination at the 5 s core already gives a coordinator (session_coordinator.ex:134-142); daemon teardown at 5 s; Store at 30 s. The operator maximum is their sum with the derived term named. One rule keeps a phase honest: no Store operation begins without at least its own timeout remaining, so a fence with four seconds left is not attempted. Phase 6 stops lease owners as a collective sweep -- all sent stop at once, one wait for every DOWN, forced kill at the phase end -- with the disposition stated, since 512 sequential stops inside five seconds was arithmetic nobody had done. B1. Stopping the listener stops new connections, not new commands: every existing connection process could still submit while quiesce snapshotted the session set, and `session.create` did not pass through the relay at all. The cut is now a synchronous call to the relay, whose scope extends to cover creates as well as ticketed mutations; it acknowledges only when admissions are closed and every ticket it holds has settled or been recorded, and the owner does nothing else until that returns. A command arriving after the cut is refused `daemon_stopping`, a new generation-2 code. --- docs/plans/M5-technical.md | 98 ++++++++++++++++++++++++++------------ 1 file changed, 68 insertions(+), 30 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 40bbe21a5..2aa327740 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1805,19 +1805,49 @@ between the owner's death and the monitor's `DOWN` being handled. In both routes the class is `owner_lost` on `stderr`, and it is the one class no linked component produces. -**Three clocks, and no component invents a fourth.** An earlier revision gave -every component "the composed cleanup grace" and gave the Store a floor over -it. That was wrong twice: a session's `cleanup_grace_ms` is an input to -*cancellation*, not a shutdown deadline, and a per-component budget makes the -worst-case stop the sum of the components rather than a bound anyone can -state. The contract is three clocks: - -| Clock | What it bounds | Where the number comes from | -| --- | --- | --- | -| **`g`**, each session's committed `cleanup_grace_ms` | The cancellation of that session's effects, and nothing else | The session's own composition; already used by `Loopex.Executor.cancellation_bounds/1` | -| **`budget_ms`**, the drain budget | The whole drain, across every session | Derived **by core, inside `quiesce/1`**, and **returned** in its result: `max` over the drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` (`apps/loopex/lib/loopex/executor.ex:456-474`, where `cli_backstop_ms` is `observe + reserve + terminal`, documented as "the sum a process-liveness backstop must cover"). The daemon does not compute it, because it does not hold the `g_i` | -| **`teardown_ms`, fixed at `5_000`** | **One absolute deadline covering every non-Store action after the drain** — the `daemon.stopping` writes, closing the connections, closing the listener, the lease owners, the relay, the runtime, the executor, the workspace lease, transfers, custody and the registry | A plan decision, and the rationale is that each of those is a bounded write or a stop of a process with no `terminate/2` to run: milliseconds apiece, so five seconds is a ceiling none of them should approach and an upper bound an operator can add up | -| **The Store phase** | The Store's stop alone | A **fixed 30 s**, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of `g` and of `teardown_ms` | +**Seven phases, each with a named bound, and the stop is their sum.** Earlier +revisions called this "three clocks" and then let two of them overlap: the +drain budget was the largest cancellation backstop — at the smallest admitted +grace that is already **22,001 ms** (`cancellation_bounds/1`, +`apps/loopex/lib/loopex/executor.ex:456-474`) — fencing began *after* it, and +the five-second teardown was expected to absorb a sequential stop of up to 512 +lease owners and a Store call that can itself block 30 s +(`apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111`). None of that +adds up. The contract is now one phase at a time, each bounded by a number +that already exists somewhere, and the operator maximum is the sum: + +| # | Phase | Bound | Where the number comes from | +| --- | --- | --- | --- | +| 1 | **Admission cut** | The relay's own call, bounded by the teardown budget below | A synchronous acknowledgement, not a wait for work | +| 2 | **Abort admission** | **30 s**, the Store's `@call_timeout` (`local.ex:65`) — **per phase, not per session**, because the sessions are admitted **concurrently** | One Store call each; running them at once makes the phase one call long rather than *N* | +| 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | +| 4 | **Fence** | **30 s**, the same Store call timeout, again **concurrent** across sessions | Each fence is one `advance_owner` transaction | +| 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`) | The value core already gives a coordinator to stop in | +| 6 | **Daemon teardown** | **5 s** | This plan's one chosen number, covering the notice, the closes, the lease owners, the relay and the edges | +| 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | + +> **Maximum graceful stop = 30 s + `budget_ms` + 30 s + 5 s + 5 s + 30 s**, plus +> the admission cut, which is an acknowledgement rather than a wait. + +**One rule keeps a phase from starting work it cannot finish.** *No Store +operation begins without at least its own timeout remaining in its phase.* A +fence with four seconds left on a thirty-second phase is not attempted; the +session is reported `fence: :not_needed` if the head already moved and +`:unknown` otherwise, and the daemon proceeds. Starting a 30 s call inside a +4 s remainder is how a bounded sequence becomes an unbounded one. + +**Phase 6 stops the lease owners as a collective sweep, not one at a time.** +Up to 512 of them exist, and stopping them in sequence inside five seconds was +arithmetic nobody did: the owner sends every lease owner its stop +**concurrently**, waits **once** for all of their `DOWN`s, and at the phase's +end kills whatever is left with `Process.exit(pid, :kill)`. The disposition is +stated: a lease owner killed this way loses nothing durable — it holds a lease +record, an epoch and an in-flight admission set, none of which outlives the +daemon — and the relay's tickets, which do matter, are held by the relay and +stopped after them. + +**`budget_ms` is still core's to derive and report**, for the reason below; +what changed is that it is one phase among seven rather than the whole drain. The budget is derived rather than chosen because the cancellation it waits on is already bounded by core: `cli_backstop_ms` is the number core itself says a @@ -1857,17 +1887,12 @@ stopped here only the transfers owner runs a `terminate/2` at all — so the budget is a ceiling for a set of actions that are each milliseconds. It is recorded in the limits table with that rationale. -**The deadline starts the instant `quiesce/1` returns**, and it covers -**every** non-Store action from that point: the stop records, the connection -closes, the listener close, and every stop from the lease owners through the -registry. An earlier revision's formula covered only the stops, which left the -notification and closure steps outside any bound at all. Every helper under it -is given `remaining(teardown_deadline)` and nothing else — no component has a -budget of its own to spend. - -**So the operator-facing bound is stated, once, and it adds up:** - -> **Maximum graceful stop = `budget_ms` + 5 s + 30 s.** +**Phase 6's deadline starts when phase 5 ends**, and it covers every +remaining non-Store action: the stop records, the connection closes, the +listener close, and every stop from the lease owners through the registry. +Every helper under it is given `remaining(teardown_deadline)` and nothing +else — no component has a budget of its own to spend — and the collective +sweep above is what makes 512 lease owners fit inside it. **`budget_ms` is not knowable from the daemon's flags alone**, and the operator page says so rather than implying a constant. The composed @@ -1929,12 +1954,25 @@ steps itself. They are the owner's code, not a supervisor's behaviour, which is what lets each one carry a reason and lets the teardown use one deadline the owner fixes. -1. **The listener stops accepting, and the daemon refuses new admissions.** - A new connection is refused rather than queued, and a command arriving on - an open connection is refused from that instant. Nothing is written to - clients yet and nothing is closed: the connections stay open across the - drain, because a client that is about to be told something true is better - served by being told it than by an early close. +1. **The listener stops accepting, and the relay closes admissions — a + synchronous cut, not a policy.** An earlier revision said "the daemon + refuses new admissions from that instant" and left the instant undefined: + stopping the listener stops *new connections*, while every existing + connection process is still free to submit, and `session.create` did not + even pass through the relay. Quiesce would then have been snapshotting a + set of sessions that could still grow underneath it. + + So the cut is a call. The owner calls the **relay** — whose scope this + extends to cover `session.create` as well as every ticketed mutation — and + the relay **acknowledges only when admissions are closed and every ticket + it holds has settled or been recorded**. Until that acknowledgement returns + the owner does nothing else; after it, no work can enter core through the + daemon at all. A command arriving on an open connection after the cut is + refused **`daemon_stopping`**, a generation-2 error code added for it. + + Nothing is written to clients yet and nothing is closed: the connections + stay open across the drain, because a client that is about to be told + something true is better served by being told it than by an early close. 2. **The runtime is quiesced within the budget core derives.** The owner calls core's `quiesce/1` — which takes no deadline, core owning the drain clock entirely — and waits for its answer, which names the sessions that From 8cf3032b4565c79adeda2d5309fd5f152a43c613 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:03:18 -0700 Subject: [PATCH 119/585] plan(M5): close the admission cut on the wire and in the bounds B1, second half. The cut existed in the shutdown sequence and nowhere else. `daemon_stopping` is now a generation-2 error code with its shape, its correlation, its place in the digest's ordered error list and its vector, and the instant it names is the relay's acknowledgement rather than the signal -- so the two witnesses differ on one surface, the connection's own reply stream. The relay's ticket set grows from eight to nine: `session.create` is ticketed too, taken by the connection process because a session that does not exist yet has no lease owner, because a cut that could not account for creates was a promise the daemon could not keep, and because the relay is then the process that owns a create's reservation when the client is gone. A create ticket blocks no grant, there being no earlier tenure to overtake. B2, second half. The phase contract reached only the lifecycle section. The operator obligation now names the sum an operator actually types -- `budget_ms` + 105 s, with the six fixed terms written out -- the limits table carries one row per phase instead of three clocks, Outcome 1 carries the cut's witnesses, and the two places that still stopped 512 lease owners "in sequence" say collective sweep. The seven phases and the six steps are two cuts through one stop, so the mapping between them is stated: phase 1 is step 1, phases 2 to 5 are inside `quiesce/1` and are core's to enforce, phase 6 covers steps 3 to 5, phase 7 is the Store. Phase 1 gains a real bound -- 5 s, and a relay that does not answer inside it is a relay the daemon has lost. --- ...tachment-residency-and-replay-technical.md | 40 +++++-- ...controller-lease-and-takeover-technical.md | 17 ++- docs/plans/M5-technical.md | 111 ++++++++++++------ docs/plans/M5.md | 26 ++-- 4 files changed, 139 insertions(+), 55 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 08fd63520..dfd24cb7f 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -270,6 +270,7 @@ errors answering one request: each carries that request's `request_id`, no | `control_pending` | `session.acquire_control` that waited out its deadline | nothing | | `control_capacity_reached` | any lease operation beyond the 512 concurrent-owner cap | nothing | | `session_dormant` | `session.attach` | nothing | +| `daemon_stopping` | any method arriving after the daemon's admission cut | nothing | | `session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate` | any method that validates existence first | nothing | | `activation_ceiling_reached` | `session.create`, `session.resume` | nothing | | `composition_mismatch` | `session.resume` on a session this composition cannot serve | nothing | @@ -332,7 +333,7 @@ limits — five inputs, and generation 2 changes **all five**: | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` and `daemon.notice` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 reuses for the connection ceiling | | **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 @@ -428,6 +429,24 @@ on any other connection are untouched, because an observer holds no lease and loses nothing. A client that sees it may acquire again; the next acquisition starts a fresh owner and mints a fresh epoch. +**`daemon_stopping`, the refusal after the admission cut.** An orderly stop +begins with a synchronous, acknowledged cut: the daemon's owner calls the +admission relay, the relay closes admissions and answers only once every +ticket it holds has settled or been recorded, and nothing enters core through +the daemon after that answer. A connection that is still open — and every +connection is, because the cut precedes the closes — may still send a frame. +It is answered with a **correlated** `daemon_stopping` carrying that request's +`request_id` and nothing else: no `event_cursor`, no session state, and it +closes nothing on its own. The connection is closed a moment later by step 3 +of the stop sequence, which is where a client is told the reason it is going +away; `daemon_stopping` answers the one request that arrived in between. + +The instant it names is the relay's acknowledgement, not the signal: a command +whose relay ticket was recorded **before** the acknowledgement settles or is +fenced under the drain, and one that arrives after it is refused. Those are +the two witnesses, and they must give different answers on the same surface — +the connection's own reply stream. + **`session_index_too_large` is not a wire code**, and an earlier revision listed it as one. It is a **startup** refusal: the daemon exits non-zero with that class before any socket exists, so no client can be holding a connection @@ -453,14 +472,17 @@ enters the digest's record-families input beside `daemon.stopping`. **Correlation, for the refusals above.** `control_not_held`, `control_pending`, `control_capacity_reached`, `control_held`, -`session_dormant` and the four existence-query refusals are ordinary -**correlated** errors: each answers one request and carries that request's -`request_id`, no `event_cursor` and no session state, and none closes -anything — the connection and every attachment on it are untouched. The two -uncorrelated cases in generation 2 are the ones named above, -`control_owner_lost` and the `daemon.stopping` and `daemon.notice` records, -and each states its own close behaviour where it is defined. Stating this once -is what lets the vectors be written without guessing. +`session_dormant`, `daemon_stopping` and the four existence-query refusals are +ordinary **correlated** errors: each answers one request and carries that +request's `request_id`, no `event_cursor` and no session state, and none +closes anything **by itself** — the connection and every attachment on it are +untouched by the refusal, and where the connection is nonetheless closed a +moment later it is the stop sequence or the detach rule below doing it, not +the error. The uncorrelated cases in generation 2 are the ones named above, +`control_owner_lost`, ADR 0023's `detached` as this pair's detach rule reuses +it, and the `daemon.stopping` and `daemon.notice` records, and each states its +own close behaviour where it is defined. Stating this once is what lets the +vectors be written without guessing. **The existence query's `unexpected` maps to `existence_indeterminate`.** Core answers one of five results; the daemon maps `store_unavailable` to the wire's diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index fe3be2629..c43f1fef2 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -79,11 +79,18 @@ flight, and core never sees the writer epoch at all. added on the maintainer's decision of 2026-09-20. Every **lease-authorized existing-session mutation** — the set this pair lists below, each carrying `writer_epoch` and admitted only from the recorded holder — is routed through -it, and nothing else is: reads are not ticketed, since a read grants nothing, -orders nothing, and a blocking read would otherwise hold a takeover for as -long as an observer sat on it. - -The lease owner **calls** the relay and waits for the acknowledgement before +it, and so is `session.create`, which carries no epoch and whose ticket the +connection process takes because no lease owner exists for a session that does +not exist yet. Nothing else is: reads are not ticketed, since a read grants +nothing, orders nothing, and a blocking read would otherwise hold a takeover +for as long as an observer sat on it. A create's ticket blocks no grant — there +is no earlier tenure for a successor to overtake — and it exists so that the +daemon's orderly stop can close admissions with an acknowledgement covering +**every** mutation in flight, which a relay that creates bypassed could not +give. The plan's companion owns that cut. + +The lease owner — or, for a create, the connection process — **calls** the +relay and waits for the acknowledgement before the core call is made, so no mutation exists that the relay has not recorded; the relay **monitors** every lease owner, so the BEAM's per-sender message ordering puts every ticket an owner sent ahead of that owner's `DOWN`; it diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 2aa327740..98e020e84 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -142,8 +142,8 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: new connections refused and new admissions refused from that instant, then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending` and `control_capacity_reached` — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and every ticket it holds has settled or been recorded — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to settle or to be fenced under the drain, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — and a `session.create` sent after the cut refused the same way, which is the case that would fail if creates bypassed the relay; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -291,10 +291,15 @@ provider configuration. because both are facts an operator cannot derive from the software and a reviewer can check against this sentence at closure. -- **`docs/operator/daemon.md` must state the maximum graceful stop**: the - drain budget core derives, plus the fixed five-second budget covering every - non-Store action after it, plus the fixed 30-second Store phase — and, with - it, that the drain budget is **not** read off the daemon's own +- **`docs/operator/daemon.md` must state the maximum graceful stop as the sum + of the seven phase bounds**, in the form the lifecycle section fixes: + **`budget_ms` + 105 s**, being 5 s for the admission cut, 30 s for abort + admission, `budget_ms` for cancellation, 30 s for the fence, 5 s for + coordinator termination, 5 s for daemon teardown and 30 s for the Store — + with the six constants written out beside the one derived term, so an + operator setting a `TimeoutStopSec` adds up numbers rather than trusting a + total. It must say that six of the seven are fixed and + that the drain term alone is **not** read off the daemon's own `--cleanup-grace-ms`, because each session drains under the grace it committed and a root may carry sessions composed earlier, so the page must point an operator at the figure the daemon **reports in its stop line** @@ -1330,14 +1335,25 @@ So one fixed, daemon-owned process holds what the lease owners cannot — and three details of it are the difference between closing the window and looking as though it does: -- **Tickets cover exactly the lease-authorized existing-session mutations, and - nothing else.** ADR 0033 lists them: `session.resume`, `session.prompt`, +- **Tickets cover every core call that mutates, and nothing else — nine of + them.** Eight are the lease-authorized existing-session mutations ADR 0033 + lists: `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, `session.respond_interaction`, `session.admit_resources` and - `session.activate_skill` — the **eight** calls that carry `writer_epoch` and + `session.activate_skill` — the calls that carry `writer_epoch` and are admitted only from the recorded holder - (`0033-…-technical.md:188-191`). **`session.release_control` is not among - them**, and the distinction is worth one line: it carries `writer_epoch` and + (`0033-…-technical.md:188-191`). The ninth is **`session.create`**, which + carries no epoch and has no lease owner, because the session it makes does + not exist yet; its ticket is taken by the **connection process** rather than + by a lease owner, and it takes no part in the per-session grant-blocking + rule below, there being no earlier tenure for a successor to overtake. It is + ticketed for the two things a ticket is otherwise for: so that the admission + cut can say it has accounted for every mutation in flight, and so that the + relay — not the connection, which may be gone — owns the resolution of the + activation slot that create reserved. An earlier revision left creates + outside the relay entirely, which made the cut a promise the daemon could + not keep. **`session.release_control` is not among the nine**, and the + distinction is worth one line: it carries `writer_epoch` and is lease-authorized, but it starts no core call, so there is nothing for a ticket to account for. **Reads are not ticketed either.** An earlier revision said "every core call the daemon makes", which would have included @@ -1346,7 +1362,8 @@ as though it does: would have blocked every takeover for that session for as long as it sat there. A read grants nothing, orders nothing and cannot overtake a mutation. - **The ticket is recorded synchronously, before the call exists.** The lease - owner **calls** the relay and waits for the acknowledgement, and only then + owner — or, for a create, the connection process — **calls** the relay and + waits for the acknowledgement, and only then does the relay spawn the monitored task that performs the core call. A cast would have left the window open at the other end: an owner could pass its holder check, send its ticket and die before the message arrived, and a @@ -1379,7 +1396,15 @@ as though it does: call does. - **A replacement owner's first grant for a session blocks until that session's outstanding tickets have settled.** Not the daemon's admissions - generally — just that session's, which is why the ticket names one. + generally — just that session's, which is why the ticket names one. A create + ticket names no session and blocks no grant. +- **The admission cut is the relay's, because the relay is the only process + that can answer for all nine.** The owner calls it once at the start of an + orderly stop; it stops admitting, and it answers only when every ticket it + holds has either settled or been recorded as outstanding for the drain to + fence. That answer is what makes "after this instant nothing enters core + through the daemon" a fact rather than a policy, and it is why every + mutating call goes through this one process. That is the ordering claim ADR 0033's owner-loss section now rests on: a successor's first call cannot be issued while an older call for the same @@ -1433,12 +1458,12 @@ the registry — and then **the Store, last of all**, out of reverse order. The lease owners go before the relay because the relay is what holds their tickets, and stopping it first would discard a ticket an owner could still be waiting on. They are stopped -**in sequence, not concurrently**, against the shared teardown deadline rather -than a budget each: every one of them is a process with no `terminate/2` and -nothing to release, so the sequence costs no measurable time, while a -concurrent stop would need a second wait rule and a way to attribute one -timeout among several hundred pids. Sequence is the smaller mechanism for the -same result. The +as **one collective sweep, not one at a time**, against phase 6's deadline: +up to 512 of them exist, and 512 sequential stops inside a five-second phase +is arithmetic that does not work. The sweep — every stop sent at once, one +wait for all of the exits, a kill for whatever is left at the phase's end — +and the disposition of a lease owner killed that way are written out with +phase 6 below. The Store is moved to the end because its `terminate/2` releases the writer marker, and the marker must outlive every operation the owner can end; custody and registry hold nothing durable, so stopping them before it costs @@ -1818,7 +1843,7 @@ that already exists somewhere, and the operator maximum is the sum: | # | Phase | Bound | Where the number comes from | | --- | --- | --- | --- | -| 1 | **Admission cut** | The relay's own call, bounded by the teardown budget below | A synchronous acknowledgement, not a wait for work | +| 1 | **Admission cut** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement from a process with no work of its own to finish; a relay that does not answer inside it is a relay the daemon has lost, so the stop becomes the `relay_lost` fail-stop rather than waiting longer | | 2 | **Abort admission** | **30 s**, the Store's `@call_timeout` (`local.ex:65`) — **per phase, not per session**, because the sessions are admitted **concurrently** | One Store call each; running them at once makes the phase one call long rather than *N* | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Fence** | **30 s**, the same Store call timeout, again **concurrent** across sessions | Each fence is one `advance_owner` transaction | @@ -1826,8 +1851,22 @@ that already exists somewhere, and the operator maximum is the sum: | 6 | **Daemon teardown** | **5 s** | This plan's one chosen number, covering the notice, the closes, the lease owners, the relay and the edges | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 30 s + `budget_ms` + 30 s + 5 s + 5 s + 30 s**, plus -> the admission cut, which is an acknowledgement rather than a wait. +> **Maximum graceful stop = 5 s + 30 s + `budget_ms` + 30 s + 5 s + 5 s + 30 s +> = `budget_ms` + 105 s**, and `budget_ms` is the one term an operator cannot +> compute in advance. + +**The seven phases and the six steps are two cuts through the same stop, and +the mapping is stated rather than left to be inferred.** The numbered sequence +below is what the daemon's owner *does*; the phases are what each part of it +is *bounded by*. Phase 1 is step 1's call to the relay. **Phases 2 to 5 are +inside `quiesce/1`** — they are core's to enforce, because core owns the +admission, the cancellation, the fence and the coordinator, and the daemon +passes no deadline in — and together they are step 2. Of the four, only +phase 3's actual value is returned, as `budget_ms`; the other three are fixed +numbers an operator adds to it. Phase 6 begins the instant `quiesce/1` returns +and covers steps 3, 4, 5 and the non-Store part of step 6. Phase 7 is the +Store stop at the end of step 6. Nothing is bounded twice and nothing is +bounded by nobody. **One rule keeps a phase from starting work it cannot finish.** *No Store operation begins without at least its own timeout remaining in its phase.* A @@ -1877,7 +1916,8 @@ is a ceiling that matters only when the filesystem is wedged, which is exactly when killing the Store mid-release is worst. The same fixed phase applies in the failed-start reverse cleanup, for the same reason. -**`teardown_ms` is `5_000`, and it is a number rather than a formula.** An +**`teardown_ms` is phase 6's bound, `5_000`, and it is a number rather than a +formula.** An earlier revision named the clock and never gave it a value, which left the operator bound unstatable and every "what remains" reference undefined. Five seconds is chosen, not derived: nothing under this deadline waits on a @@ -1988,8 +2028,8 @@ the owner fixes. socket is closed with them. **Nothing unlinks the pathname**, on this path or any other: the next daemon to prove it holds the marker removes it before binding, which is the only safe moment there is. -4. **Every lease owner stops, then the admission relay**, in sequence, - against the shared `teardown_ms` deadline. Every lease vanishes with the +4. **Every lease owner stops as one sweep, then the admission relay**, inside + phase 6's deadline. Every lease vanishes with the owners; the relay goes after them because it is what holds their admission tickets, and stopping it first would discard a ticket a lease owner could still be waiting on. Nothing durable is involved, and no client is left @@ -2086,11 +2126,11 @@ the owner fixes. of components. An earlier revision gave each component its own grace, which made the worst-case stop a sum nobody had written down. - **The Store's phase is separate and fixed**, for the reason the three - clocks give: it is the one stop whose `terminate/2` releases a durable - exclusion, and its length has nothing to do with any session's cancellation - grace. It begins when the teardown deadline is done with, runs for at most - 30 s, and usually finishes in milliseconds. + **The Store's phase is separate and fixed** — phase 7, and the reason it is + its own phase is that it is the one stop whose `terminate/2` releases a + durable exclusion, and its length has nothing to do with any session's + cancellation grace. It begins when phase 6's deadline is done with, runs + for at most 30 s, and usually finishes in milliseconds. **The residual is stated.** A Store that has not released within its 30 s is killed, and the marker survives. That is the same stale marker ADR @@ -3324,9 +3364,14 @@ line; M5 introduces none of its own. | Socket path bound, over `/daemon/daemon.sock` | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | -| Drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | -| Non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | -| Store shutdown phase | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | +| Phase 1, the admission cut | **5_000 ms**, the teardown number reused; an unanswered cut becomes the `relay_lost` fail-stop | This plan | +| Phase 2, abort admission | a fixed **30 s**, the Store's own `@call_timeout`; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65` | +| Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | +| Phase 4, the fence | a fixed **30 s**, the same Store call timeout, concurrent across sessions | Core, against the Store's existing bound | +| Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | +| Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | +| Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | +| Maximum graceful stop | `budget_ms` + **105 s**, the sum of the six fixed phases above | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 3b0b78fbe..b32c4e109 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -62,7 +62,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that refuses new work, **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — so a command whose ticket the relay recorded before the cut settles or is fenced under the drain, and one arriving after it is refused `daemon_stopping` — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -366,9 +366,11 @@ offline `loopex sessions`, `run` and `resume` are unchanged, and each live form is a separate explicit `--daemon` form of them. A daemon ends in one of two ways and the plan keeps them apart, because the -code does. **A daemon-initiated stop** is a drain and then a teardown: refuse -new connections and new admissions; **quiesce the runtime within the composed -cleanup grace**; attempt one best-effort stop record per open connection and +code does. **A daemon-initiated stop** is a drain and then a teardown: stop +the listener and **close admissions with one synchronous, acknowledged cut**, +after which nothing can enter core through the daemon and a command arriving +on a connection that is still open is refused `daemon_stopping`; **quiesce the +runtime within the budget core derives**; attempt one best-effort stop record per open connection and close it; close the listener and **leave the socket pathname**, which no exit path removes; stop the lease owners and then the runtime, which ends crash-equivalently whatever the drain did not settle; stop the remaining edges; and stop the Store last, which is @@ -402,10 +404,18 @@ the second loop this milestone forbids, and it could not admit a durable command on its own authority at all. **A graceful stop has a stated maximum**, because an operator configuring a -service manager needs one: the drain budget **core derives and reports**, plus -**five seconds** for every non-Store action after it — the stop records, the -closes, and every stop but the Store's — plus a fixed **thirty-second** Store -phase. The drain term is core's because each session drains under the grace it +service manager needs one, and it is the **sum of seven bounded phases** rather +than one clock that has to cover everything: five seconds for the admission +cut, thirty for admitting every session's abort, the drain budget **core +derives and reports** for the cancellation, thirty for the fence, five for +terminating the coordinators that did not settle, five for every non-Store +action after the drain — the stop records, the closes, the lease owners and +the edges — and thirty for the Store stop that releases the marker. Six of the +seven are fixed, so the maximum is **`budget_ms` plus 105 seconds**. Every one +of the six comes from a number that already exists — the Store's own call +timeout, the coordinator's own shutdown value — rather than from a figure this +plan invented, and no phase begins a Store call without that call's own +timeout still left in it. The drain term is core's because each session drains under the grace it committed, which a daemon reading its own flag would not know for a session composed earlier. A service manager that kills the daemon sooner turns the stop into a forced From 475ff0fe51b7b9af303b9d1f8cd8441e68438a2c Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:05:12 -0700 Subject: [PATCH 120/585] plan(M5): derive the fence from durable state and report what it did B3. The fence was neither result-total nor restart-recoverable. It handled `commit`, `stale_owner_epoch` and `commit_unknown`. The adapter's `succession_refusal/3` has a fourth answer -- `stale_journal_version`, when a same-epoch commit wins between the head read and the fence's linearization (`state.ex:450-463`, reached from `linearize/3` at `:241-254`) -- which is exactly the race a fence is for and which the old table would have read as an unexplained error. Both stale results now mean one thing: the head moved. Quiesce rereads it, recomputes from it, and attempts once more; it never repeats a transaction the store has already refused. The `tx_id` derived from a random `drain_id` held only in the daemon's memory, so a `commit_unknown` fence plus a death left a preallocated ID no successor could reconstruct -- against the restart-safe unknown-commit rule at `vision-technical.md:710-715`. It now derives from `(session_id, expected_owner_epoch, expected_journal_version)` through the `owner_identity/3` discipline the coordinator already uses, so a successor rereads the head, recomputes the id and resolves it with `Store.transaction_status/4` (`store.ex:1026-1048`, closed set at `:293-297`). `drain_id` stays as a report label. A journaled drain record would have made this trivial and is a persistent-schema decision; it is recorded as declined. The fence's outcome was unobservable: three outcomes described, none returned. `quiesce/1` now answers `drain_id` and a per-session `fences` map of `:committed | :superseded | :unknown | :not_needed`. And phase two no longer releases cleanup for a session whose abort admission failed or is ambiguous -- it is fenced or left fenced, because cancelling work no command admitted is the one thing a drain must not do. --- docs/plans/M5-technical.md | 159 ++++++++++++++++++++++++++----------- docs/plans/M5.md | 9 ++- 2 files changed, 122 insertions(+), 46 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 98e020e84..4214b725d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -142,7 +142,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and every ticket it holds has settled or been recorded — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to settle or to be fenced under the drain, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — and a `session.create` sent after the cut refused the same way, which is the case that would fail if creates bypassed the relay; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and every ticket it holds has settled or been recorded — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to settle or to be fenced under the drain, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — and a `session.create` sent after the cut refused the same way, which is the case that would fail if creates bypassed the relay; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -340,7 +340,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale classifies the session from the journal`; `a fence answering commit_unknown is retried under the same derived tx_id and reported unsettled with fence: :unknown`; `every fence in one drain derives its id from the same drain_id` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | @@ -2197,11 +2197,13 @@ Loopex.Runtime.quiesce(runtime) :: settled: [session_id], unsettled: [session_id], absent: [session_id], - budget_ms: non_neg_integer() + budget_ms: non_neg_integer(), + drain_id: binary(), + fences: %{session_id => :committed | :superseded | :unknown | :not_needed} }} ``` -**One argument, four keys, and no deadline crosses the boundary.** An earlier +**One argument, six keys, and no deadline crosses the boundary.** An earlier revision passed the daemon's teardown deadline in, which contradicted the rule two paragraphs later that the teardown clock starts when `quiesce/1` *returns*: a deadline cannot both bound the drain and begin after it. It takes @@ -2211,10 +2213,17 @@ comes back. A long derived budget is not a hazard the argument would have fixed either — it is what the operator bound above already reports, and what a service manager's own timeout is set against. -Of the four keys, two answer questions the daemon cannot ask. `absent` names +Of the six keys, four answer questions the daemon cannot ask. `absent` names the sessions `Control` still held as active whose coordinator was already gone, which is neither settled nor unsettled and must not be counted as -either. `budget_ms` is the drain budget core derived and used. +either. `budget_ms` is the drain budget core derived and used. `drain_id` is +the label this drain reports, and `fences` is what the fence below actually +did for each session it touched — `:committed` where the epoch moved, +`:superseded` where an older transaction won the race first, `:unknown` where +the Store could not say, and `:not_needed` where the head had already moved +under the session's own settled work. **Without `fences` a fence's failure is +a thing no caller can observe**, which is the defect an earlier revision +carried: it described three outcomes and returned none of them. **Three parts, in order, and the first two are one thing split in half.** @@ -2368,32 +2377,46 @@ either. `budget_ms` is the drain budget core derived and used. | --- | --- | | `session_id` | The session being fenced | | `mutation_domain` | The ownership domain, as every owner transaction uses | - | `tx_id` | **Derived, not random**, by the discipline the coordinator already uses: `owner_identity/3` hashes a namespace, a succession identity and an attempt into a stable ID (`session_coordinator.ex:1346`, `:1490-1498`). Quiesce derives its own from **`(drain_id, session_id)`** — see below | + | `tx_id` | **Derived from durable state, not from anything in memory**, by the discipline the coordinator already uses: `owner_identity/3` hashes a namespace, a succession identity and an attempt into a stable ID (`session_coordinator.ex:1346`, `:1490-1498`). Quiesce derives its own from **`("drain_fence", session_id, expected_owner_epoch, expected_journal_version)`** — every input read from the head it just read | | `expected_owner_epoch`, `expected_journal_version` | Read **fresh** from `Store.ownership_head/3`, exactly as the coordinator reads them (`session_coordinator.ex:1337-1343`), so the fence binds the state it is actually fencing | | `proposed_owner_incarnation_id` | A fresh incarnation, in the same form the coordinator mints (`fresh_incarnation/2`, `:1500`) | - **`drain_id` is one identity per `quiesce/1` call, and it has to be, because - the abort's `command_id` is not available for every fenced session.** An - earlier revision derived the fence's `tx_id` from that abort — which works - for a session that was drained and fails for an `absent` one, where no - abort is admitted at all. So core mints **one** `drain_id` when the call - begins, with the generator it already uses for identifiers of its own + **The `tx_id` derives from durable state, and an earlier revision derived it + from a random number held only in memory.** That revision minted one + `drain_id` per call and hashed `(drain_id, session_id)`. It reads well and + it breaks the one rule this fence exists under: a `commit_unknown` fence + whose deriving process then dies leaves a preallocated ID **no successor can + reconstruct**, because the only copy of `drain_id` was in a VM that is gone. + The founding rule is that a preallocated ID be recoverable *from the owning + command or operation identity* and that resolution be restart-safe + (`vision-technical.md:710-715`), and a value in RAM is neither. + + So the identity is the head itself. A successor — the next daemon, or the + next activation of that session — **rereads `ownership_head/3`, recomputes + the same `tx_id` from `(session_id, owner_epoch, journal_version)`, and asks + `Store.transaction_status/4`** (`apps/loopex/lib/loopex/store.ex:1026-1048`, + the adapter's own at `local.ex:118-122`), whose closed result set — + `{:terminal, :committed}`, `{:terminal, {:not_committed, reason}}`, + `:absent`, `:unavailable` (`store.ex:293-297`) — is exactly the resolution + this needs. Two of them end it: committed means the epoch moved and the + fence held; not-committed or absent means it did not and the successor's own + ordinary owner advance supersedes the state anyway. `:unavailable` leaves + the domain fenced, which is what the founding rule already requires of any + unresolved unknown. + + **`drain_id` survives as a report label and nothing more.** Core still mints + one per call, with the generator it already uses for identifiers of its own (`:crypto.strong_rand_bytes(16)` rendered base16, - `session_directory.ex:545-548`), and every fence in that drain derives its - `tx_id` from `(drain_id, session_id)`. One identity, every session, drained - or absent. - - **What makes that recoverable, which is the property the durability rule - actually asks for.** The rule is that a preallocated ID be *recoverable - from the owning command or operation identity* — not that the identity - itself be durable. Here the owning operation is one drain, and two things - make its fences recoverable without journaling anything new: the derivation - is total, so given `drain_id` every fence ID in that drain can be - recomputed; and `drain_id` is **reported** on the daemon's stop line beside - the budget, so an operator reconciling a root has the one value the - derivation needs. Nothing about the drain is written to the journal for its - own sake — the fence transactions are the durable record, and each carries - its own derived ID. + `session_directory.ex:545-548`), and **returns** it so the stop line and the + evidence page can name one drain. No fence ID derives from it, so losing it + costs a label and no recovery. + + **A journaled drain record was the alternative and was not taken.** Writing + the drain's identity into the journal would make recovery trivial and would + also be a change to a durable record — a persistent-schema decision, which + is the maintainer's and not a thing to take in passing when a derivation + from state that is already durable answers the same question. It is recorded + here as the option available and declined. **The proposed incarnation is a fence marker, not an owner**, and nothing inherits it. The next activation of that session builds its own candidate @@ -2404,22 +2427,50 @@ either. `budget_ms` is the drain budget core derived and used. activation supersedes. Fencing therefore costs the next activation one ordinary epoch step and nothing else. - That turns an unanswerable question into a decided one, and the decision - has exactly three outcomes — an earlier revision claimed only the first - two and overstated what the mechanism gives: - - | Outcome | What it means | How the session is reported | - | --- | --- | --- | - | The fence **commits** | The epoch has moved; any older `session_commit` linearized afterwards is refused `:stale_owner_epoch` | `unsettled`, fenced | - | The fence is **refused `:stale_owner_epoch`** | The old transaction linearized **first** and committed. The fence lost the race, which means there is nothing left to fence: the session's durable state already includes that commit | Classified **from the journal**, as whatever that commit made it — settled by its own terminal if it carried one. It is not reported as fenced, because it was not | - | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | Retried with the **same derived `tx_id`**, which is idempotent by construction, until the drain deadline; if it is still unknown then, the session is reported `unsettled` with `fence: :unknown` | + That turns an unanswerable question into a decided one, and the table is + **total over what the adapter can answer** rather than over the three + outcomes an earlier revision imagined. A fence is an `advance_owner`, so + the adapter's `succession_refusal/3` governs it, and that function has + **two** stale results, not one: `:stale_owner_epoch` and + `:stale_journal_version`, in that order + (`apps/loopex_store_local/lib/loopex/store/local/state.ex:450-463`, reached + from `linearize/3` at `:241-254`). The second is the case where a + **same-epoch** commit linearized between the head read and the fence's own + linearization — exactly the race the fence exists for — and a design that + handled only the first would have read it as an unexplained error. + + | Outcome | What it means | `fences[session_id]` | How the session is reported | + | --- | --- | --- | --- | + | The fence **commits** | The epoch has moved; any older `session_commit` linearized afterwards is refused `:stale_owner_epoch` (`state.ex:548-551`) | `:committed` | `unsettled`, fenced | + | The fence is refused **`:stale_owner_epoch`** or **`:stale_journal_version`** | Another transaction linearized **first**. The fence lost the race on the epoch or on the version, which in both cases means the state it read is no longer the state there is | `:superseded` | Quiesce **rereads the head and recomputes the id from it**; if the session is still unsettled it makes **one new attempt** under the new head's identity, and classifies **from the journal** if that attempt is superseded too. It is not reported as fenced, because it was not | + | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | `:unknown` | Resolved with `Store.transaction_status/4` under the **same derived `tx_id`**, which is idempotent by construction, until the phase's bound; still unknown at the bound leaves the session `unsettled` with `fences[session_id] == :unknown`, and the domain fenced | + | **No fence is attempted** | The head had already moved under the session's own settled work, or the phase had less than a Store call timeout left in it | `:not_needed` | As its own work left it | + + **A retry is never a blind repeat of a refused attempt.** The two stale + results say the head moved, so retrying the same transaction would refuse + identically forever; the recovery is to read durable state again and build a + new attempt from it, which is what the coordinator's own + `discover_and_advance_owner/1` already does on the same refusals. A + `commit_unknown` is the opposite case: the transaction may have linearized, + so it is **resolved**, never re-proposed under a new identity. So the claim the plan makes is the one the mechanism supports: when - `quiesce/1` returns, every session it reports as fenced has had its epoch - moved, and every session it reports otherwise is classified from what the + `quiesce/1` returns, every session whose `fences` entry is `:committed` has + had its epoch moved, and every other session is classified from what the journal actually holds. What it does **not** claim is that no transaction anywhere can still commit — a fence that is itself `commit_unknown` is - precisely the case where the daemon says so rather than pretending. + precisely the case where the daemon says so rather than pretending, and it + says so in a key a caller can read. + + **Phase two never releases a session whose admission it cannot account + for.** A session whose phase-one abort admission **failed or is ambiguous** + — a refusal that is not `rejected_no_active_run`, or a `commit_unknown` on + the admission itself — has no cleanup released for it at all. It is fenced + like an unsettled session, or, where the fence too is unknown, left fenced + and reported `unsettled` with `fences[session_id] == :unknown`. Releasing a + cancellation for a session whose abort may or may not be in the journal is + the one thing a drain must not do, because it would cancel work no command + admitted. **The classification quiesce returns has three lists, not two**, because `Control` can hold an entry whose coordinator is already dead: its `DOWN` @@ -2784,7 +2835,7 @@ nothing proves. Each is named where it is used: | The dispatcher's release on `DOWN` | Core change 1 | The concurrent-attachment cases and the attach no-answer case | | The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | | `Control`'s excluded-pid set | Core change 3 | The trace-exclusion cases | -| `quiesce/1`'s three lists and `budget_ms` | Core change 4 | The drain cases and the stop line | +| `quiesce/1`'s three lists, `budget_ms`, `drain_id` and the per-session `fences` map | Core change 4 | The drain cases, the fence cases and the stop line | | `disposition` and `control_entry` | Core change 5 | The create and resume no-answer cases | Everything read outside those five exists today — the journal, a supervisor's @@ -2828,13 +2879,31 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. Quiesce then runs its deadline path: it terminates the coordinator, waits for the `DOWN`, and commits the `advance_owner` fence for that session. The paused transaction is released. The case asserts it is **refused - `:stale_owner_epoch`**, that the journal contains no terminal for it, and + `:stale_owner_epoch`**, that `fences[session_id]` is **`:committed`**, that + the journal contains no terminal for it, and that the daemon's `unsettled` report was therefore true when it was read. A variant releases the paused transaction **before** the fence commits and - asserts the other half: it commits, it is observed, and the session's - durable state includes it. Both outcomes are decided; neither is a race the - plan has to argue about. + asserts the other half: it commits, it is observed, the session's + durable state includes it, and the fence that then loses the race is + reported **`:superseded`** rather than as an error. Both outcomes are + decided; neither is a race the plan has to argue about. + + A third variant is the one the result-totality repair added: the paused + transaction is released so that it commits **under the same epoch** the + fence read, so the fence meets **`:stale_journal_version`** rather than + `:stale_owner_epoch`. The case asserts the same `:superseded` disposition + and that the drain does not treat it as an unexplained failure — the + assertion a design handling only the epoch refusal would fail. + + A fourth proves the recovery property, and it is the case the memory-held + `drain_id` could not have passed: the fence is made to answer + `commit_unknown`, the whole daemon is **killed** before it can resolve it, + and a **second process** reads the head, recomputes the `tx_id` from + `(session_id, owner_epoch, journal_version)` alone and resolves it with + `Store.transaction_status/4`. The two answers that must differ are that + status for a fence that did linearize and for one that did not; neither is + reachable from anything the dead daemon held. - **The drain is globally durable-first, not per session.** Two sessions are active, each with a cancellable effect. The case asserts that **both** aborts are committed to the journal **before either** cleanup begins — diff --git a/docs/plans/M5.md b/docs/plans/M5.md index b32c4e109..27e46b237 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -394,7 +394,14 @@ cancellation sequence a coordinator already runs for an abort, under the bounds core already derives from that session's committed cleanup grace. And at the deadline it **terminates every coordinator that has not settled and then commits a Store-linearized owner-epoch fence for it**, so an older transaction still in flight either wins before the fence and is observed or -loses after it and is refused as stale. Terminating the coordinator alone +loses after it and is refused as stale. **That fence's identity is derived +from the session's own durable head**, not from anything the daemon holds in +memory, so a fence the Store could not resolve is resolvable by whatever +starts next: it rereads the head, recomputes the same identity and asks the +Store what became of it. And the answer says, per session, what the fence +actually did — committed, superseded by a transaction that won the race, +unknown, or not needed — because a fence whose failure no caller can observe +is not a fence anybody can rely on. Terminating the coordinator alone would not have done it: a transaction already delivered to the Store completes whether or not the process that sent it is still alive. It belongs in core because core owns coordinator lifetime, cancellation and admission; a From 023ee98986b59c5fc7bd252e003f024d9a3162e0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:05:58 -0700 Subject: [PATCH 121/585] plan(M5): move daemon startup out of init so the monitor can see it B4. `GenServer.start/3` returns only once `init/1` has answered, so the command process's monitor -- the whole of the `owner_lost` route -- could not observe an owner that died while taking the marker, binding the socket or printing readiness. Every acquisition sat inside the one window the monitor does not cover, and the caller's only account of it would have been an `{:error, reason}` that says nothing about what was already acquired. `init/1` now acquires nothing and returns `{:ok, state, {:continue, :start}}`; the seven steps run in `handle_continue/2`. That alone is a race, because the owner is runnable the instant `init/1` returns and a scheduler may run its continue before the caller's next line, so the continue waits for a `:go` the command process sends **after** `Process.monitor/1`. The message is the happens-before: the owner cannot begin until it exists, and it does not exist until the monitor does. A `:go` that never comes ends the owner through reverse cleanup with nothing acquired. Witnesses straddle the marker -- the owner killed before acquiring it and after -- plus one that delays `:go` and asserts the marker is not taken until it is sent, which is the assertion that separates a proved ordering from a usual one. The rejected inversion, an owner monitoring its command process, is recorded with its three faults. --- docs/plans/M5-technical.md | 59 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 57 insertions(+), 2 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 4214b725d..ca6406980 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1202,7 +1202,7 @@ readiness *after* a stop it has already been told about, or after a component it depends on has already died — and then read both and shut down, having announced itself ready in between. -Three rules, each narrow: +Four rules, each narrow: - **The owner is started unlinked and monitored.** The escript command process calls **`GenServer.start/3`, not `start_link/3`**, and monitors the owner @@ -1214,6 +1214,47 @@ Three rules, each narrow: `DOWN`, and gives the operating system an exit status — which is the whole of its job. The inventory row says unlinked-and-monitored, and now the design does too. +- **Startup does not run in `init/1`, because a monitor taken after + `GenServer.start/3` returns cannot see a death inside it.** That call + returns only once `init/1` has answered (it waits for the started process's + acknowledgement), so an owner that took the marker, bound the socket and + then died *in `init/1`* would leave the command process with no owner to + monitor and a `{:error, reason}` that says nothing about what was acquired + before the failure. Every acquisition would sit inside the one window the + monitor cannot cover. + + So `init/1` acquires **nothing**. It sets `trap_exit`, builds the state from + the already-validated inputs, and returns + `{:ok, state, {:continue, :start}}`; the seven steps run in + `handle_continue(:start, state)`. That is enough to make `GenServer.start/3` + return before the first step, and the ordering is then explicit rather than + incidental: + + | # | Who | What | + | --- | --- | --- | + | 1 | Command process | `GenServer.start(Owner, args)` | + | 2 | Owner | `init/1` returns `{:ok, state, {:continue, :start}}`, having acquired nothing | + | 3 | Command process | `Process.monitor(owner)` | + | 4 | Command process | sends the owner `:go` | + | 5 | Owner | `handle_continue/2` **waits for `:go`** before step 1 of the startup sequence, then runs the seven steps | + + **Step 5's wait is what makes the monitor provably installed**, and it is + why the continue does not simply begin. Without it the ordering would rest + on the command process winning a race it has no reason to win: the owner is + runnable the instant `init/1` returns, and a scheduler is free to run its + continue before the caller's next line. The `:go` message turns a hope about + scheduling into a happens-before: the owner cannot pass step 5 until a + message exists, and the message does not exist until the monitor does. The + wait is bounded by the same phase-6 number every other wait uses, and a + `:go` that never arrives — a command process that died between steps 2 and + 4 — ends the owner through the reverse cleanup with nothing acquired, which + is correct, because there is nobody left to report a daemon to. + + The alternative was to keep the sequence in `init/1` and have the owner + monitor the *command process* instead. It is rejected: it inverts the + reporting direction, gives the operating system no exit status when the + owner is the thing that dies, and still leaves the `{:error, reason}` return + as the only account of an acquisition that already happened. - **The owner drains and checks before every acquisition it performs itself.** Before taking the marker, before calling the composition function, before binding the socket and before printing the readiness line, the owner reads @@ -3038,6 +3079,20 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. the command process's monitor doing it. A second case kills the owner and *then* sends `SIGTERM`, asserting the same class by whichever route wins, so the two cannot both fail silently. + + **Two more cases straddle the marker, and they are what the `{:continue, + :start}` ordering exists for.** The owner is killed **before** it acquires + the marker and again **after** it has acquired it but before the socket is + bound. Both assert the same two answers on the same two surfaces: the + process exits non-zero with `owner_lost` on `stderr`, and a following daemon + starts on that root — with nothing to recover in the first case, and with + the stale marker its verified recovery reclaims in the second. A design that + ran the sequence inside `init/1` fails the first of them outright, because + `GenServer.start/3` has not returned yet and no monitor exists to fire. A + third asserts the happens-before directly: the command process is made to + delay its `:go`, and the case asserts the marker is **not** taken until the + message is sent, which is what proves the monitor precedes the first + irreversible acquisition rather than merely usually preceding it. - **Startup is interruptible, including inside the composition call.** A `SIGTERM` is delivered mid-startup at the step before the marker is taken, again at the step before the socket is bound, and again **between two edges @@ -3250,7 +3305,7 @@ individually would make this table a copy that rots. | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | -| **Daemon owner** | The `loopex daemon` command process, `GenServer.start/3` — **unlinked**, monitored immediately | Nothing; the command process holds a monitor | Itself; it halts the VM | The command process halts non-zero with `owner_lost`; the signal handler's backstop is the second route | +| **Daemon owner** | The `loopex daemon` command process, `GenServer.start/3` — **unlinked**, monitored immediately, with `init/1` acquiring nothing and the startup sequence running in `handle_continue(:start, …)` behind a `:go` the caller sends after the monitor | Nothing; the command process holds a monitor | Itself; it halts the VM | The command process halts non-zero with `owner_lost`; the signal handler's backstop is the second route | | Credential routing **registry** (ADR 0034) | Daemon owner, first | Daemon owner | Orderly step 6 | `registry_lost`, daemon-fatal | | Credential **custody process** (ADR 0034), one for the one composed model configuration | Daemon owner, second | Daemon owner | Orderly step 6 | `custody_lost`, daemon-fatal | | **Tracing capability** (ADR 0034) | Daemon owner, third, before composition | Daemon owner | Orderly step 6 | `capability_lost`, daemon-fatal: a sender that cannot confirm its trace exclusion refuses rather than resolves, so every model invocation would fail for a reason no client can fix | From e54c2babb8d64456b22e7de6b1ee3ce55b2981c3 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:07:30 -0700 Subject: [PATCH 122/585] plan(M5): a daemon-initiated detach is a record and a close B5. ADR 0032 bound one attachment to one connection, declined a core `detach/1`, and then required detaching while keeping the connection in three places -- `control_owner_lost`, pressure eviction and idle eviction. A connection whose attachment the daemon dropped holds nothing, can be told nothing except by the record it is being sent, and can only re-establish by a `session.attach` it could equally send on a new connection; core's own `disconnect/2` keeps the dispatcher entry, so nothing in the tree produced the state those passages assumed. One rule now covers all four occasions: write the generation-2 record -- `control_owner_lost`, or ADR 0023's existing `detached` for the three eviction cases -- best-effort into that connection's 4 MiB output buffer, then close **that connection**. Other connections are untouched, which is what "the observers stay" means now that a connection holds one attachment. `event_cursor` is defined once for all four as the last completely emitted durable cursor, never a buffered one; "best-effort" is `daemon.stopping`'s existing bound reused, one non-blocking attempt, no new timer and no new number. Four vectors, and a witness per occasion with a second connection on the same session asserting it keeps receiving across the whole of it. The rejection of a core `detach/1` stays and is narrowed to what it was about: a caller detaching itself. The daemon ending an attachment is the same monitor-driven release read from the other side -- the connection process ends and its `DOWN` releases the attachment with no call at all. --- ...tachment-residency-and-replay-technical.md | 102 ++++++++++++++---- ...controller-lease-and-takeover-technical.md | 14 +-- ...aboration-controller-lease-and-takeover.md | 3 +- docs/plans/M5-technical.md | 15 +-- docs/plans/M5.md | 5 +- 5 files changed, 103 insertions(+), 36 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index dfd24cb7f..0f74ed6b0 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -152,10 +152,17 @@ answered — ends that process, and the `DOWN` releases the attachment. That is what makes a connection a sufficient handle on an attachment, and it is why a daemon needs no attachment count from core to release what it reserved. -An explicit `detach/1` on the public API was the alternative and is rejected: +An explicit `detach/1` on **core's** public API was the alternative and is +rejected: it would add a call every caller must remember on every exit path, including the paths where the caller is already gone, which is exactly the case a -monitor handles for free. +monitor handles for free. That rejection is about the core API and about a +*caller* detaching itself. It is not a rule against the daemon ending an +attachment — the daemon does that four ways, listed with `control_owner_lost` +below, and every one of them is a record written to that connection and then +the close of that connection, which is the same monitor-driven release read +from the other side: the connection process ends, and its `DOWN` releases the +attachment with no call at all. The core EventDispatcher and Control retain multiple live attachment IDs and incarnations for one session. A new distinct attachment does not implicitly @@ -181,7 +188,9 @@ owed, and both daemon stages hold only bytes for events core has already named. When the next event would exceed the core count or a daemon byte bound, the daemon detaches the attachment at its last completely emitted cursor with a -stable reason rather than letting either stage grow. No byte limit is +stable reason rather than letting either stage grow — which, under the +daemon-initiated detach rule above, means one best-effort `detached` record +and then the close of that connection. No byte limit is enforced inside core. ### Generation 2 additions @@ -303,7 +312,7 @@ carry. | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost`, `fatal:listener_lost` — nine in a daemon with artifact transfers and eight without, one per linked component of the fixed set. A lease owner's death is not among them: it closes one session's controller attachment with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost`, `fatal:listener_lost` — nine in a daemon with artifact transfers and eight without, one per linked component of the fixed set. A lease owner's death is not among them: it closes one session's controller connection with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | @@ -338,7 +347,7 @@ limits — five inputs, and generation 2 changes **all five**: **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 makes a lease owner's failure session-scoped: the daemon closes that session's -controller attachment, leaves its observers attached, and lets the next +controller connection, leaves its observers attached on their own, and lets the next acquisition start a fresh owner with a fresh epoch. The closing client is owed a reason for a close it did not ask for, and this is it — distinct from `control_held`, which refuses an acquisition, and from `control_pending`, @@ -422,12 +431,56 @@ uncorrelated `error`**, with | `session_id` | the session whose lease owner died | | `event_cursor` | the last completely emitted durable cursor for that attachment, exactly as `detached` carries it | -It is uncorrelated because no request caused it. **Close behaviour:** the -daemon emits it to the **controller's** attachment and then closes that -attachment only — the connection stays open, and observer attachments on it or -on any other connection are untouched, because an observer holds no lease and -loses nothing. A client that sees it may acquire again; the next acquisition -starts a fresh owner and mints a fresh epoch. +It is uncorrelated because no request caused it. **Close behaviour:** it is one +instance of the daemon-initiated detach rule below — the daemon writes the +record best-effort into that connection's output buffer and then **closes that +connection**. Every other connection is untouched, so every observer keeps its +attachment and keeps receiving, which is what "the observers stay" means: an +observer is on a connection of its own, because generation 2 binds a +connection to at most one attachment. A client that sees it may reconnect and +acquire again; the next acquisition starts a fresh owner and mints a fresh +epoch. + +**Every daemon-initiated detach is a record and a close, and the rule is one +rule.** A connection holds at most one attachment, so a daemon that "detaches" +a connection has left it holding nothing — no cursor position it can act on, +no way to be told what it may resume from except the record it is being sent, +and no mechanism to re-establish an attachment except a fresh `session.attach` +it could equally send on a fresh connection. An earlier revision left such a +connection open and declined a detach API in the same breath, which left the +client in a state neither side had defined. So: + +| Occasion | Record written first | Then | +| --- | --- | --- | +| The controller's lease owner died | `error`, `control_owner_lost`, with `session_id` and `event_cursor` | close that connection | +| Output-buffer or core-queue overflow | `error`, ADR 0023's `detached`, with `session_id` and `event_cursor` | close that connection | +| Aggregate byte pressure chose this attachment | the same `detached` | close that connection | +| Idle eviction at ten minutes | the same `detached` | close that connection | + +**`event_cursor` is the same quantity in all four**: the **last completely +emitted durable cursor** for that attachment — the highest event sequence the +daemon finished writing to that socket, never one it had only encoded or +buffered. That is the position the client reconnects at, and delivery from it +is contiguous and at least once, so a duplicate at the seam is expected and a +gap is a defect. + +**"Best-effort" is the bound `daemon.stopping` already has**, reused rather +than restated: exactly **one** non-blocking write attempt of the record into +the connection's existing 4 MiB output buffer, and the close happens whatever +that attempt did. A backpressured client — which is precisely the client an +overflow detach is about — will usually not receive it and learns by EOF +instead. No new timer and no new number. + +**No other connection is affected by any of the four**, and that is the +property the witnesses assert: a case per occasion, each with a second +connection attached to the same session, asserting the first connection sees +the record where its buffer admits one and sees EOF either way, and the second +keeps receiving durable events across the whole of it. Each of the four is a +generation-2 vector: `control_owner_lost` under its own code, and three +`detached` vectors distinguished by nothing on the wire — the code and fields +are identical, which is deliberate, because why the daemon detached is an +operator fact in its logs and not authority-shaped information a client acts +on differently. **`daemon_stopping`, the refusal after the admission cut.** An orderly stop begins with a synchronous, acknowledged cut: the daemon's owner calls the @@ -879,8 +932,11 @@ delivered contiguously after the snapshot. The daemon adds: aggregate is below the ceiling**, not applied once: releasing one window may not be enough, so zero-attachment windows are released in that order until either the aggregate fits or none is left. Only when none is left does the - daemon detach the slowest attachment at its last emitted cursor, and that - too repeats until the aggregate fits. Independently of pressure, a window whose session has had zero + daemon detach the slowest attachment at its last emitted cursor — sending + that connection a `detached` record and closing it, under the detach rule + above, so the bytes the attachment was holding are released with the + connection rather than lingering behind an open socket nothing is reading — + and that too repeats until the aggregate fits. Independently of pressure, a window whose session has had zero attachments for the idle interval is dropped. No reclamation stalls a journal transaction and none changes what any client is owed. @@ -891,16 +947,18 @@ delivered contiguously after the snapshot. The daemon adds: none claims to; - the core event-count queue and the daemon socket output buffer above; when the next event would exceed either, the attachment is detached at its last - completely emitted cursor with a stable reason and the client reconnects - at that cursor; + completely emitted cursor with a stable reason — a `detached` record and the + close of that connection, under the detach rule above — and the client + reconnects at that cursor on a new connection; - at most 512 MiB of retained encoded events across the daemon's output buffers and resident windows; on aggregate pressure, evict or detach the slowest eligible attachment before admitting more bytes, without stalling - a journal transaction; + a journal transaction, and by the same record-then-close; - 64 attachments per session and 512 per daemon, refused at attach with a stable reason when exhausted; - eviction of an attachment that has consumed nothing for ten minutes; the - eviction record names the cursor the client may resume from; + `detached` record names the cursor the client may resume from and the + connection is closed with it; - transient progress coalesced per attachment and dropped first under pressure, with a counted drop; no progress item ever waits on a journal transaction. @@ -921,10 +979,12 @@ window dropped mid-stream, proving the cache establishes nothing; deterministic reclamation in the fixed order above, including the case where zero-attachment windows alone consume the aggregate ceiling and are released before any attachment is detached; a slow observer detached at -its last emitted cursor while the controller and other attachments continue; -the per-session and per-daemon limits refusing independently; idle eviction -and reconnect with no missing durable event and any duplicate deduplicated by -session ID, sequence and event ID; the three encoded-byte ceilings at maximum +its last emitted cursor — its `detached` record written best-effort and its +connection closed — while the controller and other attachments on their own +connections continue; +the per-session and per-daemon limits refusing independently; idle eviction, its close, and reconnect on a +fresh connection with no missing durable event and any duplicate deduplicated +by session ID, sequence and event ID; the three encoded-byte ceilings at maximum attachment count and payload pressure enforced in the daemon-owned stages, with process RSS observed and reported separately; a generation-1-only initialize refused with `unsupported_generation` and nothing created; diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index c43f1fef2..cbe2847d1 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -58,10 +58,11 @@ owner that dies takes the set with it, so no successor owner can inherit it — and none tries to. What happens instead is exactly what happens when a lease is gone by any other route: -- the daemon closes that session's **controller** attachment with - `control_owner_lost`, the wire reason ADR 0032's generation-2 inventory - carries for it, and leaves every observer attached, because an observer - holds no lease and loses nothing; +- the daemon writes `control_owner_lost` to that session's **controller** + connection and closes it with its attachment, under the daemon-initiated + detach rule ADR 0032's generation-2 inventory fixes for exactly this, and + leaves every observer attached, because an observer + holds no lease, is on a connection of its own and loses nothing; - the lease itself is gone, held by nobody; - the next `session.acquire_control` for that session starts a **fresh** owner, holding no lease and no admission set, and mints a **fresh epoch** — @@ -314,8 +315,9 @@ closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after it in both cases; a controller killed mid-run fenced after takeover, its late commands refused; a lease owner killed while a mutation is in flight taking neither the daemon nor -any other session down: that session's controller attachment closes with -`control_owner_lost`, its observers stay attached, the relay retains the +any other session down: that session's controller connection is sent +`control_owner_lost` and closed with its attachment, its observers stay +attached on their own connections, the relay retains the outstanding ticket, the replacement owner's first grant waits until it settles, and the previous holder's delayed command is refused on both the holder and the epoch check; diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index f9de5c7ea..8cda27f03 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -109,7 +109,8 @@ path: every refusal — stale epoch, copied current epoch, non-holder connection, released lease, expired lease, observer abort — proved before core admission and before any session write, a controller killed mid-run fenced after takeover, a lease owner killed while a mutation is in flight taking neither the daemon -nor any other session down — its controller closed with `control_owner_lost`, +nor any other session down — its controller's connection sent +`control_owner_lost` and closed, its observers kept, and the replacement's grant held until the relay's outstanding ticket settles — and a daemon restart leaving every session uncontrolled with every earlier epoch refused. No durable record changes, so no migration or diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index ca6406980..17dca165f 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -117,7 +117,8 @@ nothing created. The lease record lives in the daemon's memory, keyed by session, for as long as that session has a lease or an acquisition; one owner process per session serializes its lease transitions with its admission handoff, and that owner's failure is **scoped -to its session**: the controller attachment closes with `control_owner_lost`, +to its session**: the controller's connection is sent `control_owner_lost` +and closed with its attachment, every observer stays, and the next acquisition starts a fresh owner with a fresh epoch. What keeps a successor's call from overtaking an older one is the **admission relay**, a fixed daemon process that holds a ticket for every core @@ -143,8 +144,8 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and every ticket it holds has settled or been recorded — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to settle or to be fenced under the drain, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — and a `session.create` sent after the cut refused the same way, which is the case that would fail if creates bypassed the relay; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost`, carrying `session_id` and `event_cursor` and closing one session's controller attachment without ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller attachment closed with `control_owner_lost`, its observers still attached and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -2775,8 +2776,10 @@ die without a name for it. **A lease owner's exit is the one that is not in this table**, and its absence is the rule rather than an omission. The owner's clause maps that pid to the session it belonged to and handles it per session: the daemon closes that -session's controller attachment with `control_owner_lost`, leaves every -observer attached, and keeps serving every other session. The next +session's controller connection with `control_owner_lost` — the record +best-effort, then the close — leaves every +observer on its own connection attached, and keeps serving every other +session. The next `session.acquire_control` for it starts a fresh owner with a fresh epoch, on ADR 0033's ordinary takeover mechanics. The reason is stated there and it is proportionality: one session's collaboration state is not grounds to end every @@ -3358,7 +3361,7 @@ survive arrives as `runtime_lost`. | **Core ↔ daemon: attach** | `loopex` owns the cursor barrier, snapshot and queues | Barrier race, stale handle, queue overflow, **an attachment whose holder is gone** | Core's existing attach transaction and stale-handle checks; **and core change 1's monitor on the attaching process, which is what releases an attachment when its holder exits — the daemon attaches from its per-connection process, so a closed connection releases its attachment with no call**; the daemon reads no coordinator state to repair a race | Snapshot then contiguous at-least-once events, or detachment at the last emitted cursor with a stable reason | **Durable:** the events. **Not:** the attachment, the window, the buffer | | **Core ↔ daemon: resume** | `loopex` | Placement mismatch, unknown session, already-resolved command | Core's existing resume path and command idempotency (`control.ex:901-907` returns the historical result without starting an owner) | Core's refusal, forwarded unchanged | **Durable:** the resume command and its result | | **Core ↔ daemon: commands** | `loopex` admits; the daemon forwards | **Coordinator death** | Core's `DynamicSupervisor` (`restart: :temporary`, `session_coordinator.ex:134-142`); `Control` consumes the `DOWN`, releases the fence and leaves the entry (`control.ex:821`). **No signal reaches the daemon, and none is owed** — the daemon supervises the runtime, not the coordinators beneath it | Core's existing refusal on the next command for that session, forwarded unchanged. `residency` still reads `active`, which remains true: this daemon did activate it | **Durable:** whatever committed before. **Not:** any claim about liveness | -| **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies; its in-flight admission set goes with it, and the relay's ticket for any mutation it had authorized does not | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller attachment closes with `control_owner_lost`; observers stay attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch, its first grant waiting until the relay's outstanding tickets for that session settle | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | +| **Lease owner ↔ connections** | `loopex_daemon` | A session's lease owner dies; its in-flight admission set goes with it, and the relay's ticket for any mutation it had authorized does not | The owner's `{:EXIT, pid, reason}` clause maps the pid to **its session** rather than to a daemon class — the one session-scoped row in this table, on the maintainer's decision of 2026-09-20 | That session's controller connection is sent `control_owner_lost` and closed with its attachment; every observer, being on a connection of its own, stays attached; the next `session.acquire_control` starts a fresh owner and mints a fresh epoch, its first grant waiting until the relay's outstanding tickets for that session settle | **Not durable:** the lease, the epoch, the in-flight set. The journal is untouched, and a mutation already inside core settles or refuses exactly once under core's serial ownership | | **Lease owner ↔ connections (expiry)** | `loopex_daemon` | A holder stops renewing, or a mutation is unresolved at the deadline | The lease owner's own monotonic deadline; the in-flight set decides when a takeover is granted | The holder's next mutation refuses; a takeover is eligible at the deadline and granted when the in-flight set empties | **Not durable:** the lease. The mutation that was in flight settles or refuses exactly once | | **Listener ↔ connections** | `loopex_daemon` | Foreign peer, malformed frame, over-long path, backpressure | Filesystem permission verified after bind, then the per-platform peer-credential read (`LOCAL_PEERCRED` / `SO_PEERCRED`), then ADR 0023's framing refusals; backpressure at the 4 MiB output buffer | Closed before initialize for a peer refusal; a stable framing reason otherwise; detachment at the last emitted cursor under backpressure | **Not durable:** connections, buffers, windows | | **Registry ↔ sender ↔ custody** | The **host** owns the registry, custody and the tracing capability; the adapter owns the sender. The token is bound at composition, resolved per invocation | No registry row, registry dead, custody dead, refusal, malformed reply, deadline, or a trace exclusion that cannot be confirmed | `route(handle, token)` answers `:unavailable`; resolution fails as one of the six atoms produced below the guardian (`:no_token`, `:invalid_token`, `:missing`, `:expired`, `:oversized`, `:unavailable`); the **guardian** enforces the deadline, kills the sender and reports the seventh, `:timeout` | The adapter's existing `Loopex.Model` refusal shape, with the atom in the bounded diagnostic | **Not durable:** nothing about credentials is ever journaled, and no span or record carries model `options` — the model span is a fixed identity map. The invocation's failure is durable | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 27e46b237..a9837a60c 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -221,7 +221,8 @@ restart leaves every session uncontrolled with every earlier epoch stale, and the core keeps mandating no lease. One owner process per session serializes that session's transitions against its own admissions. Its failure is scoped to that session rather than to the daemon, on the maintainer's decision of -2026-09-20: the controller attachment closes with `control_owner_lost`, every +2026-09-20: the controller's connection is sent `control_owner_lost` and +closed with its attachment, every observer stays, and the next acquisition starts a fresh owner with a fresh epoch — the takeover mechanics that already exist for a released lease. What the daemon does not claim is that it knows whether an admission the dead owner @@ -610,7 +611,7 @@ lease owner per session under lease or acquisition**, started at the first lease operation rather than at activation, retired when the lease is free and nothing is outstanding, and capped at the 512 ADR 0032 already fixes. That one class is session-scoped rather than daemon-fatal: its death closes that -session's controller attachment and leaves every other session serving, while +session's controller connection and leaves every other session serving, while the relay is what keeps the replacement's first call from overtaking an older one. It keeps every pid, because each one is a component it must be able to name when that component dies. An From 4aefe6a79f55004f076dcf02de7f0570d7a78006 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:08:39 -0700 Subject: [PATCH 123/585] plan(M5): bound concurrent connections and stop citing ADR 0032 by line B6. The process inventory bounded connections by "ADR 0032's attachment ceilings", which bound nothing about a client that connects, initializes, lists, acquires or idles without ever attaching -- so the number of sockets a daemon holds had no ceiling at all. It is 512 concurrent accepted connections, the attachment number reused rather than a fourth 512 invented. The refusal stays inside ADR 0023's negotiation rules: a correlated `capacity_exceeded`, a code generation 1 already carries so the ordered error list gains nothing, answered at `initialize` rather than withheld at `accept` so a peer can tell a full daemon from a wedged one, after which the connection stays uninitialized with no second attempt and is closed. `daemon.status` gains `connections` and `connection_limit`, the limits input gains `connections_per_daemon`, and the witness is a boundary pair: the 512th served, the 513th refused, and closing one letting the next through. Beside it, the cross-document line citations into ADR 0032 are replaced with section references. Four of them -- `:854`, `:263`, `:333-335`, `:247`, `:154`, `:850`, `:127-129`, `:131-155` -- already pointed at the wrong lines before this round edited the file, and a citation that silently drifts is worse than a named section a reader can find. --- ...tachment-residency-and-replay-technical.md | 30 +++++++++++++++++- ...-daemon-attachment-residency-and-replay.md | 5 +-- docs/plans/M5-technical.md | 31 ++++++++++--------- 3 files changed, 49 insertions(+), 17 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 0f74ed6b0..89f102200 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -229,6 +229,8 @@ no content, no durable session state. | result | `placement_identity` | binary identity | required | | result | `daemon_incarnation` | binary identity | required | | result | `socket_path` | string | required | +| result | `connections` | integer, accepted connections currently open | required | +| result | `connection_limit` | integer, 512 | required | | result | `attachments` | integer | required | | result | `attachment_limit` | integer, 512 | required | | result | `active_sessions` | integer | required | @@ -293,6 +295,7 @@ added keys are enumerated so the digest covers them: | Limit key | Value | | --- | --- | +| `connections_per_daemon` | 512 | | `attachments_per_session` | 64 | | `attachments_per_daemon` | 512 | | `session_list_page_max` | 256 | @@ -302,6 +305,31 @@ added keys are enumerated so the digest covers them: ADR 0023's own framing and input ceilings are unchanged; these are additions beside them, and **all five** digest inputs therefore change in generation 2. +**Connections are bounded, and an earlier revision said they were bounded by +the attachment ceiling, which they are not.** A client may connect, +`initialize`, call `session.list`, `daemon.status` or +`session.acquire_control`, or sit idle, without ever attaching — so the +attachment ceilings bound nothing about the number of sockets the daemon +holds, and a daemon whose bound is "the attachment ceiling" has no bound on +connections at all. The ceiling is **512 concurrent accepted connections**, +the attachment number reused rather than a fourth 512 invented, and the +daemon reports it as `connection_limit` with the live count as `connections` +so an operator can see the headroom before it is gone. + +**The refusal is ADR 0023's, not a new one.** A connection accepted beyond the +ceiling is answered, at its `initialize`, with a correlated +**`capacity_exceeded`** — which generation 1 already carries, so generation +2's ordered error list gains nothing for it — and then closed. It is answered +at `initialize` rather than refused at `accept` because a peer that is never +answered cannot tell a full daemon from a wedged one, and because ADR 0023 +already fixes what a refused `initialize` means: the connection remains +uninitialized and gets no second negotiation attempt +(`0023-…-technical.md:357-358`). The peer-credential and filesystem checks +still run first; a foreign peer is closed before any of this. Its witness is a +boundary pair: the 512th connection initializes and is served, the 513th is +refused `capacity_exceeded` and closed, and closing one of the 512 lets the +next through. + The tables above are the contract for both directions; an earlier revision kept a second, prose summary of the same four methods beside them, which is exactly how two descriptions of one wire drift apart. It is gone, and the @@ -343,7 +371,7 @@ limits — five inputs, and generation 2 changes **all five**: | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` and `daemon.notice` | | **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 reuses for the connection ceiling | -| **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | +| **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `connections_per_daemon`, `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 makes a lease owner's failure session-scoped: the daemon closes that session's diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index e0542eb66..e0df29b9f 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -145,8 +145,9 @@ over what the Store contains, because no index built from the session directory can claim that. Lineage, lifecycle state and committed sequence are not list fields: a client that needs them attaches and reads the snapshot. The proposed -limits are exact and are bound at acceptance: 64 attachments per session, -512 per daemon, a 1,024-event core queue per attachment, a 4,096-event +limits are exact and are bound at acceptance: 512 concurrent connections per +daemon, 64 attachments per session, +512 attachments per daemon, a 1,024-event core queue per attachment, a 4,096-event resident window per session, 4 MiB of encoded output buffered per connection, 16 MiB of encoded resident-window events per session, 512 MiB of aggregate retained encoded events per daemon, ten minutes of idle time diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 17dca165f..a2cc3ea00 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -696,8 +696,8 @@ without `--daemon` nothing reaches a socket — and it presents: contains*. A warning rather than a failure, because the page it accompanies is still true as far as it goes; - `--status`, which issues `daemon.status` and prints placement identity, - daemon incarnation, socket path, attachment, activation and index counts - against their limits, and uptime. + daemon incarnation, socket path, connection, attachment, activation and + index counts against their limits, and uptime. Exit status: `0` for a page printed, including an empty one; non-zero with the reason on `stderr` when the socket cannot be reached, the peer check refuses, @@ -1074,7 +1074,7 @@ releases on that. **Attach: end the connection process and the attachment goes with it.** Core exposes no attachment count, so there is nothing to observe — and nothing needs to be. ADR 0032 binds a connection to **at most one attachment at a -time** (`0032-…-technical.md:127-129`, with the release rule at `:131-155`), the daemon attaches from its +time** (ADR 0032's transport section, with its release rule beside it), the daemon attaches from its **per-connection process**, and core change 1 makes the dispatcher monitor that process and drop its attachment on `DOWN`. So the reservation is keyed by the connection, and a connection whose `session.attach` never answered is @@ -1470,7 +1470,7 @@ implementation: | When does one start? | On the **first lease operation for that session after successful existence validation** — an `session.acquire_control`, whether or not the session is active. Not at activation: an earlier revision said activation, which was wrong twice over, since dormant recovery acquires *before* it resumes and `loopex attach --take-over` may acquire and release a session it never activates | | When does one retire? | When the lease is free — released or expired — **and** no acquisition is waiting **and** the relay holds no outstanding ticket for that session. All three, because any one of them alone would retire an owner whose state something still depends on | | When does one stop unconditionally? | At daemon exit, in the stop sequence below | -| How many can exist at once? | One per session under lease or acquisition, capped at **512, the per-daemon attachment ceiling ADR 0032 already fixes** (`0032-…-technical.md:854`), reused rather than invented, with the cap and its refusal stated at `0032-…-technical.md:333-335` and `:247`; a lease operation that would exceed it refuses with `control_capacity_reached`. The population is **independent of the activation ceiling**, which counts something else entirely | +| How many can exist at once? | One per session under lease or acquisition, capped at **512, the per-daemon attachment ceiling ADR 0032 already fixes**, reused rather than invented, with the cap and its `control_capacity_reached` refusal stated in that pair's error inventory; a lease operation that would exceed it refuses with `control_capacity_reached`. The population is **independent of the activation ceiling**, which counts something else entirely | | What does its death mean? | That **session's** collaboration state, not the daemon's — the one exception to fail-stop uniformity, below | **Why not the activation ceiling.** An earlier revision bounded the population @@ -3325,7 +3325,7 @@ individually would make this table a copy that rots. | Group | Started by | Bound | Its death | | --- | --- | --- | --- | | **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | -| **Connections**, one per accepted client | The listener | ADR 0032's attachment ceilings | That client's connection closes | +| **Connections**, one per accepted client | The listener | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | | **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time | Nothing: monitored, never linked | | **Relay tasks**, one per ticketed mutation | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | @@ -3477,13 +3477,14 @@ line; M5 introduces none of its own. | Log capacity per state root | 256 MiB; an append past it refused as `store_capacity_exceeded`, which terminates the store and closes the daemon, a log already past it refused at open as `store_log_too_large` | ADR 0031 | | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | +| Concurrent connections per daemon | 512, the attachment number reused; the 513th is refused `capacity_exceeded` at `initialize` and closed | ADR 0032 | | Attachments per session | 64 | ADR 0032 | -| Attachments per daemon | 512 | ADR 0032, `:854`, with the limit key at `:263` | +| Attachments per daemon | 512 | ADR 0032, its attachment-lifecycle list, with the limit key in its limits table | | Core event-count queue per attachment | 1,024 events | ADR 0032 | | Daemon socket output buffer per connection | 4 MiB encoded | ADR 0032 | | Resident window per session | 4,096 events and 16 MiB encoded | ADR 0032 | -| Aggregate retained encoded events per daemon | 512 MiB | ADR 0032, `:154` and `:850` | -| Concurrent lease owners | 512, the attachment number reused rather than a second limit | ADR 0032, `:333-335`, with its refusal at `:247` | +| Aggregate retained encoded events per daemon | 512 MiB | ADR 0032, its queue-ownership and attachment-lifecycle sections | +| Concurrent lease owners | 512, the attachment number reused rather than a second limit; the refusal is `control_capacity_reached` | ADR 0032, where that refusal is defined | | Idle time before an attachment is evicted and its window and buffer released | 10 minutes; it never stops a coordinator | ADR 0032 | | Sessions activated per daemon lifetime | 64; the 65th activation refused, the remedy being to restart the daemon. It is per lifetime rather than concurrent because nothing deactivates a coordinator, which is recorded as a limitation | ADR 0032 | | Recorded session index entries per root | 4,096; a root whose directory holds more refused at daemon start. The ceiling is on recorded entries and never on reachability: a session reached by ID beyond it is activated and not recorded, and the listing carries `index_full` | ADR 0032 | @@ -3508,13 +3509,15 @@ line; M5 introduces none of its own. | Credential frame cap | 69,632 bytes | ADR 0034, which is where the frame's shape is written; no ADR 0019 file states it | | `req_llm` version pin | `~> 1.24.0` | Maintainer decision 4B of 2026-09-20, a **plan** decision. A dependency pin is not a contract number: it binds what this milestone builds against and is changed by an ordinary reviewed dependency change, not by an ADR amendment | -**Three rows say 512 and they are three different bounds**, which is worth one +**Four rows say 512 and they are four different bounds**, which is worth one sentence because "one number, one ADR" would otherwise read as one limit: 512 -*attachments* per daemon (ADR 0032 `:854`), 512 *MiB* of retained encoded -events across every buffer and window (`:147`, `:716`), and at most 512 -concurrent *lease owners* (`:333-335`), the last deliberately reusing the -attachment number rather than introducing a third limit that could drift from -it. +*attachments* per daemon, 512 *MiB* of retained encoded +events across every buffer and window, at most 512 +concurrent *lease owners*, and at most 512 concurrent *connections* — the last +two deliberately reusing the attachment number rather than introducing limits +that could drift from it. The connection bound is not implied by the +attachment bound and is stated separately for that reason: a client may +connect, initialize, list and acquire without ever attaching. Count and byte ceilings apply together: an event that would exceed either triggers the stated detachment, eviction or refusal before the ceiling is From 8a158d378d12239cb22780cdc4d95aa3282bfef0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:10:05 -0700 Subject: [PATCH 124/585] plan(M5): key reservations by command and keep the facade's return B7. Four things about the activation reservation were wrong. It was keyed by session ID for a resume, so two resume commands for one dormant session collided on one key. It is now the pair `(command_id, session_id)`, with a create's session position filled in when the call answers. An already-counted active session's resume was refused at the ceiling although it adds no activation. A session already in the activation set now takes no reservation and meets no ceiling test, so a controller cannot be locked out of a session it is already driving. The "no answer in 5 s" premise was false: `create_session/3` and `resume_session/3` pass `:infinity` explicitly (`runtime.ex:156-163`, `:169-177`) and never inherit the `control_call/3` default, and `attach/3` takes no timeout at all. There is no deadline to give the daemon no answer. What ends the wait is the per-connection process dying while the call runs in core, so the rows name that, and the resolution owner is the relay -- which holds the call's real answer whether or not the asker survived, and which is the second reason creates are ticketed. The client's replay under the same `command_id` remains the client-visible half and charges no second slot. And the richer result would have changed the embedded facade: `loopex.ex:87` forwards `Runtime.create_session/3` verbatim, as `:110` does for resume, so widening those returns breaks a released caller. Core change 5 is now two new daemon-facing functions, `create_session_detailed/3` and `resume_session_detailed/3`, with the existing pair a projection of them and its spec and return untouched. --- docs/plans/M5-technical.md | 133 ++++++++++++++++++++++++++----------- docs/plans/M5.md | 8 ++- 2 files changed, 101 insertions(+), 40 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index a2cc3ea00..caa269c86 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not**, **the runtime-side create and resume results' `disposition` and `control_entry` fields**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -904,10 +904,30 @@ Rather than make the daemon use a mode it does not otherwise want, the plain resume result carries the same `disposition` and `control_entry` the create result does. That is one shape for both, not two. -**The public protocol result is unchanged.** Generation 1 and generation 2 +**The two fields arrive on new functions, not on the existing ones**, and that +is the half an earlier revision left unsaid. `Loopex.Runtime.create_session/3` +and `resume_session/3` are specified `{:ok, binary()} | {:error, term()}` +(`runtime.ex:156`, `:169`), and the embedded facade forwards exactly that: +`Loopex.create_session/3` returns what `Runtime.create_session/3` returns +(`loopex.ex:87-91`) and `Loopex.resume_session/3` likewise (`:110-113`). +Widening those returns would change what a released embedded caller receives +from a call it already makes — a compatibility break taken for a daemon's +bookkeeping. + +So core change 5 adds **two daemon-facing functions beside them**, +`Loopex.Runtime.create_session_detailed/3` and +`resume_session_detailed/3`, answering +`{:ok, %{session_id: binary(), disposition: :fresh | :historical, +control_entry: :active | :dormant}} | {:error, term()}`. The existing pair +keeps its exact spec and its exact return, implemented as a projection of the +detailed one, so `loopex.ex:87` and `:110` forward what they forward today and +no embedded caller sees anything move. The daemon calls the detailed pair, +which is the only caller that needs them. + +**The public protocol result is unchanged too.** Generation 1 and generation 2 return what they return today; this is an in-VM API detail between core and any host, and no wire schema, digest or vector moves. A host that ignores the -fields behaves exactly as it does now. +detailed functions behaves exactly as it does now. **What happens at the ceiling, stated because the honest answer is not the neat one.** The brief for this change asked whether a fresh create can be @@ -1001,14 +1021,32 @@ core is called at all**, which is the only place a refusal can be both truthful and early. The reservation is taken in the daemon's own serial owner, so "atomic" needs no new mechanism: it is one process deciding. -**A reservation is keyed by the identity the daemon has when it takes one** — -the session ID for a resume, the create `command_id` for a create, whose -session ID does not exist yet — and it is **converted or released +**A reservation is keyed by `(command_id, session_id)`**, and the pair matters +in both directions. An earlier revision keyed a resume's reservation by its +**session ID alone**, which collides the moment two clients send two different +resume commands for one dormant session: the second would find a reservation +already taken for a key it does not own, and either double-count or refuse a +command that should have refused for a different reason. The command +identity is what makes a reservation *this call's*. A create's session +position is empty until the call answers — no session ID exists to key on — +and is filled in when it does; a resume carries both from the start. + +It is **converted or released idempotently**: converting records the session ID in the activation set and drops the reservation; releasing drops it. Repeating either for the same key is a no-op, so a retry, a crash-recovered handler or a duplicated reply cannot double-count or double-free. +**A session already in the activation set takes no reservation at all**, which +an earlier revision also got wrong: it refused a resume at the ceiling for a +session this daemon had *already* activated, although that resume adds no +activation — the coordinator exists, the slot was spent when it started, and +core's own command idempotency handles the rest. So the rule is checked in +that order: if the session ID is already counted, the call proceeds with no +reservation and no ceiling test; only a call that may add an activation +reserves. That is also what keeps a controller from being locked out of a +session it is already driving merely because the daemon is full. + **Every branch of both results resolves the reservation, and the table is complete rather than illustrative**, because a branch nobody listed is a slot leaked until the daemon restarts: @@ -1022,33 +1060,46 @@ leaked until the daemon restarts: | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | | Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | | Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | -| A **resume** crashing or timing out | **Held, then resolved by replay**: replayed under its original `command_id`, whose `disposition`/`control_entry` say whether the original call activated the session. The existence query cannot answer this — it says `present` either way | -| A **create** crashing or timing out | **Held, then resolved by replay**: replayed under the same `command_id`, which returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | +| A **resume** whose connection is lost while the call is in flight | **Held, then resolved by the relay**, which holds the call's real answer whether or not the process that asked is still there; where the daemon must re-establish it later, the client's replay under its original `command_id` carries the same `disposition`/`control_entry`. The existence query cannot answer this — it says `present` either way | +| A **create** whose connection is lost while the call is in flight | **Held, then resolved by the relay** the same way; a later replay under the same `command_id` returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | | An **attach whose connection process ends before it answers** | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment, and core change 1 monitoring the attaching process. The daemon closes that connection, its process ends, and the dispatcher's `DOWN` handler drops the attachment. Nothing is observed, because nothing needs to be | -**That last row is not hypothetical, and the reason is a default nobody -chose.** The daemon reaches core through `Loopex.Runtime`, whose -`control_call/3` and `dispatcher_call/3` default to a **five-second** reply -timeout (`runtime.ex:470`, `:478`). A create or resume that takes longer -returns the daemon an error while core is still starting a coordinator — so -"the call gave no answer" is an ordinary outcome of a slow root, not an -exotic one. Every daemon call that consumes a ceiling **and accepts one** -therefore carries an explicit timeout rather than inheriting that default, and -resolves its reservation by the rule its own row names when the timeout is -what it gets. - -**`Runtime.attach/3` accepts none and needs none**, which is why the qualifier -matters. Its signature takes a runtime, a session ID and options and no +**Those rows used to say "crashing or timing out", and the timing-out half was +false.** An earlier revision rested it on a default: `Loopex.Runtime`'s +`control_call/3` and `dispatcher_call/3` do default to a **five-second** reply +timeout (`runtime.ex:470`, `:478`) — but **`create_session/3` and +`resume_session/3` both pass `:infinity` explicitly** +(`runtime.ex:156-163`, `:169-177`), so neither inherits it and neither can +time out. There is no deadline on those calls to give the daemon "no answer". +What actually ends the wait is the **per-connection process dying** while the +call is still running in core, which is why the rows now name that. + +**`Runtime.attach/3` is the same shape for its own reason.** Its signature +takes a runtime, a session ID and options and no timeout at all (`runtime.ex:198-210`), and inside it waits `:infinity` twice — at the dispatcher and again at the install (`:538`, `:547`) — **precisely so a caller timeout cannot revoke a mutation it cannot see**, which is what the code says there in as many words: the dispatcher has already created the attachment and the install is registering its routing, so a caller that gave up would be revoking neither mutation, and could not report truthfully that -the attach failed. The attach row above is written against that reality -rather than against a timeout the call does not have. - -**A call that gives the daemon no answer may still have started a coordinator +the attach failed. All three activation-capable calls therefore wait +`:infinity`, and the daemon's rule is the simpler one an earlier revision +obscured: **it adds no timeout to a core call that consumes a ceiling**, +because a timeout it could not act on truthfully would be worse than the +wait. + +**Who resolves a reservation when the asking process is gone: the relay.** The +relay's task performs the core call and returns core's answer whether or not +the connection that asked still exists, so for the two ticketed calls the +relay holds the `disposition` and `control_entry` and hands them to the +daemon's serial owner, which converts or releases by the row above. That is +the whole of the ordinary path, and it is why creates are ticketed. The +client, which saw nothing, recovers as it always does — by re-presenting the +same `command_id`, whose replay returns the historical result and the same two +fields, charging no second slot because the reservation key is the pair. + +**A call whose answer the daemon holds no route to may still have started a +coordinator or an attachment**, so releasing the reservation would let the ceiling be exceeded and converting it would spend a slot that may not exist. What resolves it differs by call, and an earlier revision used one resolution for @@ -2876,11 +2927,11 @@ nothing proves. Each is named where it is used: | Surface | Created by | Read by | | --- | --- | --- | -| The dispatcher's release on `DOWN` | Core change 1 | The concurrent-attachment cases and the attach no-answer case | +| The dispatcher's release on `DOWN` | Core change 1 | The concurrent-attachment cases and the attach connection-loss case | | The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | | `Control`'s excluded-pid set | Core change 3 | The trace-exclusion cases | | `quiesce/1`'s three lists, `budget_ms`, `drain_id` and the per-session `fences` map | Core change 4 | The drain cases, the fence cases and the stop line | -| `disposition` and `control_entry` | Core change 5 | The create and resume no-answer cases | +| `disposition` and `control_entry`, on `create_session_detailed/3` and `resume_session_detailed/3` | Core change 5 | The create and resume connection-loss cases, and the case asserting `create_session/3`'s own return is byte-identical to today's | Everything read outside those five exists today — the journal, a supervisor's children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. @@ -3238,26 +3289,30 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. `:823`) in the same VM and asserts **512**, not 513. Saying "proved by core holding 512" without saying where that number is read would have been the same unobservable claim this round removed elsewhere. -- **Every branch releases or converts its reservation, and the no-answer +- **Every branch releases or converts its reservation, and the connection-loss cases are written so the two outcomes can differ.** One case per row: a fresh create, a replayed create against an active and a dormant session, a - fresh resume, a replayed resume, a refusal, and then the three no-answer - rows, each constructed so that a resolution which could not discriminate - would fail: - - *Resume, no answer, two sub-cases.* One where the original resume **did** + fresh resume, a replayed resume, a refusal, and then the three + connection-loss rows, each constructed so that a resolution which could not + discriminate would fail. Two more sit beside them: a resume for a session + **already in the activation set** at the ceiling, asserted to **succeed** + with no reservation taken, since it adds no activation; and two different + resume commands for one dormant session, asserted to hold two reservations + under their two `(command_id, session_id)` keys rather than colliding on one: + + *Resume, connection lost in flight, two sub-cases.* One where the original resume **did** activate the session and one where it **did not** — the same session ID, the same query answer `present` in both. The case asserts the daemon converts in the first and releases in the second, which it can only do from the replayed result's `disposition` and `control_entry`. A resolution by existence query would give the same answer to both and is thereby excluded. - *Create, no answer.* The replay is asserted **in-VM** to start no + *Create, connection lost in flight.* The replay is asserted **in-VM** to start no coordinator — no new pid under core's session supervisor — and to charge no second slot, and the slot count afterwards distinguishes a fresh original from a replayed one. - *Attach, no answer.* Two surfaces, and they differ in the two cases. On the + *Attach, connection lost in flight.* Two surfaces, and they differ in the two cases. On the wire, the client's connection is asserted **closed** — an EOF a test can observe — where a connection whose attach answered stays open. In-VM, the dispatcher's `attachments` map (`event_dispatcher.ex:154`, `:823`), read @@ -3420,10 +3475,14 @@ a codec, which cost every other frame's tracing. The match-specification list is not dropped; it is half the call, and the process flag is the other half, because a list of `{module, function, arity}` identities cannot cover what an excluded function *calls*: a traced `:gen_tcp.send/2` shows the credential -frame however this adapter's own functions are patterned. **Two plain fields on the runtime-side create and resume results** — which unify +frame however this adapter's own functions are patterned. **Two plain fields on two new runtime-side functions beside create and resume** — which unify nothing and add no wire surface: they exist because core computes `fresh?` at `control.ex:895` and then throws it away four lines later, leaving every -caller unable to tell a fresh create from a replay. Direct code cannot supply +caller unable to tell a fresh create from a replay. They are new functions +rather than widened returns because widening `create_session/3` would change +what `Loopex.create_session/3` forwards to a released embedded caller +(`loopex.ex:87-91`), which is a compatibility break bought for a daemon's +bookkeeping. Direct code cannot supply them, because the only alternative is inferring the answer from side effects, which is a race. **One bounded `quiesce/1`** — which unifies nothing today and says so: its only caller is the daemon's orderly stop, and the app-server host does not diff --git a/docs/plans/M5.md b/docs/plans/M5.md index a9837a60c..81920f29e 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -48,9 +48,11 @@ process that releases its attachment when that process ends; one read-only query that answers whether a session ID exists durably in the root; `Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion accepted ADR 0030 names and the process-level exclusion its callees need, before any message is delivered; `quiesce/1`, the bounded settle an orderly stop -drains through; and two plain fields on the **runtime-side** create and resume -results — `disposition`, saying whether the call was fresh or a replay, and -`control_entry`, saying whether core's `Control` holds that session as active +drains through; and two plain fields on **two new runtime-side functions beside** create and +resume — `create_session_detailed/3` and `resume_session_detailed/3`, so the +existing pair keeps its exact return and the embedded facade forwards what it +forwards today — `disposition`, saying whether the call was fresh or a replay, +and `control_entry`, saying whether core's `Control` holds that session as active or dormant at the instant of the call. `control_entry` is deliberately not called `residency`: that word is a **daemon** fact on the wire, about this daemon's lifetime, and the two differ exactly when `Control` still lists a From 051aa2ecb17eb816695c18222a218a81fc4e46f9 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:11:15 -0700 Subject: [PATCH 125/585] adr(M5): complete generation 2's control gate, release and renewal B8. Three gaps in the generation-2 wire would each have been found at implementation time, by a writer with no answer to look up. ADR 0033 required six refusals before core entry -- stale epoch, copied current epoch, non-holder connection, released lease, expired lease, observer mutation -- and named the code for none of them, while ADR 0032's error table had no row for the combined mutation gate at all. There is now one answer, `control_not_held`, and it is deliberately **non-oracular**: the five conditions are indistinguishable on the wire, because telling a caller which one it failed tells it whether a lease exists, whether its epoch was right and whether it was merely late -- an oracle for the value the gate protects. The witnesses assert the six cases separately in daemon state and assert one code on the wire, which is what stops a later revision helpfully differentiating them. `session.release_control` carried `writer_epoch` in ADR 0032's DTO table and not in ADR 0033's method list. It carries it in both. Acquire refused `control_held` for any held lease while another clause said the holder renews through acquire, and nothing said which branch a holder's own acquire took. The renewal branch is specified: same holder connection, same epoch, moved deadline, and a `renewed` field so a client can tell a renewal from a grant without comparing an opaque value. And `daemon.status`'s counts are defined while a reservation is in flight -- a reservation counts, so `activations_used` is the quantity the ceiling invariant bounds and never advertises headroom the next call would refuse. --- ...tachment-residency-and-replay-technical.md | 42 ++++++++++++-- ...controller-lease-and-takeover-technical.md | 56 ++++++++++++++++--- docs/plans/M5-technical.md | 2 +- 3 files changed, 86 insertions(+), 14 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 89f102200..45dd456f9 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -241,6 +241,26 @@ no content, no durable session state. | result | `index_full` | bool | required | | result | `uptime_ms` | `u64` | required | +**What the counts mean while a reservation is in flight**, which an earlier +revision left to the implementation and which two clients calling +`daemon.status` during a burst of creates would otherwise disagree about. +The rule is that **a reservation counts**: + +- `activations_used` is `|activation set| + |reservations|` — the same + quantity the ceiling invariant bounds, so `activations_used` and + `activation_limit` are directly comparable and a client can never read + `activations_used < activation_limit` on a daemon that would refuse its next + create; +- `active_sessions` is `|activation set|` alone — sessions with a coordinator + now, which is a different question and is why the two fields both exist; +- `attachments` counts installed attachments plus reserved attachment slots, + for the same reason `activations_used` does; +- `connections` counts accepted connections, reservation-free by nature. + +So `activations_used` may exceed `active_sessions` for as long as a call is in +flight, and settles to it. Reporting the set alone would advertise headroom +the very next call would refuse. + **`session.acquire_control`** | Direction | Key | Type | Optionality | @@ -248,6 +268,13 @@ no content, no durable session state. | request | `session_id` | binary identity | required | | result | `writer_epoch` | binary identity, ≤ 64 bytes | required | | result | `expires_in_ms` | `u64`, the remaining term on the daemon's clock | required | +| result | `renewed` | bool | present **exactly when** the caller was already the holder of a held, unexpired lease | + +A holder's own `session.acquire_control` is a **renewal**, not a refusal: the +deadline moves, the epoch stays, `writer_epoch` is the same value it held and +`renewed` is `true`. ADR 0033 owns the branch; the field is here so a client +can tell a renewal from a fresh grant without comparing epochs it treats as +opaque. **`session.release_control`** @@ -277,7 +304,7 @@ errors answering one request: each carries that request's `request_id`, no | Code | Answers | Carries beyond the envelope | | --- | --- | --- | | `control_held` | `session.acquire_control` | **Nothing.** It does *not* carry the current epoch: an epoch is authority-shaped, and handing one to a client that was just refused is exactly the value it must not have. An earlier revision of ADR 0033 said it named the current epoch; that is withdrawn | -| `control_not_held` | `session.release_control` from a non-holder | nothing | +| `control_not_held` | `session.release_control` from a non-holder, **and every lease-authorized existing-session mutation whose combined admission gate fails** — wrong connection, wrong epoch, released lease, expired lease, or an attachment without controller capability | **Nothing**, deliberately: the five conditions are indistinguishable on the wire, because saying which one failed would make the refusal an epoch and lease oracle. ADR 0033 fixes the gate; this is the one answer it has | | `control_pending` | `session.acquire_control` that waited out its deadline | nothing | | `control_capacity_reached` | any lease operation beyond the 512 concurrent-owner cap | nothing | | `session_dormant` | `session.attach` | nothing | @@ -425,9 +452,16 @@ module can pin a digest, so each is fixed here rather than left to the implementation. Seven were underspecified in an earlier revision, and this is the whole of what was missing. -**`control_not_held`, the non-holder release.** `session.release_control` from -a connection that is not the current holder refuses with `control_not_held`. -It is distinct from `control_held`, which refuses an *acquisition* because +**`control_not_held`, the one answer the admission gate has.** It refuses +`session.release_control` from a connection that is not the current holder or +whose `writer_epoch` does not match, **and** every lease-authorized +existing-session mutation that fails ADR 0033's combined check on holder +connection, epoch, `held` state, unexpired deadline or controller-capable +attachment. One code for all of them, carrying nothing beyond the envelope: +the refusals a client can provoke must not tell it whether a lease exists, +whether its epoch was right or whether it was merely late, because that is an +oracle for the value the gate protects. It is distinct from `control_held`, +which refuses an *acquisition* because somebody else holds the lease, and from `control_owner_lost` below. The refusal changes nothing: the current holder's lease, epoch and deadline are untouched, which is the point — a release that could be issued by a non-holder diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index cbe2847d1..ada6b88b5 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -163,7 +163,9 @@ the local store's writer marker, unchanged. ### Methods and fields - `session.acquire_control` (`session_id`, `request_id`): grants control when - no lease is held, or when the held lease is released or expired; refuses + no lease is held, or when the held lease is released or expired; **renews** + it when the caller is the recorded holder of a held, unexpired lease — see + the renewal branch below; and refuses with `control_held` otherwise, **carrying no epoch** — an epoch is authority-shaped, and a client that was just refused control is the last one that should be handed the current one. An earlier revision of this sentence @@ -188,11 +190,27 @@ the local store's writer marker, unchanged. held lease lets that connection call `session.resume` and then attach. Daemon startup recovery of sessions is a root-owner operation under the store's writer marker, never a client mutation and never a grant of controller authority. -- `session.release_control` (`session_id`, `request_id`): releases the - caller's own lease; a non-holder refuses. -- Renewal is implicit on any admitted command and explicit through - `session.acquire_control` from the holder, which extends the deadline - without changing the epoch. +- `session.release_control` (`session_id`, `request_id`, **`writer_epoch`**): + releases the caller's own lease. It carries `writer_epoch` like every other + lease-authorized call, and ADR 0032's DTO table is the contract for it; an + earlier revision of this line omitted the field the table already required, + which would have left two documents describing one request. A caller that is + not the recorded holder, or whose epoch does not match, refuses + `control_not_held` and changes nothing. +- **Renewal is a branch of `session.acquire_control`, and it has to be stated + because the refusal rule would otherwise swallow it.** Acquire from the + connection that **is** the recorded holder of a lease that is `held` and + unexpired is a **renewal**: the deadline moves to the full term from the + admission instant, the **epoch does not change**, and the result carries + that same `writer_epoch` with the new `expires_in_ms`. Acquire from any + other connection while such a lease exists refuses `control_held`. The two + branches are told apart by the connection identity alone — acquire carries + no epoch on the wire, and needs none, because the holder is recorded against + the connection. An earlier revision said both "refuses with `control_held` + otherwise" and "renewal is explicit through `session.acquire_control` from + the holder" without saying which clause a holder's own acquire took. + Renewal is also implicit on any admitted mutation, which extends the + deadline the same way and likewise never changes the epoch. - Every existing-session mutation in generation 2, including `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, `session.respond_interaction`, @@ -203,9 +221,29 @@ the local store's writer marker, unchanged. connection holds a controller-capable attachment, except that a verified dormant session's `session.resume` may precede attach under that connection's held lease. The check and core handoff are serialized against - lease transitions for the session. A mismatch or failed condition refuses - before core admission and before a session write; an observer who copied - the visible current epoch still refuses. Queries and attach carry no epoch. + lease transitions for the session. + + **Every way that gate can fail answers one code, `control_not_held`, and it + says nothing about which condition failed.** The gate has five conditions — + holder connection, epoch equality, `held` state, unexpired deadline, + controller-capable attachment — and an earlier revision required each of + them without naming the result any of them produces, which left the one + refusal a client actually meets undefined and ADR 0032's error table + incomplete. It is deliberately **non-oracular**: a stale epoch, a copied + current epoch, a non-holder connection, a released lease, an expired lease + and an observer's mutation are **indistinguishable on the wire**, because + telling a caller *which* condition it failed tells it something about the + lease it does not hold — whether one exists, whether its epoch was right, + whether it was merely late — and an epoch oracle is exactly what a refusal + must not be. It refuses before core admission and before any session write, + carries the request's `request_id` and nothing else, and changes nothing + about the current holder's lease, epoch or deadline. Queries and attach + carry no epoch and pass no gate. + + The witnesses assert the six refusals separately in the daemon's own state — + which condition each case constructed — and assert that all six are the + **same** code and the same fields on the wire, which is what stops a later + revision from helpfully differentiating them. - `session.create` has no `writer_epoch` because the session lease does not exist. It creates an uncontrolled session, and creation never implicitly grants control. The caller must acquire control explicitly and use the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index caa269c86..d7df64b7a 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -145,7 +145,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and every ticket it holds has settled or been recorded — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to settle or to be fenced under the drain, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — and a `session.create` sent after the cut refused the same way, which is the case that would fail if creates bypassed the relay; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state and unexpired term checked together before core admission or any durable write, including a known current epoch sent by an observer. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the six ways that gate fails asserted separately in the daemon's own state and asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch` and to refuse `control_not_held` without it. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | From f31931f6040764e1027f562b5d7f687eff33caf1 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:12:33 -0700 Subject: [PATCH 126/585] adr(M5): make the tracing capability mandatory and redact the token B9. The capability was optional and its omission proved nothing. Every runtime starts its own tracer unconditionally as the supervisor's last child (`runtime/supervisor.ex:86-89`), and any holder of the runtime reference can start a session on it, the tracer being resolved dynamically on every call (`runtime.ex:343-348`). "The host composed no capability" therefore says nothing about whether a session is running -- only that the sender cannot exclude itself from one. It is now mandatory wherever a `:credential_token` is configured: missing or malformed refuses at composition, unbound or unreachable refuses the invocation with `:unavailable` before the token is routed. This reverses the earlier "absent proceeds" rule, which is recorded as what it was -- the one case where the credential would have been resolved in a process a session may have been tracing. The absolute no-trace claim is narrowed to what it can carry. Credential bytes are covered unqualified, because the sender excludes itself before it holds them. The **token** is not: it sits in model `options` and reaches the adapter as the second argument of `module.complete(request, options, progress)` (`session_coordinator.ex:3231`), inside a traced coordinator and before the sender process exists. Nothing about ordering fixes that, so the token is covered by redaction instead -- and redaction does not reach it today. `Entry` keys off a map key and `@credential_pattern` does match `token` (`entry.ex:25`, `:140-146`, `:220`), but a keyword list goes through `redact_list/4`, which passes `nil` for every element (`:206-218`) and then through the tuple clause, again `nil` (`:153-158`), so the key never reaches `credential_key?/1`; a 16-byte token id renders verbatim under the 64-byte threshold at `:148`. Core change 3 therefore carries one further generic `Entry` clause -- a `{key, value}` pair in a list is redacted under its key, as the same pair in a map already is -- which closes every keyword list and names no adapter type. Its witness is the pair that must differ. --- ...andoff-over-bootstrap-channel-technical.md | 98 +++++++++++++++++-- docs/plans/M5-technical.md | 8 +- docs/plans/M5.md | 5 +- 3 files changed, 96 insertions(+), 15 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 5ab1a9612..7f9cf6f99 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -333,6 +333,57 @@ boundary, not an absolute: functions a host names — including `:gen_tcp`, including modules nobody has thought of. + **That promise is about credential bytes, and it begins at the exclusion + point**, which an earlier revision stated absolutely and therefore stated + too widely. The **token** reaches the sender by travelling somewhere the + exclusion cannot cover: it sits in the model configuration's `options`, and + the coordinator hands those options to the adapter as the second argument of + `module.complete(request, options, progress)` + (`session_coordinator.ex:3231`) — inside a **coordinator**, a process the + runtime owns and `:set_on_spawn` therefore traces, and **before the sender + process exists at all**. A session that names the adapter module sees that + call. There is no ordering that fixes it: the token has to arrive before the + sender can exclude itself on its behalf. + + So the token is covered by **redaction**, not by exclusion, and this pair + says which rather than letting the absolute claim imply otherwise: + + - the **credential bytes** never appear in any trace message, because the + sender excludes itself before it holds them — that is the claim above, and + it is unqualified; + - the **token** may appear in a raw trace message for `complete/3`, and what + keeps it out of an **entry** is `Loopex.Trace.Entry`'s credential + redaction — which today does not reach it. + + **The gap is exact, and closing it is part of core change 3.** `Entry` keys + its redaction off a map key: `redact/3` placeholders any value whose key + matches `@credential_pattern` — which does match `token` + (`entry.ex:25`, `:140-146`, `:220`). But `options` is a **keyword list**, + and a keyword list reaches `redact_list/4`, which walks every element with + the key argument `nil` (`entry.ex:206-218`) and then redacts each + `{key, value}` pair through the tuple clause, again with `nil` + (`entry.ex:153-158`). The key never reaches `credential_key?/1`. A + `%Loopex.LLM.ReqLLM.CredentialToken{id: <<16 bytes>>}` under + `credential_token:` is therefore rendered **verbatim** today: the struct's + own field is `id`, which matches nothing, and sixteen bytes is under the + 64-byte binary threshold at `entry.ex:148`. + + So core change 3 carries one further clause in `Entry`, and it is generic + rather than about this adapter: **a `{key, value}` pair inside a list is + redacted with `key` as its key** when `key` is an atom or a binary, exactly + as the same pair inside a map already is. That is the missing half of a rule + `Entry` already has, it closes every keyword list — `api_key:`, + `authorization:`, anything under 64 bytes — and it names no module core is + not allowed to know about. With it, the token renders as a `credential` + placeholder, and this pair's option key is `:credential_token` precisely so + that it does. + + Its witness is the pair that must differ: `Entry.render/2` over a keyword + list carrying a `%CredentialToken{}` under `:credential_token` produces no + occurrence of the token's bytes, while the same token under a key naming + nothing does — so a case cannot pass because the value was short, absent or + never rendered. + **The process half, probed at both toolchain pairs before it was written down.** A process flagged by inheritance (`:set_on_spawn` from a traced parent) calls `:trace.process(session, self(), false, [:all])`; the call @@ -417,11 +468,32 @@ boundary, not an absolute: be the one case where a credential is resolved in a process a session may be tracing. - **Only an explicitly absent capability proceeds.** Where the host composed - no tracing capability at all, there is no tracer and no session, so nothing - can trace and the sender resolves normally. Absent is not the same as - unreachable, and the two are distinguished at composition rather than at - the call. + **The capability is mandatory wherever a credential token is configured, + and an absent one refuses.** An earlier revision of this pair let an + explicitly absent capability proceed, on the reasoning that a host which + composed no tracing capability has no tracer and no session, so nothing can + trace. That reasoning does not hold against the tree. **Every runtime starts + its own tracer**: it is the runtime supervisor's last child, started + unconditionally (`runtime/supervisor.ex:86-89`), and **any holder of the + runtime reference can start a session on it** through + `Loopex.Runtime.trace/2`, which resolves the tracer dynamically on every + call (`runtime.ex:343-348`). So "the host composed no capability" proves + nothing about whether a session is running; it proves only that the sender + has no way to exclude itself from one. Omission was safety made optional, + and the thing it protects is present in every runtime there is. + + So the rule is one rule, and there is no absent branch: **a model + configuration that carries a `:credential_token` must carry a tracing + capability**, and one that is **missing, malformed, unbound, or present but + unreachable** fails the invocation with `:unavailable` **before the token is + routed** — before any lookup, before custody is reached, before a byte + exists in the parent. Missing and unreachable now differ only in when they + are caught: a missing or malformed capability is refused at **composition**, + where every other malformed option is, so an unbound one cannot reach a + call; an unreachable one is the per-invocation refusal above. This reverses + the earlier decision, and the earlier decision is recorded here as what it + was: a case in which the credential would have been resolved in a process a + session may have been tracing. **The MFAs this adapter supplies, exactly three.** They are the functions that hold the resolved bytes or the token, and the list is passed to @@ -493,13 +565,19 @@ boundary, not an absolute: while a sender is alive and empty after it exits, which is what separates "the monitors work" from "the set was never populated". - **It fails closed.** Surface: the invocation's own result, plus the child's - record of what it received. With the tracer made unavailable at the instant + **It fails closed, on every way the capability can be missing.** Surface: the + invocation's own result, plus the child's record of what it received. With + the tracer made unavailable at the instant `exclude_self/2` is called, the invocation is asserted to refuse `:unavailable` and the child is asserted to have received **no** credential - frame; with the capability explicitly absent, the same invocation is - asserted to succeed and the child to receive one. Two configurations, two - different answers on the same two surfaces. + frame. With the capability **absent** from a configuration that carries a + token, and again with one **bound to a dead process**, the same two + assertions hold — the refusal and the empty child — where the earlier + revision asserted the opposite for the absent case. The two answers that + must differ are therefore the refusal and an ordinary success, and the + success case is a **complete** configuration, which is the only one there + is. A composition given a token and no capability is asserted to refuse at + **composition**, so no call reaches the per-invocation branch at all. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d7df64b7a..2bd843719 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -148,7 +148,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the six ways that gate fails asserted separately in the daemon's own state and asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch` and to refuse `control_not_held` without it. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -343,7 +343,7 @@ core-internal states a daemon cannot construct through the socket. | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | | **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | -| **`Loopex.Trace.exclude_self/2` and `Control`'s excluded-pid set** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits` | fast | +| **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | The paused-transaction case in `runtime_quiesce_test.exs` pauses the transaction through core's own controllable store, not the shipped adapter: @@ -2929,7 +2929,7 @@ nothing proves. Each is named where it is used: | --- | --- | --- | | The dispatcher's release on `DOWN` | Core change 1 | The concurrent-attachment cases and the attach connection-loss case | | The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | -| `Control`'s excluded-pid set | Core change 3 | The trace-exclusion cases | +| `Control`'s excluded-pid set, and `Entry`'s redaction of a keyword pair under its own key | Core change 3 | The trace-exclusion cases, and the render pair that must differ | | `quiesce/1`'s three lists, `budget_ms`, `drain_id` and the per-session `fences` map | Core change 4 | The drain cases, the fence cases and the stop line | | `disposition` and `control_entry`, on `create_session_detailed/3` and `resume_session_detailed/3` | Core change 5 | The create and resume connection-loss cases, and the case asserting `create_session/3`'s own return is byte-identical to today's | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 81920f29e..7d8d4b087 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -47,7 +47,10 @@ therefore has to add what removes one instead, a monitor on the attaching process that releases its attachment when that process ends; one read-only query that answers whether a session ID exists durably in the root; `Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion accepted ADR 0030 names and the -process-level exclusion its callees need, before any message is delivered; `quiesce/1`, the bounded settle an orderly stop +process-level exclusion its callees need, before any message is delivered, +together with the one `Loopex.Trace.Entry` clause that redacts a keyword +list's values under their own keys, which is what keeps the credential token +out of an entry on its way to the adapter; `quiesce/1`, the bounded settle an orderly stop drains through; and two plain fields on **two new runtime-side functions beside** create and resume — `create_session_detailed/3` and `resume_session_detailed/3`, so the existing pair keeps its exact return and the embedded facade forwards what it From a75603f47c77e5bf245aa672e61872ee0d6c96c7 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:14:47 -0700 Subject: [PATCH 127/585] plan(M5): archive inventory, signal routes, startup-failure matrix B10. The archive's unchanged-tree check hashed "the extracted tracked source paths", and *tracked* is a fact held in `.git`, which `git archive` does not produce. The extraction now carries a tracked `SOURCE_INVENTORY` generated from `git ls-files -z` when the archive is staged, and the check compares **both** the path set -- so a file created during the build is caught even when every named file is byte-identical -- and the bytes, with exactly one named exclusion, `_build/` and `deps/`, retained with the evidence so a later exclusion cannot quietly widen what unchanged means. Its witness is the one an inventory-free check could not have: a file created inside the extraction and outside those roots, asserted to refuse. An empty inventory is itself a refusal, so a check that enumerated nothing cannot read as a pass. B11. The plan gave `SIGHUP` and `SIGQUIT` default meanings without naming a route, while `bin/loopex:51-60` traps `INT TERM HUP QUIT` and forwards every one as `kill -TERM`. The contract is now a table by signal and entry point: through the launcher all four begin the orderly stop, and directly to the escript only `SIGTERM` does, `HUP` and `QUIT` keeping the emulator's default and `SIGINT` staying unspecifiable because `:os.set_signal/2` refuses it (`interrupt.ex:13-17`). Eight witnesses, one per signal per route, replace the two. Changing the launcher was available and is rejected: it would change what `loopex run` does on `SIGHUP` in the same edit. B12. Three passages gave three answers about what a failed start leaves. One closed a bound socket, left its path and removed the `daemon/` subdirectory -- which cannot both happen, a directory holding a socket not being empty -- and two witnesses asserted no socket file where the no-unlink witness asserted one. One matrix now decides it on the bind: before it, nothing is bound so nothing is left, and a subdirectory this start created is removed only when empty; at or after it, the pathname and the directory both stay, like every other exit path. The three witnesses are split to match, and the two that now assert opposite things assert them for different failures. --- docs/plans/M5-technical.md | 155 +++++++++++++++++++++++++++++-------- docs/plans/M5.md | 6 +- 2 files changed, 128 insertions(+), 33 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 2bd843719..28c510e2f 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -635,13 +635,41 @@ and one shared resolver they both call: a hand-written one looks like, since anything but one lowercase 40-character hexadecimal commit id and a commit date is refused; or the extracted tree **changed during the build**, which is the property `git status` buys in a - checkout and which the resolver proves here by a SHA-256 over the extracted - tracked source paths, sorted, taken before the build and again after and - required equal; + checkout and which the resolver has to buy some other way here, because an + extraction has no git index to ask what is tracked; - the provider build manifest embeds the resolved commit id together with that source digest, so an identity naming a commit whose tree is not what was built is detectable rather than merely trusted. +**The unchanged-tree check needs an inventory, because an extraction has no +index.** An earlier revision said the resolver hashes "the extracted tracked +source paths" — but *tracked* is a fact held in `.git`, and `git archive` +leaves none, so there is nothing to enumerate and the check would either +compute over an empty set or fall back to a glob nobody stated. The archive +therefore carries the enumeration with it: + +- a tracked **`SOURCE_INVENTORY`** file, generated from + `git ls-files -z` at the moment the archive is staged and written as the + sorted list of every path in it, so the extraction holds the same answer the + checkout would have given; +- **both** halves are compared, before the build and again after: the **path + set**, so a file created or deleted during the build is caught even if every + file it names is byte-identical, and the **bytes**, as a SHA-256 over each + path's contents in inventory order; +- exactly **one** exclusion, named rather than implied: the build-output roots + `_build/` and `deps/`, which the build is supposed to create. Nothing else + is excluded, and the list of exclusions is part of the retained evidence, so + a later exclusion cannot quietly widen what "unchanged" means. + +Its witness is the one an inventory-free check could not have: a file is +created **inside the extraction and outside the excluded roots** during the +build, and the resolver is asserted to **refuse** with the changed-tree +reason — where the same build without it succeeds. An empty or missing +`SOURCE_INVENTORY` is itself a refusal, on the same rule as an unsubstituted +identity, so a check that enumerated nothing cannot read as a pass. The +inventory, the exclusion list and both digests are retained with the closure +runs beside the archive's own SHA-256. + The **mismatch** case is proved where the external truth exists: the release check stages the archive with `git archive` from a known commit, retains the archive's SHA-256 and that commit, and asserts that the identity the @@ -762,11 +790,13 @@ a client to connect to a socket the daemon has not finished checking. Every diagnostic, warning and failure goes to `stderr`, so `stdout` carries the readiness line alone and stays machine-readable. -**Stopping.** **`SIGTERM`** begins the orderly shutdown below — or `SIGINT` -through the launcher, `apps/loopex_cli/bin/loopex`, which forwards it as -`SIGTERM`. The daemon itself installs no `SIGINT` handler and cannot: the +**Stopping.** Sent **to the escript**, `SIGTERM` begins the orderly shutdown +below and is the only signal that does. Sent **to the launcher**, +`apps/loopex_cli/bin/loopex`, **any of `INT`, `TERM`, `HUP` or `QUIT`** does, +because the launcher traps all four and forwards `kill -TERM` to its child. +The daemon itself installs no `SIGINT` handler and cannot: the emulator reserves that signal and `:os.set_signal/2` refuses the name, as the -signal section below sets out. +signal section below sets out with the full route-by-signal table. There is no `daemon.stop` method on the wire: stopping is an operator act against the process, and a client-issued stop would let one connection end every other client's session residency, which is authority the socket does not @@ -1888,9 +1918,37 @@ died on `SIGHUP` would exit when the terminal that happened to start it closed — which for a background service is a defect rather than a courtesy. `SIGQUIT`'s default is a core dump, and taking it over to do a graceful stop would take away the one signal an operator has for "stop and leave me a dump". -So the daemon handles `SIGTERM`, leaves `SIGHUP` and `SIGQUIT` at their -defaults, and the witnesses cover `SIGTERM` and the launcher's forwarded -`SIGINT` only. +So the daemon handles `SIGTERM` and leaves `SIGHUP` and `SIGQUIT` at their +defaults. + +**The contract therefore depends on the entry point, and the plan says so +rather than giving one answer for two different processes.** It has to, +because `apps/loopex_cli/bin/loopex` traps **`INT TERM HUP QUIT`** and +forwards every one of them to its child as `kill -TERM` +(`bin/loopex:51-60`) — so what a signal means is decided by whether it lands +on the launcher or on the escript: + +| Signal | Sent to the **launcher** | Sent to the **escript** directly | +| --- | --- | --- | +| `SIGINT` | Orderly stop: forwarded as `SIGTERM` | Not this plan's to specify — `:os.set_signal/2` refuses `:sigint` (`interrupt.ex:13-17`) and the emulator's break handler owns it | +| `SIGTERM` | Orderly stop: forwarded as `SIGTERM` | Orderly stop: the one signal the daemon installs a handler for | +| `SIGHUP` | Orderly stop: forwarded as `SIGTERM` | The emulator's default — the daemon installs nothing, for the reason above | +| `SIGQUIT` | Orderly stop: forwarded as `SIGTERM` | The emulator's default, a dump | + +So "the daemon dies on `SIGHUP` when its terminal closes" is false through the +escript and **true through the launcher**, which is the shipped path — and +that is the launcher's existing behaviour, deliberately left alone. An +earlier revision of this section gave `SIGHUP` and `SIGQUIT` one meaning each +without naming a route, which contradicted the launcher for two of the four. +**Changing the launcher was the alternative and is rejected**: it forwards +all four as `TERM` for every `loopex` command, that behaviour is released, and +narrowing it for the daemon's sake would change what `loopex run` does on +`SIGHUP` in the same change. + +The witnesses are **one per signal per route** — eight cases, four of which +assert an orderly stop and four of which assert the entry point's own +behaviour — rather than the `SIGTERM`-and-forwarded-`SIGINT` pair an earlier +revision listed. For `SIGTERM` the daemon does what the CLI already does, and reuses the same mechanism rather than inventing one: @@ -2887,7 +2945,8 @@ step unwinds what that step and its predecessors did, in reverse — and "predecessors" means **every process the startup started**, not the three an earlier revision named. A bound socket is **closed, and its path left in place** — reverse cleanup unlinks nothing, for the same reason no shutdown -path does — a `daemon/` subdirectory the owner created is removed — no lease owner can exist +path does — a `daemon/` subdirectory this start created is removed **when it +is empty**, by the matrix below — no lease owner can exist yet, since none is started before a session is activated — and **every pid the composition function returned is stopped in reverse start order** — runtime, executor, workspace lease, transfers where it exists @@ -2908,8 +2967,27 @@ The owner does this in its own start path rather than leaving it to a crash, because a crashing owner would take the links down without releasing the marker or removing the directory it made. A daemon that refuses to start leaves **no marker held** — which is what lets an operator fix the cause and -try again without a recovery step — and may leave a socket pathname, which the -next daemon removes before binding. +try again without a recovery step. + +**What a failed start leaves on disk is one matrix, because three passages +gave three answers.** One said a bound socket is closed with its path left in +place while the `daemon/` subdirectory is removed — which cannot both happen, +a directory holding a socket file not being empty. Two witnesses then asserted +"no socket file exists afterwards" while the no-unlink witness asserted the +opposite for the same failure. The rule is the bind: + +| Where the start failed | Socket pathname | `daemon/` subdirectory | +| --- | --- | --- | +| **Before the bind** — path resolution, signal install, the registry, custody or capability, composition and the marker, the index read, the subdirectory create | **None exists**; nothing was bound, so nothing is left | Removed **only if this start created it and it is empty**; a subdirectory that was already there, or that holds anything, is left exactly as found | +| **At or after the bind** — the permission read-back, the accept, the readiness write, or any component dying during those | **Left in place**, closed but not unlinked, like every other exit path | **Left in place**, because it holds that pathname | + +Both halves follow from one rule already stated and one plain fact: **no +predecessor path ever unlinks**, so a bound socket's pathname survives a +failed start exactly as it survives a stop; and a directory holding a file +cannot be removed, so the subdirectory removal is conditional on there being +nothing in it. A daemon that refuses to start may therefore leave a socket +pathname, which the next verified marker holder removes before binding, and +that is the one thing it leaves behind. **Witnesses.** Most run a real daemon operating-system process; a few read state no surface exposes and run **in-VM**, in the same VM as the daemon or @@ -3098,8 +3176,11 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. its correctness. After an **orderly stop**, the pathname is still on disk and `connect` to it fails as refused rather than hanging; the next daemon removes it, binds and serves. After a **store-loss fail-stop**, the same. - After a **failed start** — the marker acquired and the socket bound, then - the index bound exceeded — the same again, with no marker held. + After a **failed start at or after the bind** — the marker acquired and the + socket bound, then the permission read-back refused — the same again, with + no marker held. The index-bound failure is **not** this case and is asserted + the other way in the reverse-cleanup witness, because it happens before the + bind and there is no pathname to leave. The race the old design had is then run directly: the first daemon is held at the instant it would have unlinked, its Store is killed so the marker is @@ -3112,18 +3193,23 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. that is otherwise perfectly valid — right owner, right mode — but outside the selected root's `daemon/` directory exits `invalid_socket_path` with no marker taken, no socket bound and nothing left behind. -- **Signals, one case per delivery route.** `SIGTERM` sent to the daemon - process itself begins the orderly sequence; `SIGINT` is sent **to the - launcher**, `apps/loopex_cli/bin/loopex`, which forwards `SIGTERM` to the - child, because `:os.set_signal/2` refuses `:sigint` and a `SIGINT` sent to - the daemon process directly is not this plan's to specify. Each case names - which process it signals. A third asserts the install order: a `SIGTERM` +- **Signals, one case per signal per route, and the route is what decides.** + Four cases send `INT`, `TERM`, `HUP` and `QUIT` **to the launcher**, + `apps/loopex_cli/bin/loopex`, and each asserts the **orderly sequence** — + because the launcher traps all four and forwards `kill -TERM` + (`bin/loopex:51-60`), so through the shipped path all four mean stop. Four + more send the same signals **to the escript process itself**: `TERM` asserts + the orderly sequence, and `HUP` and `QUIT` assert the emulator's own + behaviour with **no** orderly stop — no `daemon.stopping` record, no drain — + which is what makes "the daemon installs on `SIGTERM` and nothing else" a + checked claim rather than a preference. `SIGINT` to the escript has no case + and states why: `:os.set_signal/2` refuses `:sigint` (`interrupt.ex:13-17`) + and the emulator's break handler owns it, so there is nothing of this plan's + to assert. Every case names which process it signals, which is the whole + point of the pair. A ninth asserts the install order: a `SIGTERM` delivered before startup completes ends a daemon that holds no marker and has bound no socket, proved by a following daemon starting with nothing to - recover. There is **no `SIGHUP` or `SIGQUIT` case**, because the daemon - installs on neither: the case list matches the handler set, and a case for a - signal nobody handles would be a case for the default behaviour of the - emulator. + recover. - **`owner_lost`, by the monitor and not by a later signal.** The owner is killed while the daemon is otherwise healthy and **nothing else happens**: no signal is sent. The case asserts the process halts non-zero with @@ -3154,8 +3240,9 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. makes observable. That third case asserts the function returns `{:error, reason, started}` naming every edge it had started, and that reverse cleanup stops exactly those. Each case asserts **no readiness line is printed**, that no marker is - held and no socket file exists afterwards, and that a following daemon - starts cleanly with nothing to recover. A third kills the Store immediately + held, that what is left on disk matches the startup-failure matrix for where + it stopped — no pathname for the two pre-bind cases — and that a following + daemon starts cleanly with nothing to recover. A third kills the Store immediately after the composition call returns and asserts the start aborts into reverse cleanup rather than binding a socket and announcing readiness on top of a dead component. @@ -3328,10 +3415,16 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. reservation state directly rather than through any wire method — no DTO field exposes it, and none is added — so a branch that leaked a reservation shows up as a daemon that refuses early rather than as a silent drift. -- **Reverse cleanup.** A startup made to fail after the marker is acquired — - at the socket permission check and at the index bound, separately — leaves - no marker held and no socket file behind, proved by a second daemon starting - cleanly on the same root with no recovery step. +- **Reverse cleanup, on both sides of the bind.** A startup made to fail + **before** the bind — at the index bound, after the marker is acquired — + leaves no marker held, **no socket pathname** and no `daemon/` subdirectory + it created. A startup made to fail **at or after** the bind — at the socket + permission read-back — leaves no marker held, **the socket pathname in + place** and the subdirectory with it. Both are proved by a second daemon + starting cleanly on the same root with no recovery step, and the two + assertions about the pathname are opposite, which is the point: an earlier + revision asserted the same answer for both and contradicted the no-unlink + rule for one of them. - **Readiness ordering.** A client that connects the instant the readiness line appears is served; no readiness line is printed when the marker is held elsewhere, the socket permission check fails, or the index bound is diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 7d8d4b087..06923ae09 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -346,8 +346,10 @@ makes its operator contracts part of the milestone rather than an afterthought, so M5 fixes them. `loopex daemon` selects a root and a socket, prints exactly one readiness line on standard output — and only once the marker is held and the socket is bound and permission-checked — sends everything else to standard -error, stops on `SIGTERM` — or on a terminal `SIGINT`, which the launcher -forwards as `SIGTERM`, since the emulator reserves that signal — and exits `0` +error, stops on `SIGTERM` sent to it directly — and on any of `INT`, `TERM`, +`HUP` or `QUIT` sent to the launcher, which forwards all four as `SIGTERM`, +the route a terminal `SIGINT` takes since the emulator reserves that +signal — and exits `0` for an operator stop or non-zero with a named reason class for a fatal one. There is no stop method on the wire, because ending every client's session residency is not authority a From 8b9786215900409f6ac8685dc3f2dec6061980fd Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:19:18 -0700 Subject: [PATCH 128/585] plan(M5): nine material corrections across the set 1. The read-only marker query is gone from ADR 0031 and from the concept plan's rollback sentence; the lifecycle section deleted it two rounds ago with the unlink it existed for, and two documents still promised the adapter a call it does not get. 2. ADR 0033-technical still said a lease owner's failure "takes the daemon with it", three paragraphs above the section that makes it session-scoped. 3. The stop driver had two rules for one exit. The `stopping` field consumed any exit from the named pid; step 4 classified every reason but `:normal`, `:shutdown` and the owner's own `:killed`. The transfers witness -- a `terminate/2` that raises during a stop the owner asked for, asserted `transfers_lost` -- fails under the first and passes under the second. Reason decides; the field only says whose `:killed` was the owner's doing. 4. The fixed-process table headed eleven rows "ten". It is the owner and the ten it links, ten without transfers, and the heading says so. 5. Dormant meant "the index records it and this daemon has not", which left a session past the 4,096-entry ceiling neither active nor dormant and made the listing bound read as a bound on reachability. Dormant is durably present and not activated; indexing decides only what `session.list` shows. 6. ADR 0032-technical still listed core change 5 as `disposition` and `residency`; it is `control_entry`, on the detailed functions. 7. 69,632 is the credential frame's **payload** cap -- `@semantic_bytes + @envelope_bytes` at `provider_codec.ex:53-54`, `:80` -- and the wire frame is eight bytes longer for the header `encode/2` prefixes at `:92`. 8. The startup sequence started the registry and custody at step 3 and left the tracing capability to be inferred from a table, although it is one of the ten links and must exist before the model options are built. 9. The `Control` restart qualification named only the tracer. `Control` is the root's second child under `:rest_for_one` (`supervisor.ex:64-90`, `:92`), so its restart carries the workers, the owner groups, the sessions, the dispatcher and the tracer -- every live coordinator, not merely every trace session. The fail-closed witness that constructs one now asserts that cost. --- ...mon-grade-store-selection-and-migration.md | 4 +- ...tachment-residency-and-replay-technical.md | 19 +++++-- ...-daemon-attachment-residency-and-replay.md | 4 +- ...controller-lease-and-takeover-technical.md | 7 +-- ...andoff-over-bootstrap-channel-technical.md | 25 ++++++--- docs/plans/M5-technical.md | 52 ++++++++++++++----- docs/plans/M5.md | 16 ++++-- 7 files changed, 93 insertions(+), 34 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 7044f6f4d..a05d24b0b 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -71,7 +71,9 @@ what backup and restore, and which binary is the oldest reader of the new root their own ADR, proposed with the successor milestone's plan, accepted on its own review, declaring `Supersedes: 0031` for the selection this pair makes. Nothing about that work binds M5, and nothing in M5 forecloses it: the local -format and its ports are unchanged, and its adapter is unchanged in behaviour, gaining one read-only call that reports whether it still holds its marker, so any successor starts from +format, its ports and its adapter are unchanged — the adapter gains nothing at +all, the read-only marker query an earlier revision gave it having gone with +the unlink it was invented for — so any successor starts from exactly the root M5 leaves. **Alternatives rejected.** Deferring this decision out of M5 entirely was diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 45dd456f9..b5396de7f 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -840,9 +840,17 @@ byte position. ### Session residency: active, dormant, and their bounds A session is **active** when this daemon activated it in this lifetime and -**dormant** when the index records it and this daemon has not. Nothing durable -distinguishes the two, and neither is a claim about a live coordinator: both -are daemon facts, recorded when the daemon acted. +**dormant** when the root holds it durably and this daemon has not. Dormancy +is about activation and **not** about the index: a session the index does not +record — one past the 4,096-entry ceiling, or one whose directory entry was +never written — is dormant in exactly the same sense, and is reached by ID and +activated in exactly the same way. What the index controls is whether +`session.list` shows it, and nothing else. An earlier revision defined dormant +as "the index records it and this daemon has not", which made an unrecorded +session neither active nor dormant and made the listing bound look like a +bound on reachability, which this pair says twice that it is not. Nothing +durable distinguishes active from dormant, and neither is a claim about a live +coordinator: both are daemon facts, recorded when the daemon acted. A dormant session costs less than an active one, but not nothing, and the plan should not pretend otherwise. It holds one index row against the @@ -867,8 +875,9 @@ an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and none of M5's five core changes (concurrent attachment, the read-only existence -query, the trace exclusion, `quiesce/1`, and the create and resume results' -`disposition` and `residency` fields) stops a coordinator, +query, the trace exclusion, `quiesce/1`, and the `disposition` and +`control_entry` fields on the detailed create and resume functions) stops a +coordinator, so a deactivation call would be a further core change this milestone does not make. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index e0df29b9f..6ded2098f 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -114,7 +114,9 @@ missing durable event. Transient progress is coalesced or dropped first and never delays a journal transaction. A session is *active* when **this daemon activated it in this lifetime** and -*dormant* when the root records it and this daemon has not. Both are daemon +*dormant* when the root holds it durably and this daemon has not — whether or +not the daemon's index records it, indexing deciding only what `session.list` +shows. Both are daemon facts, true by construction; neither is a claim about a live coordinator, which the daemon has no way to know. Recovery is lazy: a restarted daemon activates nothing, reads its index, and activates a session when a client creates or resumes it. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index ada6b88b5..98a318d47 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -20,9 +20,10 @@ deadline (monotonic), state ∈ {held, released, expired} `writer_epoch` is an opaque string from ADR 0023's identifier alphabet, at most 64 bytes, carrying at least 128 bits of fresh randomness. It is minted -at every grant and never reused: not across grants to the same connection and -not across a restart of the daemon, which is the only restart that exists -because a lease owner's failure takes the daemon with it. Clients treat the epoch as opaque and compare it +at every grant and never reused: not across grants to the same connection, +not across the fresh owner a lease owner's death leaves behind — that failure +is **session-scoped**, as this pair sets out below — and not across a restart +of the daemon. Clients treat the epoch as opaque and compare it only for equality. The daemon incarnation is a fresh opaque identifier generated at each daemon start and reported by `daemon.status` as a diagnostic; it confers nothing and is not part of the epoch. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 7f9cf6f99..94a4070c1 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -20,7 +20,13 @@ The credential frame on that socket keeps the shape it has today. The codec carries an eight-byte header — `LP`, version 2, a closed kind byte and a length — and the `credential` kind admits exactly the two members `nonce` and `credential`, with the credential a non-empty binary of at most 65,536 bytes -and the frame capped at 69,632. Nothing about the frame changes; what changes +and the frame's **payload** capped at 69,632 — `cap(:credential)` is +`@semantic_bytes + @envelope_bytes`, 65,536 + 4,096 +(`provider_codec.ex:53-54`, `:80`) — with the frame on the wire eight bytes +longer than that, `encode/2` prefixing `<<"LP", version, code, length::32>>` +before the payload (`:92`). An earlier revision called 69,632 the frame cap, +which is the one number a reader sizing a buffer would get wrong. Nothing +about the frame changes; what changes is where its second member comes from. ### Ordering @@ -435,11 +441,18 @@ boundary, not an absolute: it skips every pid Control holds, the same place `excluded?/3` already excludes the tracer and the dispatcher by role (`trace.ex:411`), and a tracer that has just restarted asks Control rather than starting empty. - - **A `Control` restart is the one gap, and the claim is qualified rather - than repeated.** `Control` is a `:permanent` child under `:rest_for_one` - (`runtime/supervisor.ex:69-72`, `:92`), so its restart clears the set — - and also restarts every child after it, the tracer included, which ends - every live session. What that means precisely: the **process flags already + - **A `Control` restart is the one gap, and it is a runtime-wide event + rather than a tracing one.** `Control` is a `:permanent` child under + `:rest_for_one` and is the **second** of the root's seven children + (`runtime/supervisor.ex:64-90`, strategy at `:92`), so its restart clears + the set — and also restarts **every child after it**: the worker task + supervisor, the owner-group and session dynamic supervisors, the event + dispatcher and, last, the tracer (`:73`, `:74-77`, `:78-81`, `:82-85`, + `:86-89`). That ends every live trace session, and it also ends every + live **session coordinator**, which is the larger fact and the one an + earlier revision left out by naming only the tracer. A daemon meets it as + `runtime_lost` if the root does not survive, and otherwise as core's own + refusal on the next command for every session. What that means precisely: the **process flags already installed on live sessions persist**, being state in the VM's trace sessions rather than in `Control`; only sessions started **after** the restart consult the set, and those find it empty. A sender that resolved diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 28c510e2f..45fe8063d 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -333,7 +333,7 @@ Three of the five were witnessed only downstream — in the daemon's lifetime suite and the adapter's credential suite — and three of their properties cannot be reached from there at all: quiesce's `absent` branch needs a `Control` entry whose coordinator has already died (`control.ex:821-823`), -`exclude_self/2`'s fail-closed path needs the tracer mid-restart, and +`exclude_self/2`'s two fail-closed paths need the tracer mid-restart and `Control` mid-restart, and `Control` pruning an excluded sender needs that sender's `DOWN`. All three are core-internal states a daemon cannot construct through the socket. @@ -343,7 +343,7 @@ core-internal states a daemon cannot construct through the socket. | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | | **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | -| **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | +| **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | The paused-transaction case in `runtime_quiesce_test.exs` pauses the transaction through core's own controllable store, not the shipped adapter: @@ -1248,9 +1248,15 @@ runtime — rather than against a staged one the plan would have to invent: 2. **Install the signal handlers**, for the reason the signal section gives: before this, the default handler would stop the VM outright and strand whatever the next steps take. -3. **Start the credential routing registry and the custody process.** They are - the daemon's own, as ADR 0034's host, and they must exist before the model - configuration that carries the registry handle and the token is built. +3. **Start the credential routing registry, the custody process and the + tracing capability**, in that order. All three are + the daemon's own, as ADR 0034's host, and all three must exist before the + model configuration that carries the registry handle, the token and the + capability reference is built. The capability is listed here rather than + left to the process table: it is one of the ten links, ADR 0034 now makes + it mandatory wherever a token is configured, and a startup sequence that + named two of the three would have left the third's position to inference. + It is handed the runtime reference as soon as step 4 returns one. 4. **Call the composition function**, which opens the Store and acquires the writer marker with `recover_stale_writer: true` and the three holder outcomes ADR 0032 fixes, then assembles the artifact transfers owner where @@ -1630,15 +1636,27 @@ So the owner carries a `stopping` field naming **the one component it is currently stopping**, set immediately before each stop call. The EXIT clause reads: -- an exit from the pid named in `stopping`, while it is named, is **consumed** - and clears the field — it is the stop the owner asked for, arriving as a - signal; -- **every other exit is classified exactly as before**, including one from a +- an exit from the pid named in `stopping`, **whose reason is `:normal`, + `:shutdown` or the owner's own `:killed`**, is **consumed** and clears the + field — it is the stop the owner asked for, arriving as a signal; +- **every other exit is classified**, including one from the pid named in + `stopping` whose reason is none of those three, and one from a component not yet stopped that dies of its own accord *during* another component's stop. A store that fails while the listener is being stopped is still `store_lost`, and must be: the daemon is going down either way, but the operator is owed the real reason rather than `operator_stop`. +**The field narrows *which* exits can be consumed; the reason decides +*whether* one is**, and an earlier revision had the field deciding on its own. +That version consumed **any** exit from the named pid, which contradicts the +reason-sensitive rule four steps below and contradicts this file's own +witness: the transfers owner is made to raise inside its `terminate/2` during +a stop the owner asked for, and the case asserts `transfers_lost` rather than +`operator_stop`. Under "any exit from the named pid is consumed" that case +fails. The two rules are one rule now, stated here and applied at step 4 of +the stop driver: **reason first, and the field only says whose `:killed` was +the owner's doing.** + **The owner never calls `GenServer.stop/3` itself**, and the reason is a result an earlier draft did not have. Every previous version of this section put the call in the owner and tried to name the shapes it must catch. That @@ -3452,7 +3470,11 @@ owned by core, the adapter or the executor appears as a **group with its owner**, because their counts are those components' business and naming them individually would make this table a copy that rots. -**The daemon's fixed processes — ten, nine without transfers:** +**The daemon's fixed processes — eleven rows, ten without transfers: the owner +and the ten it links.** The count is stated that way because the table has one +more row than the link set does, the owner being the process that holds the +links rather than one of them, and an earlier revision headed eleven rows +"ten". | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | @@ -3478,9 +3500,13 @@ individually would make this table a copy that rots. | **Relay tasks**, one per ticketed mutation | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | **Core's processes, as groups with their owner.** The runtime root supervises -seven children under `:rest_for_one` (`runtime/supervisor.ex:66-92`): the tool +seven children under `:rest_for_one` (`runtime/supervisor.ex:64-90`, strategy +at `:92`), in this order: the tool registry, `Control`, a worker task supervisor, an owner-group dynamic supervisor, a session dynamic supervisor, the event dispatcher and the tracer. +The order is load-bearing under that strategy: a restart of the *n*th child +restarts every child after it, so `Control`'s restart takes the five beneath +it including every session coordinator, and the tracer's takes nothing. The daemon holds none of them and names none of them in its fatal map — it links the **root**, and a death anywhere beneath it that the root does not survive arrives as `runtime_lost`. @@ -3490,7 +3516,7 @@ survive arrives as `runtime_lost`. | **Session coordinators** | Core's session supervisor, `restart: :temporary` | One per active session | Core's own refusal on the next command; **no signal reaches the daemon and none is owed**. `quiesce/1` terminates and fences them at the drain deadline | | **Owner groups and their workers** | Core, beneath a coordinator | Per coordinator | Core's; a trapping owner group unwinds on its own clock and the daemon does not wait | | **Event dispatcher** | The runtime root | **One per runtime**, holding the per-attachment queues — not one per attachment, which an earlier revision of this table said | Restarted by the root under `:rest_for_one`, which restarts the tracer with it | -| **`Control`** | The runtime root | One per runtime | Holds the trace exclusion set and the session entries; its restart is the root's business, and it carries the tracer with it | +| **`Control`** | The runtime root | One per runtime | Holds the trace exclusion set and the session entries; it is the root's **second** child, so under `:rest_for_one` its restart carries the workers, the owner groups, the sessions, the dispatcher and the tracer with it — every live coordinator, not merely every trace session | | **Tracer** | The runtime root, **last** child | One per runtime | Restarts alone, changing pid, which is why nothing holds a tracer pid | **The adapter's and executor's processes, likewise:** @@ -3658,7 +3684,7 @@ line; M5 introduces none of its own. | Takeover grace beyond expiry | none; takeover is eligible at expiry and granted once the session's in-flight admission set is empty | ADR 0033 | | Writer epoch | opaque, at most 64 bytes, at least 128 bits of fresh randomness, minted per grant | ADR 0033 | | Credential size | 1 to 65,536 bytes | ADR 0019, unchanged by ADR 0034 | -| Credential frame cap | 69,632 bytes | ADR 0034, which is where the frame's shape is written; no ADR 0019 file states it | +| Credential frame **payload** cap | 69,632 bytes, the wire frame being eight bytes longer for its header | ADR 0034, which is where the frame's shape is written; no ADR 0019 file states it | | `req_llm` version pin | `~> 1.24.0` | Maintainer decision 4B of 2026-09-20, a **plan** decision. A dependency pin is not a contract number: it binds what this milestone builds against and is changed by an ordinary reviewed dependency change, not by an ADR amendment | **Four rows say 512 and they are four different bounds**, which is worth one diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 06923ae09..21ff2e41d 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -264,8 +264,9 @@ not M5's. No new store adapter, journal format version, migration or backup tooling enters M5. A daemon activates a session when a client creates or resumes it, not at startup — those are the two operations that start a coordinator, and acquiring control or attaching is neither. -Sessions the root records are dormant until then, and the daemon holds at most -a bounded number of active ones at a time. A dormant session costs what a +Every session the root holds durably is dormant until then — indexed or not, +since the index decides only what `session.list` shows — and the daemon holds +at most a bounded number of active ones at a time. A dormant session costs what a recorded session costs and no more: a row in the daemon's bounded index, itself capped at 4,096 entries, plus its journal and directory entry on disk. It runs no process, holds no attachment, no lease owner, no window and no @@ -744,7 +745,9 @@ The documented recovery is to retire the root — stop the daemon, move the root aside, start a fresh one — after which a session in the retired root is reached only by reopening that root. -The private journal and its format are unchanged, and its adapter is unchanged in behaviour — it gains one read-only call reporting whether it still holds its marker, and writes nothing new — so moving a +The private journal, its format and its adapter are unchanged — the adapter +gains no call and writes nothing new, the marker query an earlier revision +added having gone with the unlink it existed for — so moving a state root between the daemon and the foreground surfaces is stopping one and starting the other. That is also the rollback: dropping back to `0.1.0` means stopping the daemon and using the M4 foreground server and CLI on the same @@ -1031,8 +1034,11 @@ that one call. The excluded-pid set is held in `Control` and reached through a capability the host composes, since the tracer is the runtime's last child and is resolved dynamically. The credential-bearing process excludes itself before it resolves anything, and no trace *configuration* can name it back in — a -`Control` restart is the one event that clears the set, and it restarts the -tracer with it, so what it clears is a set no live session is still consulting; +`Control` restart is the one event that clears the set, and under +`:rest_for_one` it restarts every child after it — the workers, the owner +groups, the sessions, the dispatcher and the tracer — so what it clears is a +set no live session is still consulting, at the price of every coordinator +beneath it, which is a runtime-wide event rather than a tracing one; a sender that meets `Control` mid-restart fails closed rather than resolving. Both the leak and the mechanism were reproduced by probe at both toolchain pairs before this was written down. ADR 0030 is **not** edited — an accepted ADR changes through its own From ca644cd488968ae5098a2b76a7026406e44f29f0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:21:53 -0700 Subject: [PATCH 129/585] plan(M5): six repairs from the adversarial pass over this round MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Class 17, check-then-act across a process death. The fence recovery reads the head, recomputes the id from it and queries the status -- which looks like a window, because the head can move in between. It is not one, and the reason is now written down rather than assumed: the identity is a **function of the head**, and the fence binds its expected epoch and version to the head it read, so a head that has moved is a fence already decided -- it either was the mover or can no longer linearize at all (`succession_refusal/3`, `state.ex:450-463`). `transaction_status/4` on the id derived from the current head is therefore always the right question, answering `:absent` past the fence and its real status before it. Class 22, hidden default timeouts. The relay ticket call is a `GenServer.call` this round put `session.create` onto, and nothing named its bound, so a client mutation would have carried a silent five seconds. It carries the teardown number explicitly, and an unanswered ticket call is `relay_lost` rather than a stall. Class 7, stale vocabulary. `daemon.status`'s `activations_used` row still read "activations spent in this daemon lifetime" while the counting rule beneath it makes a reservation count. Class 2, conflicts with accepted ADRs. Generation 2 now reuses ADR 0023's `detached` for three eviction occasions that ADR defines for post-admission writer loss. That is a widening inside generation 2 and says so: same code, same fields, same uncorrelated shape, generation 1 untouched, and ADR 0023's own pressure rule already detaches at the last emitted cursor and says so (`0023-…-technical.md:362`). Class 5, Concept promises versus Technical mechanisms. ADR 0032's Concept described eviction and detachment without the close the companion now requires, and carried no connection bound at all. Both are in the Concept. And two ADR 0023 citations that pointed one line off -- the pressure rule and the initialize refusal -- are corrected against the file. --- ...tachment-residency-and-replay-technical.md | 11 +++++++- ...-daemon-attachment-residency-and-replay.md | 8 +++++- docs/plans/M5-technical.md | 26 +++++++++++++++++++ 3 files changed, 43 insertions(+), 2 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index b5396de7f..cbe53eee1 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -235,7 +235,7 @@ no content, no durable session state. | result | `attachment_limit` | integer, 512 | required | | result | `active_sessions` | integer | required | | result | `activation_limit` | integer, 64 | required | -| result | `activations_used` | integer, activations spent in this daemon lifetime | required | +| result | `activations_used` | integer, activations spent in this daemon lifetime **plus reservations in flight** — see below | required | | result | `index_entries` | integer | required | | result | `index_limit` | integer, 4,096 | required | | result | `index_full` | bool | required | @@ -519,6 +519,15 @@ client in a state neither side had defined. So: | Aggregate byte pressure chose this attachment | the same `detached` | close that connection | | Idle eviction at ten minutes | the same `detached` | close that connection | +Reusing `detached` for the three eviction rows is a **widening inside +generation 2**, stated rather than slipped in: ADR 0023 defines that code for +post-admission writer loss, and its own pressure rule already says to detach +at the last completely emitted cursor and say so +(`0023-…-technical.md:362`). Generation 2 extends the occasions, not the +record — same code, same fields, same uncorrelated shape — and generation 1's +use of it is untouched, so the foreground server's behaviour does not move and +the ordered error list gains nothing for it. + **`event_cursor` is the same quantity in all four**: the **last completely emitted durable cursor** for that attachment — the highest event sequence the daemon finished writing to that socket, never one it had only encoded or diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 6ded2098f..1d3aca5aa 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -110,7 +110,13 @@ it. Each connection owns a bounded socket output buffer; a slow attachment is detached at its last completely emitted cursor while every other attachment continues. Idle attachments are evicted at the residency limit and reconnect at their retained cursor with no -missing durable event. Transient progress is coalesced or dropped first and +missing durable event. **Every detach the daemon initiates is a record and a +close**: the client is told, best-effort, on the connection being ended, and +that connection is closed with its attachment while every other connection is +untouched. A connection holds one attachment, so there is nothing for it to +do afterwards, and the close is what releases the attachment in core. +Concurrent connections are themselves bounded, at 512, because a client that +never attaches is bounded by no attachment ceiling. Transient progress is coalesced or dropped first and never delays a journal transaction. A session is *active* when **this daemon activated it in this lifetime** and diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 45fe8063d..5f68b4f17 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1497,6 +1497,15 @@ as though it does: would have left the window open at the other end: an owner could pass its holder check, send its ticket and die before the message arrived, and a replacement would see no ticket for a call that was about to be made. + + **That call carries an explicit bound and does not inherit + `GenServer.call/2`'s hidden five seconds**, which is the same discipline the + rest of this plan applies to every call that matters: the bound is the + teardown number, 5 s, because the relay's whole job here is to write a row + and answer, and a relay that cannot do that in five seconds is a relay the + daemon has lost. An unanswered ticket call is therefore not a silent + five-second stall inside a client's mutation; it is `relay_lost`, the class + that already exists for a relay the daemon can no longer account through. - **The relay monitors every lease owner**, so an owner's death is ordered *after* the tickets it sent. Message ordering between one sender and one receiver is guaranteed by the BEAM — signals from a process to a process are @@ -2573,6 +2582,23 @@ carried: it described three outcomes and returned none of them. the domain fenced, which is what the founding rule already requires of any unresolved unknown. + **Reading the head and then asking about a transaction is not + check-then-act here, and the reason is that the identity is a function of + the head.** The obvious objection is that the head can move between the + successor's read and its query, so the successor would be asking about a + transaction nobody proposed. It would be — and that is the correct answer + rather than a race. The fence binds `expected_owner_epoch` and + `expected_journal_version` to the head it read, so **a head that has moved + is a fence that is already decided**: either that fence was the mover and + committed, or it can no longer linearize at all, since the adapter refuses a + transaction whose expected version no longer matches + (`succession_refusal/3`, `state.ex:450-463`). So the successor's question is + always the right one: `transaction_status/4` on the id derived from the + **current** head answers `:absent` when the head has moved past the fence — + there is nothing unresolved at this version — and answers the fence's real + status when it has not. There is no window in which the successor is fenced + by an unknown it cannot name. + **`drain_id` survives as a report label and nothing more.** Core still mints one per call, with the generator it already uses for identifiers of its own (`:crypto.strong_rand_bytes(16)` rendered base16, From a6c1a5cc26ecf872af21a10b4cdc47a837912f89 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:23:12 -0700 Subject: [PATCH 130/585] plan(M5): reconcile the lease-owner sweep with the stop rules Second adversarial pass, class 5 and class 24. The collective sweep this round introduced was written in the phase table and nowhere else, so three rules it touches still described a sequence of one. The `stopping` field names one component; the sweep stops up to 512 at once. It now names the **set** for that one step, with the reason rule unchanged over it -- `:normal`, `:shutdown` or the owner's own `:killed` consumed, any other reason classified, exactly as for a singleton. The two receives are selective on one pid; the sweep's loop matches any pid in that set and removes it. Same discipline over a set rather than a singleton, and nothing else in the sequence sweeps, so nothing else needs either form. The sweep waited for "`DOWN`s", which lease owners do not produce: they are `start_link`ed by the owner, so what arrives is `{:EXIT, pid, reason}` on the link the classification already reads. The stop-helper row said "one at a time", which the sweep makes false; it is bounded by the 512 above. And the disposition gains the sentence a reader would otherwise have to derive: a lease owner ended here produces no `control_owner_lost`, step 3 having already closed every connection there was to send one to. --- docs/plans/M5-technical.md | 39 +++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 5f68b4f17..2c36c6e2e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1641,8 +1641,10 @@ step 1 as `listener_lost`, every lease owner's stop as a lost controller, step 3's clean return as `runtime_lost` — a daemon that could never exit `0`, and an idle-shutdown witness that could never pass. -So the owner carries a `stopping` field naming **the one component it is -currently stopping**, set immediately before each stop call. The EXIT clause +So the owner carries a `stopping` field naming **the component it is +currently stopping** — one pid at every step but phase 6's lease-owner sweep, +where it names that step's set of pids — set immediately before each stop +call. The EXIT clause reads: - an exit from the pid named in `stopping`, **whose reason is `:normal`, @@ -1761,7 +1763,9 @@ process is unconditional, and on one already dead the exit the owner is waiting for is the one that made it dead, already queued. It is a wait for a signal that exists, not a second bound. -**Other messages wait their turn.** Both receives are selective on one pid, so +**Other messages wait their turn.** Both receives are selective on the pid +this step is stopping — on the set of them, in phase 6's lease-owner sweep, by +the same discipline read over a set — so an exit from another component, a client's frame, or anything else stays in the mailbox and is read when the owner returns to its loop. Nothing is skipped, only ordered — and nothing is lost even so, because of one invariant: @@ -2055,13 +2059,30 @@ session is reported `fence: :not_needed` if the head already moved and **Phase 6 stops the lease owners as a collective sweep, not one at a time.** Up to 512 of them exist, and stopping them in sequence inside five seconds was -arithmetic nobody did: the owner sends every lease owner its stop -**concurrently**, waits **once** for all of their `DOWN`s, and at the phase's -end kills whatever is left with `Process.exit(pid, :kill)`. The disposition is -stated: a lease owner killed this way loses nothing durable — it holds a lease +arithmetic nobody did: the owner spawns one stop helper **per lease owner, all +at once**, then waits in **one** loop until every one of those pids has +produced an exit on the owner's own link — the same link it already holds, so +the exits are `{:EXIT, pid, reason}` and not monitor `DOWN`s — and at the +phase's end kills whatever is left with `Process.exit(pid, :kill)` and reads +the exits that follow. + +**Two rules bend exactly here, and only here.** The `stopping` field names one +component elsewhere; for this step it names the **set** of lease-owner pids, +and the EXIT clause's rule is otherwise unchanged — an exit from a pid in that +set whose reason is `:normal`, `:shutdown` or the owner's own `:killed` is +consumed, and any other reason is classified, exactly as for a single +component. And the two selective receives elsewhere match one pid; here the +loop matches **any** pid in the set and removes it, which is the same +discipline over a set rather than a singleton. Nothing else in the sequence +sweeps, so nothing else needs either form. + +The disposition of a killed lease owner is +stated: it loses nothing durable — it holds a lease record, an epoch and an in-flight admission set, none of which outlives the daemon — and the relay's tickets, which do matter, are held by the relay and -stopped after them. +stopped after them. Its session's controller connection is already gone, step +3 having closed every connection, so a lease owner ended here produces no +`control_owner_lost` and there is nothing left to send one to. **`budget_ms` is still core's to derive and report**, for the reason below; what changed is that it is one phase among seven rather than the whole drain. @@ -3522,7 +3543,7 @@ links rather than one of them, and an earlier revision headed eleven rows | --- | --- | --- | --- | | **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | | **Connections**, one per accepted client | The listener | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | -| **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time | Nothing: monitored, never linked | +| **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time, except phase 6's lease-owner sweep, which spawns one per lease owner at once and so is bounded by the 512 above | Nothing: monitored, never linked | | **Relay tasks**, one per ticketed mutation | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | **Core's processes, as groups with their owner.** The runtime root supervises From 916ca59e31dbf929a73f666e563f3e823d9bb164 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:45:35 -0700 Subject: [PATCH 131/585] plan(M5): count Store calls per phase and stop retrying inside the drain F1. Phases 2 and 4 were bounded at one Store call each and are two and three. Every call into the adapter carries the same 30 s `@call_timeout` -- `transact` at `local.ex:111-113`, `ownership_head` at `:130-132`, `transaction_status` at `:116-122`, the constant at `:65` -- so a phase bound is its worst sequential call count times 30 s, not "30 s because it is a Store call". Phase 2 is two: the abort admission goes to a live coordinator whose lane is serial (`owner_lane.ex:83-99`, called at `session_coordinator.ex:1242`, `:1363`, `:1702`), so it may wait out one in-flight transaction and then make its own. Phase 4 is three at worst: head, advance, and one status query. The maximum is `budget_ms` + 195 s. Retries leave the drain, which is what keeps those counts finite. Core's ordinary path retries a `commit_unknown` once (`session_coordinator.ex:1761- 1764`); the drain uses neither that path nor its own. An ambiguous admission is not retried -- the session is fenced. An ambiguous fence is resolved once, never re-proposed. And a stale fence no longer makes a second attempt. By the time a fence runs the coordinator is dead, and while it lived it held at most one Store transaction in flight for that session, the lane being a synchronous call it makes from its own process. So a stale refusal is proof that the one transaction linearized and proof that nothing else will: `:superseded`, classified from the journal, no reread and no reattempt. The per-call rule's escape is deleted as circular: it refused a Store call and then branched on whether the head had moved, which is a Store read. With the counts above the rule never fires on the intended sequence. `:not_needed` now means one thing decided without reading anything -- the session is in `settled` and has nothing to fence. F3. The fence-recovery witness asserted the same answer in both worlds. `transaction_status/4` answers `:absent` for a fence that committed (the head moved, so the id recomputed from the new head was never proposed) and for one that never linearized (`state.ex:48-60`). The discriminating surface is the **head**: the drain now records `{:unknown, head}` and reports that head on the stop line, and a successor compares it with the head it reads -- moved means decided, unchanged means recompute the id from the recorded head and ask the status. The witness runs twice and the two runs differ on that surface. --- docs/plans/M5-technical.md | 217 +++++++++++++++++++++++++------------ docs/plans/M5.md | 15 +-- 2 files changed, 155 insertions(+), 77 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 2c36c6e2e..8e1862a73 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -294,8 +294,8 @@ reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop as the sum of the seven phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 105 s**, being 5 s for the admission cut, 30 s for abort - admission, `budget_ms` for cancellation, 30 s for the fence, 5 s for + **`budget_ms` + 195 s**, being 5 s for the admission cut, 60 s for abort + admission, `budget_ms` for cancellation, 90 s for the fence, 5 s for coordinator termination, 5 s for daemon teardown and 30 s for the Store — with the six constants written out beside the one derived term, so an operator setting a `TimeoutStopSec` adds up numbers rather than trusting a @@ -2026,17 +2026,42 @@ that already exists somewhere, and the operator maximum is the sum: | # | Phase | Bound | Where the number comes from | | --- | --- | --- | --- | | 1 | **Admission cut** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement from a process with no work of its own to finish; a relay that does not answer inside it is a relay the daemon has lost, so the stop becomes the `relay_lost` fail-stop rather than waiting longer | -| 2 | **Abort admission** | **30 s**, the Store's `@call_timeout` (`local.ex:65`) — **per phase, not per session**, because the sessions are admitted **concurrently** | One Store call each; running them at once makes the phase one call long rather than *N* | +| 2 | **Abort admission** | **60 s** — **two** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission may have to wait behind the transaction the coordinator already has in flight, and then make its own; those are sequential, so the phase is two calls long | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | -| 4 | **Fence** | **30 s**, the same Store call timeout, again **concurrent** across sessions | Each fence is one `advance_owner` transaction | +| 4 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | | 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`) | The value core already gives a coordinator to stop in | | 6 | **Daemon teardown** | **5 s** | This plan's one chosen number, covering the notice, the closes, the lease owners, the relay and the edges | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 5 s + 30 s + `budget_ms` + 30 s + 5 s + 5 s + 30 s -> = `budget_ms` + 105 s**, and `budget_ms` is the one term an operator cannot +> **Maximum graceful stop = 5 s + 60 s + `budget_ms` + 90 s + 5 s + 5 s + 30 s +> = `budget_ms` + 195 s**, and `budget_ms` is the one term an operator cannot > compute in advance. +**Every phase bound is a Store-call count, and an earlier revision counted +one where the sequence is two or three.** *Every* call into the local adapter +is the same 30 s: `transact/2` at `local.ex:111-113`, `ownership_head/3` at +`:130-132` and `transaction_status/4` at `:116-122` all pass `@call_timeout` +(`:65`). So a phase's bound is not "30 s because it is a Store call"; it is +**(the worst sequential count of Store calls in it) × 30 s**, and the counts +are these: + +- **Phase 2 is two.** The abort admission goes to a **live coordinator**, whose + lane is serial — `OwnerLane.transact/2` is a plain synchronous call the + coordinator makes from its own process (`store/owner_lane.ex:83-99`, called + at `session_coordinator.ex:1242`, `:1363`, `:1702`) — so the admission may + wait out one transaction already in flight and then make its own. Two, in + sequence. +- **Phase 4 is three at worst.** A head read, then the `advance_owner`, then, + only where that answers `commit_unknown`, **one** `transaction_status` query. +- **And the drain retries nothing**, which is what keeps both counts finite. + Core's ordinary commit path retries a `commit_unknown` once — + `resolve_transaction/2` re-presents the transaction on the second line of its + own case (`session_coordinator.ex:1761-1764`) — and the drain does not use + that path for either of these. An ambiguous **admission** is not retried: the + session is fenced, by the rule this section already states. An ambiguous + **fence** is resolved by the one status query, not re-proposed. A **stale** + fence is not reattempted at all, for the reason the fence table gives. + **The seven phases and the six steps are two cuts through the same stop, and the mapping is stated rather than left to be inferred.** The numbered sequence below is what the daemon's owner *does*; the phases are what each part of it @@ -2050,12 +2075,23 @@ and covers steps 3, 4, 5 and the non-Store part of step 6. Phase 7 is the Store stop at the end of step 6. Nothing is bounded twice and nothing is bounded by nobody. -**One rule keeps a phase from starting work it cannot finish.** *No Store -operation begins without at least its own timeout remaining in its phase.* A -fence with four seconds left on a thirty-second phase is not attempted; the -session is reported `fence: :not_needed` if the head already moved and -`:unknown` otherwise, and the daemon proceeds. Starting a 30 s call inside a -4 s remainder is how a bounded sequence becomes an unbounded one. +**One rule keeps a phase from starting work it cannot finish, and with the +counts above it can always be honoured.** *No Store +operation begins without at least its own 30 s remaining in its phase.* Because +each phase's bound **is** its worst sequential call count times 30 s, a phase +that has reached its *k*th call still has at least 30 s left, so the rule never +fires on the intended sequence; it is a guard against a sequence longer than +the one counted, not a routine exit. + +**The escape an earlier revision gave it is deleted, because it was +circular.** That revision said a fence with four seconds left is not attempted +and "the session is reported `fence: :not_needed` if the head already moved +and `:unknown` otherwise" — but deciding whether the head moved *is* a Store +read, which is the very thing the rule has just refused. There is no way to +take that branch. `:not_needed` now means one thing only, decided without +reading anything: **quiesce does not fence a session it reports `settled`**, +its own work having already ended. Unsettled and absent sessions are fenced, +and their entry is `:committed`, `:superseded` or `:unknown`. **Phase 6 stops the lease owners as a collective sweep, not one at a time.** Up to 512 of them exist, and stopping them in sequence inside five seconds was @@ -2398,7 +2434,9 @@ Loopex.Runtime.quiesce(runtime) :: absent: [session_id], budget_ms: non_neg_integer(), drain_id: binary(), - fences: %{session_id => :committed | :superseded | :unknown | :not_needed} + fences: %{session_id => :committed | :superseded | :not_needed + | {:unknown, %{owner_epoch: non_neg_integer(), + journal_version: non_neg_integer()}}} }} ``` @@ -2418,9 +2456,11 @@ gone, which is neither settled nor unsettled and must not be counted as either. `budget_ms` is the drain budget core derived and used. `drain_id` is the label this drain reports, and `fences` is what the fence below actually did for each session it touched — `:committed` where the epoch moved, -`:superseded` where an older transaction won the race first, `:unknown` where -the Store could not say, and `:not_needed` where the head had already moved -under the session's own settled work. **Without `fences` a fence's failure is +`:superseded` where the one transaction that could still linearize won the +race first, `:not_needed` where the session settled and needed no fence, and +`{:unknown, head}` where the Store could not say, **carrying the head the +fence was built from**, because that head is the only thing a successor can +discriminate on. **Without `fences` a fence's failure is a thing no caller can observe**, which is the defect an earlier revision carried: it described three outcomes and returned none of them. @@ -2590,35 +2630,47 @@ carried: it described three outcomes and returned none of them. command or operation identity* and that resolution be restart-safe (`vision-technical.md:710-715`), and a value in RAM is neither. - So the identity is the head itself. A successor — the next daemon, or the - next activation of that session — **rereads `ownership_head/3`, recomputes - the same `tx_id` from `(session_id, owner_epoch, journal_version)`, and asks - `Store.transaction_status/4`** (`apps/loopex/lib/loopex/store.ex:1026-1048`, - the adapter's own at `local.ex:118-122`), whose closed result set — - `{:terminal, :committed}`, `{:terminal, {:not_committed, reason}}`, - `:absent`, `:unavailable` (`store.ex:293-297`) — is exactly the resolution - this needs. Two of them end it: committed means the epoch moved and the - fence held; not-committed or absent means it did not and the successor's own - ordinary owner advance supersedes the state anyway. `:unavailable` leaves - the domain fenced, which is what the founding rule already requires of any - unresolved unknown. - - **Reading the head and then asking about a transaction is not - check-then-act here, and the reason is that the identity is a function of - the head.** The obvious objection is that the head can move between the - successor's read and its query, so the successor would be asking about a - transaction nobody proposed. It would be — and that is the correct answer - rather than a race. The fence binds `expected_owner_epoch` and - `expected_journal_version` to the head it read, so **a head that has moved - is a fence that is already decided**: either that fence was the mover and - committed, or it can no longer linearize at all, since the adapter refuses a - transaction whose expected version no longer matches - (`succession_refusal/3`, `state.ex:450-463`). So the successor's question is - always the right one: `transaction_status/4` on the id derived from the - **current** head answers `:absent` when the head has moved past the fence — - there is nothing unresolved at this version — and answers the fence's real - status when it has not. There is no window in which the successor is fenced - by an unknown it cannot name. + So the identity is the head itself, and the drain **reports the head it + fenced from** for every session it leaves `:unknown`: `fences` carries + `{:unknown, %{owner_epoch: …, journal_version: …}}` for those, and the stop + line names the same three values per session beside `drain_id`. That pair — + the recorded head and the head a successor reads — is what discriminates. + + **The surface is the head, not the transaction status**, and an earlier + revision got that exactly backwards. It had a successor reread + `ownership_head/3`, recompute the `tx_id` **from the head it just read**, + and ask `Store.transaction_status/4`. That question cannot answer anything: + if the fence committed, the head has moved, so the id recomputed from the + **new** head is an id nobody ever proposed and the status is `:absent` + (`state.ex:48-60` answers `:absent` for any tx_id with no retained + resolution); if the fence never linearized, the head has not moved, the id + is the fence's own — and the status is `:absent` again. **Two different + worlds, one answer.** + + The recovery is therefore two steps in this order: + + 1. **Read `ownership_head/3` and compare it with the recorded head.** If it + has moved, the fence is decided and the successor is done — either that + fence was the mover or it can no longer linearize at all, the adapter + refusing any transaction whose expected epoch or version no longer + matches (`succession_refusal/3`, `state.ex:450-463`). Nothing is + unresolved at the recorded version, and the successor's own ordinary + owner advance proceeds from the head it just read. + 2. **Only if the head is unchanged**, recompute the `tx_id` from the + **recorded** head — which is the current head, so the two agree — and ask + `Store.transaction_status/4` (`apps/loopex/lib/loopex/store.ex:1026-1048`, + the adapter's own at `local.ex:116-122`), whose closed result set — + `{:terminal, :committed}`, `{:terminal, {:not_committed, reason}}`, + `:absent`, `:unavailable` (`store.ex:293-297`) — resolves it. + `{:terminal, :committed}` with an unmoved head cannot occur and is a + defect if seen; `{:terminal, {:not_committed, _}}` and `:absent` both + mean the fence is not there and the successor proceeds; `:unavailable` + leaves the domain fenced, which is what the founding rule already + requires of any unresolved unknown. + + That ordering also disposes of the check-then-act objection without an + argument about windows: step 1's answer is the decision, and step 2 runs + only in the world where step 1 said nothing has moved. **`drain_id` survives as a report label and nothing more.** Core still mints one per call, with the generator it already uses for identifiers of its own @@ -2658,17 +2710,28 @@ carried: it described three outcomes and returned none of them. | Outcome | What it means | `fences[session_id]` | How the session is reported | | --- | --- | --- | --- | | The fence **commits** | The epoch has moved; any older `session_commit` linearized afterwards is refused `:stale_owner_epoch` (`state.ex:548-551`) | `:committed` | `unsettled`, fenced | - | The fence is refused **`:stale_owner_epoch`** or **`:stale_journal_version`** | Another transaction linearized **first**. The fence lost the race on the epoch or on the version, which in both cases means the state it read is no longer the state there is | `:superseded` | Quiesce **rereads the head and recomputes the id from it**; if the session is still unsettled it makes **one new attempt** under the new head's identity, and classifies **from the journal** if that attempt is superseded too. It is not reported as fenced, because it was not | - | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | `:unknown` | Resolved with `Store.transaction_status/4` under the **same derived `tx_id`**, which is idempotent by construction, until the phase's bound; still unknown at the bound leaves the session `unsettled` with `fences[session_id] == :unknown`, and the domain fenced | - | **No fence is attempted** | The head had already moved under the session's own settled work, or the phase had less than a Store call timeout left in it | `:not_needed` | As its own work left it | - - **A retry is never a blind repeat of a refused attempt.** The two stale - results say the head moved, so retrying the same transaction would refuse - identically forever; the recovery is to read durable state again and build a - new attempt from it, which is what the coordinator's own - `discover_and_advance_owner/1` already does on the same refusals. A + | The fence is refused **`:stale_owner_epoch`** or **`:stale_journal_version`** | The one transaction that could still have been in flight linearized **first**. The fence lost the race on the epoch or on the version; either way the state it read is no longer the state there is, and there is **nothing left to fence** | `:superseded` | Classified **from the journal**, as whatever that commit made it. **No second attempt.** It is not reported as fenced, because it was not | + | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | `{:unknown, head}` | Resolved by **one** `Store.transaction_status/4` query under the same derived `tx_id`; an answer that is still unknown after it leaves the session `unsettled` with `{:unknown, head}` carrying the head the fence read, and the domain fenced | + | **No fence is attempted** | The session is in `settled` — its own work ended, so there is nothing ambiguous to fence | `:not_needed` | As its own work left it | + + **A stale refusal ends the fence rather than starting a second one, and the + reason is the serial lane.** An earlier revision rereads the head and makes + one new attempt — which would be right if more transactions could keep + arriving, and none can. By the time a fence is attempted the coordinator is + **dead** (quiesce terminates it and waits for the `DOWN` first), and while + it was alive it held **at most one** Store transaction in flight for that + session, because `OwnerLane.transact/2` is a synchronous call the + coordinator makes from its own process and threads the returned lane through + its state (`store/owner_lane.ex:83-99`, `session_coordinator.ex:1242`, + `:1363`, `:1702`). So at most one transaction can linearize after the + coordinator is gone. A stale refusal is proof that it did — and proof that + nothing else will, there being no process left to send one. Reattempting + would spend a third and fourth Store call to fence a session that no longer + has anything to fence, and would make the phase's bound a number nobody + could state. A `commit_unknown` is the opposite case: the transaction may have linearized, - so it is **resolved**, never re-proposed under a new identity. + so it is **resolved once**, never re-proposed under a new identity and + never retried into an unbounded loop. So the claim the plan makes is the one the mechanism supports: when `quiesce/1` returns, every session whose `fences` entry is `:committed` has @@ -2683,7 +2746,7 @@ carried: it described three outcomes and returned none of them. — a refusal that is not `rejected_no_active_run`, or a `commit_unknown` on the admission itself — has no cleanup released for it at all. It is fenced like an unsettled session, or, where the fence too is unknown, left fenced - and reported `unsettled` with `fences[session_id] == :unknown`. Releasing a + and reported `unsettled` with `{:unknown, head}`. Releasing a cancellation for a session whose abort may or may not be in the journal is the one thing a drain must not do, because it would cancel work no command admitted. @@ -3000,8 +3063,11 @@ a trace or a telemetry span. Nothing here is a new logging plane: the daemon has no diagnostic surface of its own beyond these lines and the records it already sends on the wire, and the fatal-class map above is the whole vocabulary of what a **fatal** exit may say. An **orderly** stop adds exactly -one line and no class: a census naming `drain_id`, `budget_ms` and the three -counts quiesce returned. That line is the only thing an ordinary stop writes +one line and no class: a census naming `drain_id`, `budget_ms`, the three +counts quiesce returned and, for every session it left `{:unknown, head}`, +that session's id with the `owner_epoch` and `journal_version` its fence read +— the values a successor compares against, and the only part of the census +that is recovery data rather than a count. That line is the only thing an ordinary stop writes to `stderr`, and it names no fatal class, which is what a reader checks it for. @@ -3087,7 +3153,8 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. is what proves the marker was actually released. The case also asserts the negative that the `stopping` field exists for: **no fatal class is recorded at any point during the stop**, and `stderr` carries **nothing but the one - census line** — `drain_id`, `budget_ms` and three counts — **with no fatal + census line** — `drain_id`, `budget_ms`, three counts and no unknown-fence + heads, an idle daemon having none — **with no fatal class in it**. Stopping every linked process deliberately produces an exit from each, and every one of them must be consumed rather than classified. (Real process.) @@ -3134,14 +3201,24 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. and that the drain does not treat it as an unexplained failure — the assertion a design handling only the epoch refusal would fail. - A fourth proves the recovery property, and it is the case the memory-held - `drain_id` could not have passed: the fence is made to answer - `commit_unknown`, the whole daemon is **killed** before it can resolve it, - and a **second process** reads the head, recomputes the `tx_id` from - `(session_id, owner_epoch, journal_version)` alone and resolves it with - `Store.transaction_status/4`. The two answers that must differ are that - status for a fence that did linearize and for one that did not; neither is - reachable from anything the dead daemon held. + A fourth proves the recovery property, and its surface is the **head**, + which is the correction a review found: the fence is made to answer + `commit_unknown`, the drain records `{:unknown, head}` for that session and + reports it on the stop line, the whole daemon is **killed** before it can + resolve anything, and a **second process** reads + `ownership_head/3` and compares it with the recorded head. The case runs + **twice** and the two runs must give different answers on that surface: in + the first the held fence is released so it linearizes, and the successor + reads a head that has **moved**, concludes the fence is decided and asks no + status at all; in the second it never linearizes, the successor reads the + **unchanged** head, recomputes the `tx_id` from `(session_id, owner_epoch, + journal_version)` and gets `:absent` from `Store.transaction_status/4`. The + case that asserted `transaction_status/4` alone is withdrawn: that call + answers `:absent` in **both** worlds — a committed fence moves the head, so + the id recomputed from the new head was never proposed — and a witness whose + two branches assert the same value proves nothing. Neither surface is + reachable from anything the dead daemon held, which is the property the + memory-held `drain_id` could not have given. - **The drain is globally durable-first, not per session.** Two sessions are active, each with a cancellable effect. The case asserts that **both** aborts are committed to the journal **before either** cleanup begins — @@ -3718,13 +3795,13 @@ line; M5 introduces none of its own. | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Phase 1, the admission cut | **5_000 ms**, the teardown number reused; an unanswered cut becomes the `relay_lost` fail-stop | This plan | -| Phase 2, abort admission | a fixed **30 s**, the Store's own `@call_timeout`; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65` | +| Phase 2, abort admission | a fixed **60 s** — two sequential Store calls at the adapter's own 30 s `@call_timeout`, the admission waiting out at most one transaction already in the coordinator's serial lane and then making its own; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | -| Phase 4, the fence | a fixed **30 s**, the same Store call timeout, concurrent across sessions | Core, against the Store's existing bound | +| Phase 4, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | -| Maximum graceful stop | `budget_ms` + **105 s**, the sum of the six fixed phases above | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **195 s**, the sum of the six fixed phases above | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 21ff2e41d..c06f91600 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -422,16 +422,17 @@ command on its own authority at all. **A graceful stop has a stated maximum**, because an operator configuring a service manager needs one, and it is the **sum of seven bounded phases** rather than one clock that has to cover everything: five seconds for the admission -cut, thirty for admitting every session's abort, the drain budget **core -derives and reports** for the cancellation, thirty for the fence, five for +cut, sixty for admitting every session's abort, the drain budget **core +derives and reports** for the cancellation, ninety for the fence, five for terminating the coordinators that did not settle, five for every non-Store action after the drain — the stop records, the closes, the lease owners and the edges — and thirty for the Store stop that releases the marker. Six of the -seven are fixed, so the maximum is **`budget_ms` plus 105 seconds**. Every one -of the six comes from a number that already exists — the Store's own call -timeout, the coordinator's own shutdown value — rather than from a figure this -plan invented, and no phase begins a Store call without that call's own -timeout still left in it. The drain term is core's because each session drains under the grace it +seven are fixed, so the maximum is **`budget_ms` plus 195 seconds**. Every one +of the six is a count of the adapter's own thirty-second call timeout, or the +coordinator's own shutdown value, rather than a figure this plan invented: a +phase that makes two Store calls in sequence is bounded at sixty and one that +makes three at ninety, and the drain retries nothing, which is what keeps +those counts finite. The drain term is core's because each session drains under the grace it committed, which a daemon reading its own flag would not know for a session composed earlier. A service manager that kills the daemon sooner turns the stop into a forced From d43d64a47c7c14ae161d90956617ea4ebec8740f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:47:47 -0700 Subject: [PATCH 132/585] plan(M5): attach is the tenth ticket and the cut waits for settlement MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F2. The admission cut had two holes and a classification that was not total. `session.attach` was neither ticketed nor a read, and it enters core: its second leg calls `{:attach, …}` on the dispatcher (`runtime.ex:199-210`, `:538`), whose handler spawns a scan worker, monitors the caller and records a pending scan in dispatcher state (`event_dispatcher.ex:168-199`), and whose completion installs the attachment and releases superseded transfers (`:805-824`). It is now the tenth ticket, ticketed for the cut alone: it names no session for ordering, because an attachment grants nothing a successor could overtake. Reads stay unticketed, and the line between them is now stated as what it is -- a read changes no core state, an attach does. The relay could acknowledge with tickets "recorded as outstanding for the drain to fence", which gives away the property: a recorded ticket is a call still running inside core, so quiesce would enumerate `Control` while an admission, a create or an attach was still changing it. The acknowledgement now requires every ticket to have **settled**, which is reachable because every ticketed call is bounded by core's work rather than by a client, and a ticket that cannot settle is already `relay_lost`. And quiesce's classification is total over `Control`, which has three statuses rather than one: `:active` with a live coordinator drains; `:active` with a dead one and `:unavailable` (`control.ex:620`, `:818`, `:862`, `:1150`) are both `absent` and both fenced, there being no coordinator and possibly a transaction; a session with no entry is in no list. `:acquiring` (`:569`, `:1030`, `:1189`) cannot be reached after the cut, because only create and resume write it, both start a coordinator inside the call, both are ticketed, and the cut waits for settlement -- but it gets a row anyway, fenced as `unsettled`, because a classification that omits a status the code can write is one nobody can check. --- ...tachment-residency-and-replay-technical.md | 7 +- ...controller-lease-and-takeover-technical.md | 17 +-- docs/plans/M5-technical.md | 103 +++++++++++++----- 3 files changed, 90 insertions(+), 37 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index cbe53eee1..3d7343766 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -556,7 +556,8 @@ on differently. **`daemon_stopping`, the refusal after the admission cut.** An orderly stop begins with a synchronous, acknowledged cut: the daemon's owner calls the admission relay, the relay closes admissions and answers only once every -ticket it holds has settled or been recorded, and nothing enters core through +ticket it holds has **settled** — not merely been recorded, a recorded ticket +being a call still running — and nothing enters core through the daemon after that answer. A connection that is still open — and every connection is, because the cut precedes the closes — may still send a frame. It is answered with a **correlated** `daemon_stopping` carrying that request's @@ -566,8 +567,8 @@ of the stop sequence, which is where a client is told the reason it is going away; `daemon_stopping` answers the one request that arrived in between. The instant it names is the relay's acknowledgement, not the signal: a command -whose relay ticket was recorded **before** the acknowledgement settles or is -fenced under the drain, and one that arrives after it is refused. Those are +whose relay ticket was recorded **before** the acknowledgement has settled by +the time it returns, and one that arrives after it is refused. Those are the two witnesses, and they must give different answers on the same surface — the connection's own reply stream. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 98a318d47..b3bd81c89 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -81,14 +81,17 @@ flight, and core never sees the writer epoch at all. added on the maintainer's decision of 2026-09-20. Every **lease-authorized existing-session mutation** — the set this pair lists below, each carrying `writer_epoch` and admitted only from the recorded holder — is routed through -it, and so is `session.create`, which carries no epoch and whose ticket the -connection process takes because no lease owner exists for a session that does -not exist yet. Nothing else is: reads are not ticketed, since a read grants -nothing, orders nothing, and a blocking read would otherwise hold a takeover -for as long as an observer sat on it. A create's ticket blocks no grant — there -is no earlier tenure for a successor to overtake — and it exists so that the +it, and so are two calls that carry no epoch: `session.create`, whose ticket +the connection process takes because no lease owner exists for a session that +does not exist yet, and `session.attach`, whose second leg mutates the +runtime's dispatcher. Ten in all. Nothing else is: reads are not ticketed, +since a read changes no core state, grants nothing, orders nothing, and a +blocking read would otherwise hold a takeover +for as long as an observer sat on it. Neither the create ticket nor the attach +ticket blocks a grant — the first names no session yet, the second grants +nothing a successor could overtake — and both exist so that the daemon's orderly stop can close admissions with an acknowledgement covering -**every** mutation in flight, which a relay that creates bypassed could not +**every** call that changes core state, which a relay they bypassed could not give. The plan's companion owns that cut. The lease owner — or, for a create, the connection process — **calls** the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8e1862a73..c62a9ac8b 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and every ticket it holds has settled or been recorded — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to settle or to be fenced under the drain, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — and a `session.create` sent after the cut refused the same way, which is the case that would fail if creates bypassed the relay; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and **every ticket it holds has settled** — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to have settled by the time the acknowledgement returns, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create` and `session.attach` sent after the cut refused the same way, the two cases that would fail if either bypassed the relay, and a third asserting no `Control` entry changes between the acknowledgement and quiesce's enumeration; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the six ways that gate fails asserted separately in the daemon's own state and asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch` and to refuse `control_not_held` without it. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -341,7 +341,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -1441,7 +1441,7 @@ exist. The fixed set is this: | 6 | The workspace lease | `start_edge(WorkspaceLease, …)` | no | | 7 | The local executor | `start_edge(Local, …)` | no | | 8 | The runtime root | `start_edge(Loopex, …)` | no | -| 9 | The **admission relay** | The daemon's own; every ticketed mutation is routed through it | no | +| 9 | The **admission relay** | The daemon's own; every one of the ten core calls that change core state is routed through it | no | | 10 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | The tracing capability starts with the other two host-owned processes and @@ -1464,8 +1464,9 @@ So one fixed, daemon-owned process holds what the lease owners cannot — and three details of it are the difference between closing the window and looking as though it does: -- **Tickets cover every core call that mutates, and nothing else — nine of - them.** Eight are the lease-authorized existing-session mutations ADR 0033 +- **Tickets cover every core call the daemon makes that mutates core state, + and nothing else — ten of them.** Eight are the lease-authorized + existing-session mutations ADR 0033 lists: `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, `session.respond_interaction`, `session.admit_resources` and @@ -1481,7 +1482,25 @@ as though it does: relay — not the connection, which may be gone — owns the resolution of the activation slot that create reserved. An earlier revision left creates outside the relay entirely, which made the cut a promise the daemon could - not keep. **`session.release_control` is not among the nine**, and the + not keep. + + **The tenth is `session.attach`, and it is ticketed for the cut alone.** An + earlier revision called it a read and left it out, which it is not: its + second leg **mutates the dispatcher**. `Runtime.attach/3` calls + `{:attach, …}` on the dispatcher (`runtime.ex:199-210`, `:538`), whose + handler spawns a scan worker, monitors the caller and records a pending scan + in dispatcher state (`event_dispatcher.ex:168-199`), and whose completion + installs the attachment into the `attachments` map and releases the + transfers of anything it supersedes (`:805-824`). A cut that had not + accounted for an attach in flight would have quiesce enumerating `Control` + while core was still installing one. **Its ticket names no session for + ordering purposes**: it takes no part in the per-session grant-blocking + rule, because an attachment grants nothing and cannot overtake a mutation. + It exists so the cut is total. **Reads stay unticketed** for the reason + below, and the distinction is exactly this one — a read changes no core + state, and an attach does. + + **`session.release_control` is not among the ten**, and the distinction is worth one line: it carries `writer_epoch` and is lease-authorized, but it starts no core call, so there is nothing for a ticket to account for. **Reads are not ticketed either.** An earlier @@ -1535,14 +1554,21 @@ as though it does: - **A replacement owner's first grant for a session blocks until that session's outstanding tickets have settled.** Not the daemon's admissions generally — just that session's, which is why the ticket names one. A create - ticket names no session and blocks no grant. + ticket and an attach ticket block no grant: the first names no session yet, + and the second grants nothing that could be overtaken. - **The admission cut is the relay's, because the relay is the only process - that can answer for all nine.** The owner calls it once at the start of an - orderly stop; it stops admitting, and it answers only when every ticket it - holds has either settled or been recorded as outstanding for the drain to - fence. That answer is what makes "after this instant nothing enters core - through the daemon" a fact rather than a policy, and it is why every - mutating call goes through this one process. + that can answer for all ten.** The owner calls it once at the start of an + orderly stop; it stops admitting, and it answers only when **every ticket it + holds has settled** — not "settled or recorded", which an earlier revision + wrote and which gives away the whole property. A ticket merely *recorded* is + a call still running inside core, so quiesce would begin enumerating + `Control` while an admission, a create or an attach was still changing it. + Settling is the only acknowledgement worth having and it is reachable: every + ticketed call is bounded by core's own work rather than by a client, and a + ticket that cannot settle is the `relay_lost` case this section already + defines. That answer is what makes "after this instant nothing enters core + through the daemon" a fact rather than a policy, and it is why every call + that changes core state goes through this one process. That is the ordering claim ADR 0033's owner-loss section now rests on: a successor's first call cannot be issued while an older call for the same @@ -2238,11 +2264,16 @@ the owner fixes. set of sessions that could still grow underneath it. So the cut is a call. The owner calls the **relay** — whose scope this - extends to cover `session.create` as well as every ticketed mutation — and + extends to cover `session.create` and `session.attach` as well as every + ticketed mutation, ten calls in all — and the relay **acknowledges only when admissions are closed and every ticket - it holds has settled or been recorded**. Until that acknowledgement returns + it holds has settled**. Not "settled or recorded": a recorded ticket is a + call still running inside core, and quiesce would then enumerate `Control` + while an admission, a create or an attach was still changing it. Until that + acknowledgement returns the owner does nothing else; after it, no work can enter core through the - daemon at all. A command arriving on an open connection after the cut is + daemon at all, which is what lets quiesce treat `Control` as a set that no + longer moves. A command arriving on an open connection after the cut is refused **`daemon_stopping`**, a generation-2 error code added for it. Nothing is written to clients yet and nothing is closed: the connections @@ -2451,9 +2482,11 @@ fixed either — it is what the operator bound above already reports, and what a service manager's own timeout is set against. Of the six keys, four answer questions the daemon cannot ask. `absent` names -the sessions `Control` still held as active whose coordinator was already -gone, which is neither settled nor unsettled and must not be counted as -either. `budget_ms` is the drain budget core derived and used. `drain_id` is +the sessions `Control` still held — as `:active` with a dead coordinator, or +as `:unavailable` — for which there is no live coordinator to drain, which is +neither settled nor unsettled and must not be counted as +either. The classification table below is total over every status `Control` +can hold. `budget_ms` is the drain budget core derived and used. `drain_id` is the label this drain reports, and `fences` is what the fence below actually did for each session it touched — `:committed` where the epoch moved, `:superseded` where the one transaction that could still linearize won the @@ -2751,13 +2784,29 @@ carried: it described three outcomes and returned none of them. the one thing a drain must not do, because it would cancel work no command admitted. - **The classification quiesce returns has three lists, not two**, because - `Control` can hold an entry whose coordinator is already dead: its `DOWN` - handler leaves an `:active` entry in place (`control.ex:821-823`), which is - correct for residency and misleading for a drain. Such a session is - **`absent`**: quiesce admits no abort for it, runs no cancellation, and - fences it exactly as it fences an unsettled one, because an old transaction - from that dead coordinator is precisely the case the fence exists for. + **The classification quiesce returns has three lists, not two, and it is + total over what `Control` actually holds.** An earlier revision wrote it as + though every entry were `:active`. `Control` has **three** statuses, and a + session may have no entry at all, so the drain says what it does with each: + + | What `Control` holds | Why it can be there | Which list | Fenced? | + | --- | --- | --- | --- | + | `:active` with a live coordinator | The ordinary case | `settled` or `unsettled`, by whether its cancellation finished inside the budget | Only when `unsettled` | + | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | + | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes**, for the same reason: there is no coordinator, and there may be a transaction | + | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | **Cannot be reached after the cut** — see below — and, if one is found, `unsettled` | **Yes** | + | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No | + + **`:acquiring` cannot exist once the cut has answered**, and the reason is + the cut rather than an assumption about timing. Only `session.create` and + `session.resume` put an entry into that status, both of them start a + coordinator inside the call, and both are **ticketed**; the cut answers only + when every ticket has **settled**, so no create and no resume is in flight + when quiesce begins. The daemon is the only host on this runtime, so there + is no other caller to have started one. It is nonetheless given a row — + treated as `unsettled` and fenced — because a classification that omits a + status the code can write is a classification a reviewer cannot check, and + fencing is the safe answer for a session whose ownership may be moving. **Where "reports" lands, since a list in a return value is not a surface.** The daemon has two places to put what quiesce answers, and it uses both: @@ -3621,7 +3670,7 @@ links rather than one of them, and an earlier revision headed eleven rows | **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | | **Connections**, one per accepted client | The listener | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | | **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time, except phase 6's lease-owner sweep, which spawns one per lease owner at once and so is bounded by the 512 above | Nothing: monitored, never linked | -| **Relay tasks**, one per ticketed mutation | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | +| **Relay tasks**, one per ticketed call — the eight lease-authorized mutations, `session.create` and `session.attach` | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | **Core's processes, as groups with their owner.** The runtime root supervises seven children under `:rest_for_one` (`runtime/supervisor.ex:64-90`, strategy From ce0f36b2a3d722e0b6aeab654ebc26dfc249aaa9 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:49:45 -0700 Subject: [PATCH 133/585] plan(M5): five repairs at the attach, entry, fence and relay boundaries MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit F4. The fail-stop section still counted a design with fewer linked processes: "the other six", "in all eight", twice more. Eleven classes reach that path, one per linked component of the fixed set -- ten without artifact transfers -- and nine of them leave the Store alive. F5. `Runtime.attach/3` was written as waiting `:infinity` throughout. Its **first** leg does not: `control_call(runtime, {:begin_attach, …})` is called with no timeout argument (`runtime.ex:200`), so it takes the 5 s default (`:470`), and `safe_call/3` turns the exit into `{:error, :runtime_unavailable}` (`:529-535`). That is safe rather than a defect, because `begin_attach/3` reads and validates and mutates nothing (`control.ex:1235-1251`), so a refusal there leaves no attachment and no pending scan. The second leg keeps its two `:infinity` waits (`:538`, `:547`) for the reason the code states. The daemon's rule follows the split: no timeout on a call that has already changed something. F6. `control_entry` was two values over `Control`'s three statuses plus no-entry. `:active` maps to `:active`; `:unavailable` and no-entry both map to `:dormant`, neither being a live coordinator; `:acquiring` cannot be observed by the caller of a completed create or resume, that status existing only while the call itself is starting the owner. F7. The fence's proposed incarnation came from `fresh_incarnation/2`, which hashes `make_ref()` (`session_coordinator.ex:1500-1509`). Two fences from one unmoved head would then share a `tx_id` and differ in binding, and `resolve_known/2` answers `{:not_committed, :tx_id_conflict}` for exactly that (`state.ex:137-144`) -- so a successor resolving an unknown fence would meet a conflict instead of a resolution, and the id would not be bound to the canonical mutation digest as `vision-technical.md:710-716` requires. The incarnation now derives from the same three head inputs through `owner_identity/3`, so a re-presentation is byte-identical. `:tx_id_conflict` gets a row anyway, handled as `commit_unknown` is: the head decides. F8. The sweep classified any non-consumed reason while the fatal map says a lease owner has no daemon class. Inside the sweep every reason from a pid in that set is consumed, because there is nothing for it to be classified as, and its session-scoped handling is a no-op once step 3 closed every connection. F9. The relay's grant wait ran inside its callback, so one session's outstanding ticket would stop the relay answering every other session's ticket calls -- and the 5 s bound on those calls would then measure somebody else's core work and turn an unrelated slow mutation into `relay_lost`. The grant is deferred instead, `{:noreply, …}` plus `GenServer.reply/2`. And the relay installs its monitor on a lease owner **inside that owner's first ticket call, before acknowledging**, so the send-order argument holds from the first ticket rather than from some other occasion. --- docs/plans/M5-technical.md | 133 ++++++++++++++++++++++++++++++------- 1 file changed, 109 insertions(+), 24 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index c62a9ac8b..84e28ea72 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -909,6 +909,20 @@ carries two plain fields beside the session ID:** | `disposition` | `:fresh` \| `:historical` | Charge an activation for `:fresh`; charge nothing for `:historical` | | `control_entry` | `:active` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | +**`control_entry` is two values over three statuses, and the mapping is +stated rather than left to be guessed.** `Control` holds `:active`, +`:acquiring` and `:unavailable`, and a session may have no entry at all +(`control.ex:569`, `:620`, `:818`, `:862`, `:1030`, `:1150`, `:1189`). +`control_entry` answers the only question the daemon has — *is there a live +coordinator for this session right now?* — so `:active` maps to `:active`, +and **`:unavailable` and no-entry both map to `:dormant`**, there being no +coordinator either way. `:acquiring` is never observed by the caller of a +**completed** create or resume: it is the status while that very call is +starting an owner, and the call does not answer until the owner is ready or +the attempt has failed, at which point the entry is `:active` or +`:unavailable`. A caller therefore cannot see it, and the field does not need +a third value to be total. + **It is `control_entry`, not `residency`, and the rename is the point.** `residency` is a **daemon** fact on the wire — what `session.list` reports about a session in *this daemon's* lifetime — while this field says what @@ -1085,7 +1099,7 @@ leaked until the daemon restarts: | --- | --- | | Create, `disposition: :fresh` | **Converted** — a coordinator started | | Create, `:historical` with `control_entry: :active` | Released — that session was counted when it was activated | -| Create, `:historical` with `control_entry: :dormant` | Released — a replay starts nothing | +| Create, `:historical` with `control_entry: :dormant` | Released — a replay starts nothing. `:dormant` here covers both a `Control` entry that is `:unavailable` and no entry at all: neither is a live coordinator, and neither was charged | | Resume, `disposition: :fresh` | **Converted** — a coordinator started | | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | | Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | @@ -1104,19 +1118,37 @@ time out. There is no deadline on those calls to give the daemon "no answer". What actually ends the wait is the **per-connection process dying** while the call is still running in core, which is why the rows now name that. -**`Runtime.attach/3` is the same shape for its own reason.** Its signature -takes a runtime, a session ID and options and no -timeout at all (`runtime.ex:198-210`), and inside it waits `:infinity` twice — -at the dispatcher and again at the install (`:538`, `:547`) — **precisely so a -caller timeout cannot revoke a mutation it cannot see**, which is what the -code says there in as many words: the dispatcher has already created the -attachment and the install is registering its routing, so a caller that gave -up would be revoking neither mutation, and could not report truthfully that -the attach failed. All three activation-capable calls therefore wait -`:infinity`, and the daemon's rule is the simpler one an earlier revision -obscured: **it adds no timeout to a core call that consumes a ceiling**, -because a timeout it could not act on truthfully would be worse than the -wait. +**`Runtime.attach/3` is two legs with two different bounds, which an earlier +revision flattened into one.** Its signature takes a runtime, a session ID and +options and no timeout at all (`runtime.ex:198-210`), and it was written here +as waiting `:infinity` throughout. It does not. + +- **The first leg carries the default five seconds.** + `control_call(runtime, {:begin_attach, …})` is called with **no timeout + argument** (`runtime.ex:200`), so it takes `control_call/3`'s default of + `5_000` (`:470`), and `safe_call/3` turns the resulting exit into + `{:error, :runtime_unavailable}` rather than letting it reach the caller + (`:529-535`). That is **safe**, and it is why the leg can afford a deadline: + `begin_attach/3` reads the session entry, validates the options and detects + repetition, and **mutates nothing** (`control.ex:1235-1251`). A refusal + there — including a timeout refusal — leaves no attachment, no incarnation + and no pending scan, so the daemon releases its reserved slot on the + ordinary refusal row and there is nothing to observe. +- **The second leg waits `:infinity`, twice** — at the dispatcher and again at + the install (`:538`, `:547`) — **precisely so a + caller timeout cannot revoke a mutation it cannot see**, which is what the + code says there in as many words: the dispatcher has already created the + attachment and the install is registering its routing, so a caller that gave + up would be revoking neither mutation, and could not report truthfully that + the attach failed. + +The daemon's rule follows the split rather than the call: **it adds no timeout +to a core call that has already changed something**, because a timeout it +could not act on truthfully would be worse than the wait, and it leaves the +first leg's existing five seconds alone because that leg changes nothing. +`create_session/3` and `resume_session/3` have no such split — they are +`:infinity` from the first line — so the two of them and attach's second leg +are what the reservation rows are written against. **Who resolves a reservation when the asking process is gone: the relay.** The relay's task performs the core call and returns core's answer whether or not @@ -1525,6 +1557,13 @@ as though it does: daemon has lost. An unanswered ticket call is therefore not a silent five-second stall inside a client's mutation; it is `relay_lost`, the class that already exists for a relay the daemon can no longer account through. +- **The relay installs that monitor inside the owner's first ticket call, + before it acknowledges**, which is what makes the ordering argument below + true rather than nearly true. A relay that monitored on some other occasion + — at the owner's start, say — would have a window in which an owner had sent + a ticket the relay had not yet begun watching for. Monitoring inside the + synchronous call means the monitor exists before the first acknowledgement + does, and every ticket that owner will ever send comes after it. - **The relay monitors every lease owner**, so an owner's death is ordered *after* the tickets it sent. Message ordering between one sender and one receiver is guaranteed by the BEAM — signals from a process to a process are @@ -1551,6 +1590,17 @@ as though it does: - **A connection disappearing settles nothing**, because the call it made is still running inside core; the ticket outlives the connection exactly as the call does. +- **The relay never blocks its own loop, and that is why one session's stall + is one session's.** A grant that must wait on an outstanding ticket is + **deferred, not waited on**: the relay answers `{:noreply, …}` and replies + later with `GenServer.reply/2` when the last of that session's tickets + settles. A relay that ran the wait inside its callback would stop answering + every other session's ticket calls for as long as one session's mutation + took, and the five-second bound on a ticket call would then be measuring + somebody else's core work rather than the relay's own responsiveness — + turning an unrelated slow mutation into `relay_lost`. With deferral that + bound measures exactly what it claims to: whether the relay is alive and + reading its mailbox. - **A replacement owner's first grant for a session blocks until that session's outstanding tickets have settled.** Not the daemon's admissions generally — just that session's, which is why the ticket names one. A create @@ -2129,11 +2179,16 @@ phase's end kills whatever is left with `Process.exit(pid, :kill)` and reads the exits that follow. **Two rules bend exactly here, and only here.** The `stopping` field names one -component elsewhere; for this step it names the **set** of lease-owner pids, -and the EXIT clause's rule is otherwise unchanged — an exit from a pid in that -set whose reason is `:normal`, `:shutdown` or the owner's own `:killed` is -consumed, and any other reason is classified, exactly as for a single -component. And the two selective receives elsewhere match one pid; here the +component elsewhere; for this step it names the **set** of lease-owner pids. +And the reason rule bends with it: for a pid in that set **every** reason is +consumed, not only the three. That is not an exception to classification but +a consequence of the fatal map — **a lease owner has no daemon exit class at +all**, its death being session-scoped, so there is nothing for a non-`:normal` +reason to be classified *as*. Its session-scoped handling is a no-op here +because step 3 has already closed every connection, so there is no controller +attachment to close and no `control_owner_lost` to send. An earlier revision +left the general rule in place over this step, which would have classified a +lease owner's crash during the sweep into a class the map does not contain. And the two selective receives elsewhere match one pid; here the loop matches **any** pid in the set and removes it, which is the same discipline over a set rather than a singleton. Nothing else in the sequence sweeps, so nothing else needs either form. @@ -2651,7 +2706,7 @@ carried: it described three outcomes and returned none of them. | `mutation_domain` | The ownership domain, as every owner transaction uses | | `tx_id` | **Derived from durable state, not from anything in memory**, by the discipline the coordinator already uses: `owner_identity/3` hashes a namespace, a succession identity and an attempt into a stable ID (`session_coordinator.ex:1346`, `:1490-1498`). Quiesce derives its own from **`("drain_fence", session_id, expected_owner_epoch, expected_journal_version)`** — every input read from the head it just read | | `expected_owner_epoch`, `expected_journal_version` | Read **fresh** from `Store.ownership_head/3`, exactly as the coordinator reads them (`session_coordinator.ex:1337-1343`), so the fence binds the state it is actually fencing | - | `proposed_owner_incarnation_id` | A fresh incarnation, in the same form the coordinator mints (`fresh_incarnation/2`, `:1500`) | + | `proposed_owner_incarnation_id` | **Derived from the same head inputs**, in the coordinator's `owner_identity/3` form rather than its `fresh_incarnation/2` form — see below | **The `tx_id` derives from durable state, and an earlier revision derived it from a random number held only in memory.** That revision minted one @@ -2705,6 +2760,30 @@ carried: it described three outcomes and returned none of them. argument about windows: step 1's answer is the decision, and step 2 runs only in the world where step 1 said nothing has moved. + **The incarnation is derived too, and it has to be.** The coordinator's + `fresh_incarnation/2` hashes `make_ref()` + (`session_coordinator.ex:1500-1509`), so two fences built from one unmoved + head would carry the same `tx_id` and **different** incarnations — and the + adapter refuses that: `resolve_known/2` compares the re-presented + transaction's immutable binding with the retained one and answers + `{:not_committed, :tx_id_conflict}` when they differ + (`state.ex:137-144`). A successor resolving an unknown fence, or a second + drain on a root whose head never moved, would meet that conflict rather + than the resolution it asked for. The founding rule wants the preallocated + ID bound to the canonical mutation digest + (`vision-technical.md:710-716`), and a random incarnation is what breaks + that binding. So the fence's incarnation derives from the same three inputs + the `tx_id` does, through the same `owner_identity/3` discipline, and a + re-presentation is **byte-identical**. + + A `:tx_id_conflict` is nonetheless given a row, because a rule with no + answer for a result the adapter can return is not total: it is handled + **exactly as `commit_unknown` is** — the head is reread, and it decides. A + moved head means the fence is done; an unmoved head with a conflict means + something re-presented a different binding at this version, which is a + defect, and the session is left `unsettled` with `{:unknown, head}` rather + than reported as fenced. + **`drain_id` survives as a report label and nothing more.** Core still mints one per call, with the generator it already uses for identifiers of its own (`:crypto.strong_rand_bytes(16)` rendered base16, @@ -2927,8 +3006,14 @@ information lost on the way. **The steps below are the fail-stop path for every fatal class, not only the two store ones.** Store loss is the instance worth reading first because it is the one where the thing the daemon would otherwise stop is already gone; the -other six differ only in which component is missing by the time the owner -runs them. In all eight the owner has a class in hand, runs no ordered +other **nine** differ only in which component is missing by the time the owner +runs them. **Eleven classes reach this path**, one per linked component of the +fixed set: the two store classes, and `transfers_lost`, +`workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, +`capability_lost`, `runtime_lost`, `relay_lost` and `listener_lost` — ten in a +daemon without artifact transfers. Earlier revisions said six and eight here, +which was the count from a design with fewer linked processes. In every one of +them the owner has a class in hand, runs no ordered sequence, and does not return to serving. A step whose component is already gone is a no-op, by the rule the `stopping` field states above: under `listener_lost` steps 1 and 2 are already true and the clients of that @@ -2940,7 +3025,7 @@ to write. 2. Close every connection, after one bounded best-effort `daemon.stopping` carrying that class: `store_lost`, or `store_capacity_exceeded` when the store's own reason was the capacity refusal, and the failed component's own - class on the other six. + class on the other nine. 3. **Stop the executor** — on every class but `executor_lost`, where it is the component that already died — under the same discipline as every other stop: a monitored helper calling @@ -2960,7 +3045,7 @@ to write. 4. **Stop the Store — on every class except the two store classes.** Where the Store terminated itself, `store_lost` or `store_capacity_exceeded`, it is already gone and its `terminate/2` has already released the marker; there - is nothing to stop. On the other six, the Store is **still alive**, and + is nothing to stop. On the other nine, the Store is **still alive**, and because `System.halt/1` runs no `terminate/2`, halting past it would leave the marker file behind on a daemon that shut down deliberately. So the owner stops it here, in **its own fixed 30-second phase**, exactly as the From c547962e84ac60130fadfc2b3ebce5970b48531c Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:52:56 -0700 Subject: [PATCH 134/585] plan(M5): the lease holder is not idle, and eight smaller repairs F10. Idle eviction would have closed a healthy controller. A controller of a quiet session -- one waiting on a long model call, a slow tool or an unanswered interaction -- consumes nothing for minutes, and evicting it closes the connection its lease is bound to, after which only expiry frees the lease, so the session is uncontrollable for the rest of the term and the outgoing controller is told nothing it can act on. A connection holding a lease is now exempt while it holds it; renewals are its activity, and a controller that stops renewing loses the lease on its own clock and becomes an ordinary observer. What resets the interval is stated: any durable record completely emitted to that connection, or any request it sends. A coalesced progress item and a record buffered but not finished do not, those being the cases where the peer may be the one that stopped reading. F11. `writer_epoch` had no type, optionality or list. It is a required binary identity of at most 64 bytes on nine requests, absent and refused on every other, in a table beside the rest of the DTOs. F12. The witness rule claimed the ADRs' witnesses name file, case and lane, and pointed at a documentation checklist that reads no test identities as the enforcement point. It is narrowed to this pair, whose tables carry those three for every witness the ADRs describe -- the smaller of the two changes -- and the enforcement point is review, named as such. F13. Five gate conditions and six refusal cases read as a disagreement. Both numbers stay and the mapping is written out: two of the six exercise the holder-connection condition. F14. A `session.release_control` without `writer_epoch` is malformed, so it is ADR 0023's `invalid_request` (`0023-technical:304-307`), not `control_not_held` -- the gate is not reached. F15. ADR 0032 still called the lease-owner rule fatal. F16. Outcome 6 claimed two concurrent invocations complete "with their own credentials" while one runtime composes one token. They complete with their own senders and frames and the same credential; two *runtimes* is the isolation case. F17. The connection ceiling bounded nothing without a deadline on the handshake: a peer that connects and says nothing held a slot indefinitely. An accepted connection that has not completed `initialize` within the lease term is closed, that number reused rather than chosen. F18. The drain's "phase one" and "phase two" were a second numbering beside the seven. They are phases 2 and 3. F19. `loopex.ex:87-91` and `:110-113` are `:87-95` and `:110-117`. --- ...tachment-residency-and-replay-technical.md | 78 +++++++++++++++++-- ...-daemon-attachment-residency-and-replay.md | 8 +- ...controller-lease-and-takeover-technical.md | 32 +++++++- docs/plans/M5-technical.md | 46 +++++++---- docs/plans/M5.md | 10 ++- 5 files changed, 146 insertions(+), 28 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 3d7343766..fffce99d8 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -123,7 +123,29 @@ the unknown-field rule are reused from ADR 0023 unchanged. **Request records are the one exception**, and they are reused with one addition rather than unchanged: every existing-session mutation in generation 2 carries `writer_epoch`. That is the addition, and it is the reason generation 2 needs -a schema digest of its own. A connection is +a schema digest of its own. + +**The addition, at the exactness a vector needs**, because "carries +`writer_epoch`" is not a type, an optionality or a list: + +| Generation-2 request | `writer_epoch` | +| --- | --- | +| `session.resume` | **binary identity, ≤ 64 bytes, required** | +| `session.prompt` | the same | +| `session.steer` | the same | +| `session.follow_up` | the same | +| `session.abort` | the same | +| `session.respond_interaction` | the same | +| `session.admit_resources` | the same | +| `session.activate_skill` | the same | +| `session.release_control` | the same — it is lease-authorized like the eight, though it starts no core call and takes no relay ticket | +| `session.create`, `session.attach`, `session.list`, `daemon.status`, `session.acquire_control`, and every ADR 0023 query | **absent, and refused if present** — an unknown field refuses before a facade call under ADR 0023's own rule (`0023-…-technical.md:131-136`) | + +It is **required**, not optional: an absent `writer_epoch` on one of the nine +is a malformed request, answered with ADR 0023's `invalid_request`, and never +`control_not_held` — the gate has not been reached, because there is nothing +well-formed to put through it. Every other field of those requests is ADR +0023's, unchanged. A connection is one attachment after `session.attach`; generation 2 permits a connection to hold at most one attachment at a time and a client process to hold as many connections as the residency limits admit. @@ -304,7 +326,7 @@ errors answering one request: each carries that request's `request_id`, no | Code | Answers | Carries beyond the envelope | | --- | --- | --- | | `control_held` | `session.acquire_control` | **Nothing.** It does *not* carry the current epoch: an epoch is authority-shaped, and handing one to a client that was just refused is exactly the value it must not have. An earlier revision of ADR 0033 said it named the current epoch; that is withdrawn | -| `control_not_held` | `session.release_control` from a non-holder, **and every lease-authorized existing-session mutation whose combined admission gate fails** — wrong connection, wrong epoch, released lease, expired lease, or an attachment without controller capability | **Nothing**, deliberately: the five conditions are indistinguishable on the wire, because saying which one failed would make the refusal an epoch and lease oracle. ADR 0033 fixes the gate; this is the one answer it has | +| `control_not_held` | `session.release_control` from a non-holder, **and every lease-authorized existing-session mutation whose combined admission gate fails** — any of the **five** conditions ADR 0033 lists: wrong connection, wrong epoch, a lease that is not `held`, a deadline already passed, or an attachment without controller capability. A request missing `writer_epoch` altogether is `invalid_request` instead, being malformed before the gate | **Nothing**, deliberately: the five conditions are indistinguishable on the wire, because saying which one failed would make the refusal an epoch and lease oracle. ADR 0033 fixes the gate; this is the one answer it has | | `control_pending` | `session.acquire_control` that waited out its deadline | nothing | | `control_capacity_reached` | any lease operation beyond the 512 concurrent-owner cap | nothing | | `session_dormant` | `session.attach` | nothing | @@ -357,6 +379,29 @@ boundary pair: the 512th connection initializes and is served, the 513th is refused `capacity_exceeded` and closed, and closing one of the 512 lets the next through. +**An accepted connection that never initializes is closed on a deadline**, and +without one the ceiling would be a ceiling on nothing: a peer that connects +and then says nothing occupies a slot for as long as it likes, and 512 of +them would refuse every real client while the daemon held 512 silent sockets. +Nothing else releases such a connection — there is no attachment to evict, no +lease to expire, and ADR 0023's connection-state rules govern what a +connection may *do* before `initialize`, not how long it may take. So an +accepted connection that has not completed `initialize` within the **lease +term, 30 seconds**, is closed. That number is reused rather than chosen: it is +already this milestone's one connection-lifetime bound, fixed by ADR 0033 and +listed in this pair's limits as `lease_term_ms`, and a `initialize` handshake +is one frame each way on a local socket, so thirty seconds is a ceiling no +honest client approaches. The close carries no record — the connection has +negotiated nothing, so there is no generation whose error shape it could be +sent in — exactly as the peer-credential refusal closes before initialize. + +Its witness is the pair that must differ: a connection accepted and left +silent is asserted **closed** after the term and the slot it held asserted +free, while one that completes `initialize` inside it is asserted to stay open +indefinitely with no such close. It is a long-duration bound, so it is tagged +`long_bound` and injected where it is armed, with the production default +asserted once. + The tables above are the contract for both directions; an earlier revision kept a second, prose summary of the same four methods beside them, which is exactly how two descriptions of one wire drift apart. It is gone, and the @@ -683,7 +728,9 @@ out to the daemon would export core's supervision topology across the boundary and invite the daemon to reason about it. M5's core changes stay at five, and neither of these is among them. -The lease-owner fatal rule in ADR 0033 is untouched by this and stays. The +ADR 0033's lease-owner rule is untouched by this and stays — and it is a +**session-scoped** rule, not a fatal one; this sentence said "fatal" from the +revision before that decision was taken. The difference is ownership: a lease owner is a **daemon** process holding daemon-only state that nothing can reconstruct, so losing it is the daemon's failure to handle; a coordinator is core's, supervised by core, and its loss @@ -1037,9 +1084,30 @@ delivered contiguously after the snapshot. The daemon adds: a journal transaction, and by the same record-then-close; - 64 attachments per session and 512 per daemon, refused at attach with a stable reason when exhausted; -- eviction of an attachment that has consumed nothing for ten minutes; the +- eviction of an **observer** attachment that has consumed nothing for ten + minutes; the `detached` record names the cursor the client may resume from and the - connection is closed with it; + connection is closed with it. + + **A connection holding a controller lease is exempt while it holds it**, and + that exemption is a correction rather than a convenience. A controller of a + quiet session — one waiting on a long model call, a slow tool or an + unanswered interaction — consumes nothing for minutes at a time and is + perfectly healthy; evicting it would close the connection its lease is bound + to, and ADR 0033 frees a lease early only on an explicit + `session.release_control`, so the session would then be uncontrollable until + the term expired, with the outgoing controller told nothing it could act on. + Renewals are that connection's activity, and they are already required every + ten seconds against a thirty-second term, so a controller that has stopped + renewing loses its lease on its own clock and becomes an ordinary observer, + at which point the idle interval applies to it like any other. + + **What resets the interval**, stated because "consumed nothing" is not a + mechanism: any **durable record the daemon completely emits to that + connection**, and any **request that connection sends**. Either is evidence + of a live peer. Progress that is coalesced or dropped does not reset it, and + neither does a record the daemon buffered but did not finish writing — the + cases where the client may be exactly the one that has stopped reading; - transient progress coalesced per attachment and dropped first under pressure, with a counted drop; no progress item ever waits on a journal transaction. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 1d3aca5aa..ee9450860 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -108,9 +108,11 @@ succeeds; `cursor_expired` remains the defined response a compacting adapter returns for a cursor older than its retained history, and no M5 path produces it. Each connection owns a bounded socket output buffer; a slow attachment is detached at its last completely emitted -cursor while every other attachment continues. Idle attachments are evicted -at the residency limit and reconnect at their retained cursor with no -missing durable event. **Every detach the daemon initiates is a record and a +cursor while every other attachment continues. Idle **observer** attachments +are evicted at the residency limit and reconnect at their retained cursor with +no missing durable event; a connection holding a controller lease is exempt +while it holds it, because a controller of a quiet session is healthy and +evicting it would strand a lease only an explicit release can free. **Every detach the daemon initiates is a record and a close**: the client is told, best-effort, on the connection being ended, and that connection is closed with its attachment while every other connection is untouched. A connection holds one attachment, so there is nothing for it to diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index b3bd81c89..9d958dc46 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -154,6 +154,14 @@ lease record by another name, which this decision rejects for its own reasons. The relay is not that: it holds no lease and no authority, only the fact that a call it made has not yet been accounted for. +A holder's connection is **exempt from ADR 0032's idle eviction while the +lease is held**, for the reason that decision states: evicting it would close +the connection the lease is bound to, and only an explicit +`session.release_control` frees a lease early, so the session would be +uncontrollable until the term ran out. A holder that stops renewing loses the +lease on its own clock and becomes an ordinary observer, evictable like any +other. + Expiry and admission use the daemon's monotonic clock: a deadline is set only by a successful grant or renewal, and a wall-clock jump cannot shorten or extend @@ -219,7 +227,13 @@ the local store's writer marker, unchanged. `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, `session.respond_interaction`, `session.admit_resources` and `session.activate_skill`, carries - `writer_epoch`. The daemon admits it only if the sending connection is the + `writer_epoch` — a **required** binary identity of at most 64 bytes, exactly + as ADR 0032's request table fixes it, together with + `session.release_control`, which is lease-authorized in the same way though + it starts no core call. A request of those nine that omits it is malformed + and answered with ADR 0023's `invalid_request` + (`0023-…-technical.md:304-307`), never with `control_not_held`: the gate is + not reached, because there is nothing well-formed to put through it. The daemon admits it only if the sending connection is the recorded holder, the epoch matches, the lease state is `held`, the deadline is later than the live daemon's monotonic admission time, and the connection holds a controller-capable attachment, except that a verified @@ -244,8 +258,20 @@ the local store's writer marker, unchanged. about the current holder's lease, epoch or deadline. Queries and attach carry no epoch and pass no gate. - The witnesses assert the six refusals separately in the daemon's own state — - which condition each case constructed — and assert that all six are the + **Five conditions, six cases**, and the mapping is written out so the two + numbers stop reading as a disagreement: + + | Case | Condition it fails | + | --- | --- | + | A stale epoch from the previous tenure | epoch equality | + | An observer replaying the **current** epoch it saw | holder connection — the epoch matches, the connection is not the holder | + | A mutation from a connection that never acquired | holder connection | + | A mutation after `session.release_control` | `held` state | + | A mutation after the term elapsed | unexpired deadline | + | A mutation from a connection with an observer-only attachment | controller-capable attachment | + + The witnesses assert each case separately in the daemon's own state — which + condition it constructed — and assert that all six produce the **same** code and the same fields on the wire, which is what stops a later revision from helpfully differentiating them. - `session.create` has no `writer_epoch` because the session lease does not diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 84e28ea72..049771e09 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -145,10 +145,10 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and **every ticket it holds has settled** — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to have settled by the time the acknowledgement returns, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create` and `session.attach` sent after the cut refused the same way, the two cases that would fail if either bypassed the relay, and a third asserting no `Control` entry changes between the acknowledgement and quiesce's enumeration; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the six ways that gate fails asserted separately in the daemon's own state and asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch` and to refuse `control_not_held` without it. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete with their own credentials. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -364,13 +364,29 @@ triggers, and the adapter's credential suite proves a real invocation is not traceable. Neither can reach the branches above, and neither is asked to. **Test honesty.** Future test bodies are written with their implementation; a -missing witness is never a pass. **Every witness this pair or an ADR in this -set describes names three things when it is written: the exact file, the case +missing witness is never a pass. **Every witness named in this plan pair names +three things: the exact file, the case name, and the lane it runs in** — `fast` for `bash scripts/check.sh`, `release` for `bash scripts/check-release.sh`, and `attended` for the two release cases that need a person. A witness described only by what it asserts -is a witness nobody can find at closure, and the derived checklist in Outcome -5's evidence row is where the three are checked against what exists. Real-provider cases live in their own files +is a witness nobody can find at closure. + +**The rule is the plan's, not the ADRs', and an earlier revision extended it +to both and then named an enforcement point that cannot enforce it.** ADR +0031, 0032 and 0033 describe their evidence in prose, as accepted ADRs in this +repository do, and rewriting three proposed ADRs into three-column tables buys +nothing a reader needs: the decisions are what those files are for. So the +obligation sits where the tables already are — **this pair's witness tables +carry the file, case and lane for every witness the ADRs describe**, and a +witness an ADR names with no row here is a gap this pair closes, not a defect +in that ADR. That is the smaller of the two changes and it is the one taken. + +And the enforcement point is **review**, stated plainly. The earlier revision +pointed at the derived documentation checklist in Outcome 5's evidence row, +which lists every tracked file under `docs/operator/` and `docs/developer/` +and reads none of them for test identities — it could not check this and was +never going to. An independent reviewer reading the candidate against these +tables is what checks it, as it is for every other claim in this pair. Real-provider cases live in their own files under the `real_provider` tag. A daemon that proxies several socket connections to one replaceable core attachment cannot satisfy Outcome 4, because independent concurrent attachments, lifetime with zero attachments, @@ -953,7 +969,7 @@ is the half an earlier revision left unsaid. `Loopex.Runtime.create_session/3` and `resume_session/3` are specified `{:ok, binary()} | {:error, term()}` (`runtime.ex:156`, `:169`), and the embedded facade forwards exactly that: `Loopex.create_session/3` returns what `Runtime.create_session/3` returns -(`loopex.ex:87-91`) and `Loopex.resume_session/3` likewise (`:110-113`). +(`loopex.ex:87-95`) and `Loopex.resume_session/3` likewise (`:110-117`). Widening those returns would change what a released embedded caller receives from a call it already makes — a compatibility break taken for a daemon's bookkeeping. @@ -964,7 +980,7 @@ So core change 5 adds **two daemon-facing functions beside them**, `{:ok, %{session_id: binary(), disposition: :fresh | :historical, control_entry: :active | :dormant}} | {:error, term()}`. The existing pair keeps its exact spec and its exact return, implemented as a projection of the -detailed one, so `loopex.ex:87` and `:110` forward what they forward today and +detailed one, so `loopex.ex:87-95` and `:110-117` forward what they forward today and no embedded caller sees anything move. The daemon calls the detailed pair, which is the only caller that needs them. @@ -2554,7 +2570,8 @@ carried: it described three outcomes and returned none of them. **Three parts, in order, and the first two are one thing split in half.** -1. **Phase one: every live coordinator admits the abort, and then stops.** +1. **Phase 2 of the stop, the abort admission: every live coordinator admits + the abort, and then stops.** ADR 0023 fixes that *only* the durable `session.abort` command cancels, and that cancellation is "never inferred from EOF or death" (`0023-…-technical.md:365`, with the method table at `:169`). Quiesce @@ -2580,8 +2597,8 @@ carried: it described three outcomes and returned none of them. (`:1750-1761`), which is the right answer for an idle session and needs no special case. -2. **Phase two: cancellation is released, concurrently, only once every - admission has resolved.** Core waits for phase one to finish for every +2. **Phase 3 of the stop, the cancellation: it is released, concurrently, + only once every admission has resolved.** Core waits for phase 2 to finish for every session — committed, refused as having no active run, or failed — and then releases the paused cleanups together. That is what makes the Concept's ordering true globally rather than per session, and it is also why the two @@ -2853,8 +2870,8 @@ carried: it described three outcomes and returned none of them. precisely the case where the daemon says so rather than pretending, and it says so in a key a caller can read. - **Phase two never releases a session whose admission it cannot account - for.** A session whose phase-one abort admission **failed or is ambiguous** + **Phase 3 never releases a session whose admission it cannot account + for.** A session whose phase-2 abort admission **failed or is ambiguous** — a refusal that is not `rejected_no_active_run`, or a `commit_unknown` on the admission itself — has no cleanup released for it at all. It is fenced like an unsettled session, or, where the fence too is unknown, left fenced @@ -3858,7 +3875,7 @@ nothing and add no wire surface: they exist because core computes `fresh?` at caller unable to tell a fresh create from a replay. They are new functions rather than widened returns because widening `create_session/3` would change what `Loopex.create_session/3` forwards to a released embedded caller -(`loopex.ex:87-91`), which is a compatibility break bought for a daemon's +(`loopex.ex:87-95`), which is a compatibility break bought for a daemon's bookkeeping. Direct code cannot supply them, because the only alternative is inferring the answer from side effects, which is a race. **One bounded `quiesce/1`** — which unifies nothing today and says so: @@ -3914,6 +3931,7 @@ line; M5 introduces none of its own. | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | | Concurrent connections per daemon | 512, the attachment number reused; the 513th is refused `capacity_exceeded` at `initialize` and closed | ADR 0032 | +| Time an accepted connection may take to complete `initialize` | 30 s, the lease term reused, after which it is closed with no record; without it the connection ceiling would bound nothing | ADR 0032, against ADR 0033's `lease_term_ms` | | Attachments per session | 64 | ADR 0032 | | Attachments per daemon | 512 | ADR 0032, its attachment-lifecycle list, with the limit key in its limits table | | Core event-count queue per attachment | 1,024 events | ADR 0032 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index c06f91600..168784c2f 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -122,7 +122,9 @@ acquiring control and attaching. Dormancy is about attachments, never about a coordinator. A session the daemon has activated keeps its coordinator until the daemon exits: idle eviction -releases an attachment, its resident window and its output buffer, and the +releases an **observer's** attachment, its resident window and its output +buffer — a connection holding a controller lease is exempt while it holds it, +its renewals being its activity — and the work beneath them continues. It has to be that way for two reasons. A session with every client detached may still have a model request in flight, a tool effect dispatched, an interaction awaiting an answer, a recovery running, an @@ -386,10 +388,12 @@ did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. **The drain has a mechanism, and it is core's.** M5 adds `quiesce/1` to -`Loopex.Runtime`, and it has three parts. **Phase one** durably admits the +`Loopex.Runtime`, and it has three parts — which are stop **phases 2, 3 and +4**, the numbering the bound uses, rather than a second scheme of its own. +**Phase 2** durably admits the existing abort command for every active session and stops there, because ADR 0023 fixes that only a durable `session.abort` cancels and nothing may infer -cancellation from a signal. **Phase two** releases every session's +cancellation from a signal. **Phase 3** releases every session's cancellation, concurrently, only once every admission has resolved — which is what makes "every abort durable before any cancellation" true across the daemon rather than one session at a time. The record it writes is the one a client's own abort writes, under a From b8af6b909617a86520a2bc1664dbf2b51febd43d Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:54:13 -0700 Subject: [PATCH 135/585] plan(M5): adversarial pass over the second review round Class 5, Concept versus Technical: M5.md still described the relay as holding a ticket for every lease-authorized mutation, which is eight of the ten it now holds, and said nothing about the cut it answers. Both are in the Concept. Class 7, stale vocabulary: Outcome 1 still called the drain "two phases" after the numbering moved to the stop's own phases 2 and 3. Class 30, result totality: the reservation table's refusal row covered "either call" and left attach out, although attach's first leg can now refuse on its 5 s default. It covers all three, and says why an attach refused at that leg is an ordinary refusal -- `begin_attach/3` mutates nothing (`control.ex:1235-1251`). Class 25, unobservable resolution: the idle-eviction exemption had no witness that could fail. It has the pair that must differ -- a controller consuming nothing across the interval asserted still attached and still holding, an observer on the same session across the same interval asserted evicted and closed -- and a second case that stops the renewals and asserts the controller is then evicted like any observer, which is what proves the exemption belongs to the lease rather than to the connection. --- ...32-daemon-attachment-residency-and-replay-technical.md | 8 ++++++++ docs/plans/M5-technical.md | 4 ++-- docs/plans/M5.md | 5 ++++- 3 files changed, 14 insertions(+), 3 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index fffce99d8..6d76f7dca 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -1102,6 +1102,14 @@ delivered contiguously after the snapshot. The daemon adds: renewing loses its lease on its own clock and becomes an ordinary observer, at which point the idle interval applies to it like any other. + Its witness is the pair that must differ: a controller of a session with a + long-running model call, consuming nothing for longer than the interval, is + asserted **still attached and still holding its lease**, while an observer + on the same session across the same interval is asserted evicted and closed. + A second case stops the controller's renewals and asserts that once the term + elapses it is evicted like any observer, so the exemption is proved to be + the lease's and not the connection's. + **What resets the interval**, stated because "consumed nothing" is not a mechanism: any **durable record the daemon completely emits to that connection**, and any **request that connection sends**. Either is evidence diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 049771e09..c7a43a82c 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and **every ticket it holds has settled** — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to have settled by the time the acknowledgement returns, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create` and `session.attach` sent after the cut refused the same way, the two cases that would fail if either bypassed the relay, and a third asserting no `Control` entry changes between the acknowledgement and quiesce's enumeration; then core's `quiesce/1` running two phases — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and **every ticket it holds has settled** — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to have settled by the time the acknowledgement returns, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create` and `session.attach` sent after the cut refused the same way, the two cases that would fail if either bypassed the relay, and a third asserting no `Control` entry changes between the acknowledgement and quiesce's enumeration; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -1119,7 +1119,7 @@ leaked until the daemon restarts: | Resume, `disposition: :fresh` | **Converted** — a coordinator started | | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | | Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | -| Either call refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, any other `{:error, _}` | Released | +| Any of the three refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, an attach whose first leg answers `{:error, :runtime_unavailable}` on its 5 s default, any other `{:error, _}` | Released. An attach refused at its first leg is the same case as any other refusal, because that leg mutates nothing (`control.ex:1235-1251`) | | A **resume** whose connection is lost while the call is in flight | **Held, then resolved by the relay**, which holds the call's real answer whether or not the process that asked is still there; where the daemon must re-establish it later, the client's replay under its original `command_id` carries the same `disposition`/`control_entry`. The existence query cannot answer this — it says `present` either way | | A **create** whose connection is lost while the call is in flight | **Held, then resolved by the relay** the same way; a later replay under the same `command_id` returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | | An **attach whose connection process ends before it answers** | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment, and core change 1 monitoring the attaching process. The daemon closes that connection, its process ends, and the dispatcher's `DOWN` handler drops the attachment. Nothing is observed, because nothing needs to be | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 168784c2f..8e0215224 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -618,7 +618,10 @@ assembles in its caller's process — the Store adapter, the runtime root, the artifact transfers owner where enabled, the workspace lease and the local executor — plus five of the daemon's own: the credential routing registry, the custody process and the tracing capability ADR 0034 gives the host, the -**admission relay** that holds a ticket for every lease-authorized mutation, +**admission relay** that holds a ticket for every one of the ten calls the +daemon makes that change core state — the eight lease-authorized mutations, +`session.create` and `session.attach` — and whose acknowledged cut is what an +orderly stop closes admissions with, and the listener. Ten where transfers are enabled, nine where they are not. **Beside them it links one lease owner per session under lease or acquisition**, started at the first lease operation rather than at activation, retired when the lease is free and From 7622073c2e8a5aef2190ddbbecb211378e4fc3f6 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 13:54:56 -0700 Subject: [PATCH 136/585] plan(M5): the concept's cut says settled too --- docs/plans/M5.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 8e0215224..97d313218 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -67,7 +67,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — so a command whose ticket the relay recorded before the cut settles or is fenced under the drain, and one arriving after it is refused `daemon_stopping` — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — the relay answering only when every ticket it holds has **settled**, so a command admitted before the cut has finished inside core before the drain begins and one arriving after it is refused `daemon_stopping` — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | From e8a5b4a84eaa94d31f63e5b3e7a4c37f2c502eb4 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:10:43 -0700 Subject: [PATCH 137/585] plan(M5): split the cut into close and settle, and count phase 2 P0-1. Phase 1 was five seconds and waited for every ticket to **settle** -- and a ticket settles only when its core call answers, a prompt's commit being bounded by the Store's 30 s and by core's one retry, with `SessionCoordinator.command/3` waiting `:infinity` for it (`session_coordinator.ex:146-149`). A `SIGTERM` during any ordinary prompt would have blown that acknowledgement and turned an operator stop into `relay_lost`. It is now two phases. **1a, close**: the relay sets its flag, refuses everything after it and answers; five seconds bounds the relay's responsiveness and nothing else, which is also the honest form of the "no work of its own" justification. **1b, settle**: the owner waits for the tickets already inside core, concurrently, bounded at the deepest ticket kind's own Store-call depth, derived per kind from the code -- two for the seven non-resume mutations (`:1761-1764`; the wait-behind cannot apply, the call being the session's one in-flight transaction), **six** for a fresh `session.create` (`control.ex:960`, then the coordinator must reach `:ready`: `:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`), and **no constant at all** for attach and resume, which page over the root's history at `@page_size 1_024` (`:49`, `:7076-7081`). Six is the maximum over the kinds that have one, so 1b is 180 s -- and the two paged kinds are why 1b is a bounded wait that then **proceeds** rather than a guarantee. Proceeding has a stated cost. A still-running mutation leaves its session `:active` and it drains normally; a still-running create or resume leaves it **`:acquiring`**, so that row is live on this path rather than defensive, and the argument that called it unreachable -- which rested on the cut waiting unconditionally -- is withdrawn with the reasoning that replaced it. An attach still settling changes no classification: it installs into the dispatcher. P0-3. Phase 2 under-counted twice. The wait-behind transaction is two calls, not one, because an ordinary commit re-presents once on `commit_unknown` (`resolve_transaction/2`, `:1752-1768`). And the drain's own abort would have taken that same retrying path, which contradicted this file's own rule that an ambiguous admission is not retried -- the "admission path otherwise untouched" sentence and that rule cannot both hold. The drain's abort now commits through a **non-retrying** path, recorded as the **second half of core change 4's coordinator change** beside the admit-and-pause split: one change, two halves, one clause, named in the concept pair's core-change list, the ownership table, the minimalism budget and the quiesce witness list. Phase 2 is three calls, 90 s. The operator maximum is **`budget_ms` + 405 s**, with the sentence that keeps it from being read as a duration: every fixed term counts the adapter's thirty-second ceiling for a wedged filesystem, and an ordinary stop finishes in milliseconds. --- docs/plans/M5-technical.md | 189 +++++++++++++++++++++++++++---------- docs/plans/M5.md | 15 ++- 2 files changed, 151 insertions(+), 53 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index c7a43a82c..719405759 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not, together with the one coordinator change it needs in two halves — a drained abort pauses where cleanup would have begun, and its commit is presented once rather than retried on an ambiguous answer**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -294,9 +294,13 @@ reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop as the sum of the seven phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 195 s**, being 5 s for the admission cut, 60 s for abort + **`budget_ms` + 405 s**, being 5 s for closing admissions, 180 s for + settling what was already admitted, 90 s for abort admission, `budget_ms` for cancellation, 90 s for the fence, 5 s for coordinator termination, 5 s for daemon teardown and 30 s for the Store — + together with the sentence that keeps the number from being read as a + duration: every fixed term counts the Store's thirty-second ceiling for a + wedged filesystem, and an ordinary stop finishes in milliseconds — with the six constants written out beside the one derived term, so an operator setting a `TimeoutStopSec` adds up numbers rather than trusting a total. It must say that six of the seven are fixed and @@ -341,7 +345,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -2117,17 +2121,26 @@ that already exists somewhere, and the operator maximum is the sum: | # | Phase | Bound | Where the number comes from | | --- | --- | --- | --- | -| 1 | **Admission cut** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement from a process with no work of its own to finish; a relay that does not answer inside it is a relay the daemon has lost, so the stop becomes the `relay_lost` fail-stop rather than waiting longer | -| 2 | **Abort admission** | **60 s** — **two** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission may have to wait behind the transaction the coordinator already has in flight, and then make its own; those are sequential, so the phase is two calls long | +| 1a | **Close admissions** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement of a **state change**, not of any work: the relay sets a flag, refuses everything after it, and answers. It has nothing to finish, so this bound measures the relay's own responsiveness and nothing else; a relay that does not answer inside it is a relay the daemon has lost, and the stop becomes the `relay_lost` fail-stop | +| 1b | **Settle the admitted** | **180 s** — **six** Store calls deep, the deepest ticket kind; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | +| 2 | **Abort admission** | **90 s** — **three** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission may wait behind the transaction the coordinator already has in flight, which is itself two calls because core's ordinary path retries a `commit_unknown` once; then the drain's own admission, which is one call because it does **not** retry | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | | 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`) | The value core already gives a coordinator to stop in | | 6 | **Daemon teardown** | **5 s** | This plan's one chosen number, covering the notice, the closes, the lease owners, the relay and the edges | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 5 s + 60 s + `budget_ms` + 90 s + 5 s + 5 s + 30 s -> = `budget_ms` + 195 s**, and `budget_ms` is the one term an operator cannot -> compute in advance. +> **Maximum graceful stop = 5 s + 180 s + 90 s + `budget_ms` + 90 s + 5 s + +> 5 s + 30 s = `budget_ms` + 405 s**, and `budget_ms` is the one term an +> operator cannot compute in advance. + +**That is a worst case nobody approaches, and saying so is part of stating +it.** Every term but `budget_ms` is a count of the local adapter's 30 s +`@call_timeout`, and that timeout is a ceiling for a wedged filesystem, not a +cost: the calls it bounds are a `File.read`, an append and a directory sync, +microseconds apiece on a working disk. An ordinary stop of an idle daemon +finishes in milliseconds. The sum is what a `TimeoutStopSec` must not be +shorter than if a stop is never to be cut off, not what a stop takes. **Every phase bound is a Store-call count, and an earlier revision counted one where the sequence is two or three.** *Every* call into the local adapter @@ -2137,27 +2150,56 @@ is the same 30 s: `transact/2` at `local.ex:111-113`, `ownership_head/3` at **(the worst sequential count of Store calls in it) × 30 s**, and the counts are these: -- **Phase 2 is two.** The abort admission goes to a **live coordinator**, whose +- **Phase 1b is six, and the derivation is per ticket kind.** A ticket settles + when its core call answers, and what that call does before answering is not + the same for all ten. Counted from the code, in sequence: + + | Ticket kind | Sequential Store calls before the ticket settles | Where | + | --- | --- | --- | + | The seven non-resume lease-authorized mutations — `prompt`, `steer`, `follow_up`, `abort`, `respond_interaction`, `admit_resources`, `activate_skill` | **2** | One `OwnerLane.transact/2`, retried once on `commit_unknown` (`session_coordinator.ex:1761-1764`). The wait-behind does **not** apply: this call *is* the session's one in-flight transaction, and the coordinator's `command/3` waits `:infinity` for it (`:146-149`) | + | `session.create`, fresh | **6** | `Store.runtime_command/2` for the genesis command (`control.ex:960`); then the coordinator it starts must reach `:ready` before the reply, which is `load_all_records` (one empty page, `:1302-1309`, `:7076-7081`, `@page_size 1_024` at `:49`), `ownership_head` (`:1338`), the owner `OwnerLane.transact` (`:1363`), then `recover_committed_owner`'s `load_all_records` and `load_all_events` (`:1397-1400`) before `phase: :ready` at `:1407` | + | `session.attach` | **1 + ⌈events ÷ 1,024⌉** | The dispatcher's snapshot scan pages the session's events (`event_dispatcher.ex:169-199`, `:926`) | + | `session.resume`, fresh | **6 + the pages its history needs** | The same six as a create minus the genesis command, plus `prior_transaction_resolved`'s `transaction_status` (`:1324-1335`), and with every one of the three `load_*` calls paged over real history rather than over an empty session | + + **The maximum over the kinds whose depth is a constant is six**, which is a + fresh create, so 1b is bounded at six calls. **Two kinds have no constant + depth** — attach and resume both page over the root's history at 1,024 rows + a call — and that is stated rather than papered over with an average, + because it is the reason 1b is a **bounded wait that then proceeds** rather + than a guarantee that everything has settled. +- **Phase 2 is three.** The abort admission goes to a **live coordinator**, whose lane is serial — `OwnerLane.transact/2` is a plain synchronous call the coordinator makes from its own process (`store/owner_lane.ex:83-99`, called at `session_coordinator.ex:1242`, `:1363`, `:1702`) — so the admission may - wait out one transaction already in flight and then make its own. Two, in - sequence. + wait out one transaction already in flight and then make its own. The + wait-behind is **two** calls, not one: an ordinary commit goes through + `resolve_transaction/2`, which re-presents once on `commit_unknown` + (`:1752-1768`). The drain's own admission is **one**, because it does not — + see the non-retrying commit below. Three, in sequence. - **Phase 4 is three at worst.** A head read, then the `advance_owner`, then, only where that answers `commit_unknown`, **one** `transaction_status` query. -- **And the drain retries nothing**, which is what keeps both counts finite. - Core's ordinary commit path retries a `commit_unknown` once — - `resolve_transaction/2` re-presents the transaction on the second line of its - own case (`session_coordinator.ex:1761-1764`) — and the drain does not use - that path for either of these. An ambiguous **admission** is not retried: the - session is fenced, by the rule this section already states. An ambiguous - **fence** is resolved by the one status query, not re-proposed. A **stale** +- **And the drain retries nothing, which is a change to the coordinator rather + than a statement about it.** Core's ordinary commit path retries a + `commit_unknown` once — `resolve_transaction/2` re-presents the transaction + on the second line of its own case (`session_coordinator.ex:1752-1768`) — + and an earlier revision said the drain's abort "is not retried" while also + saying the admission path was "otherwise untouched". Those cannot both hold: + a drained abort that took the ordinary path **would** retry. So the drain's + abort admission commits through a **non-retrying** path, and that is the + **second half of core change 4's coordinator change**, beside the + admit-and-pause split — one change with two halves, both in the same clause + of the same function, and both named in the concept pair's core-change list + and in the ownership table. A `commit_unknown` on a drained abort is + therefore ambiguous immediately: the session is fenced, by the rule this + section already states. An ambiguous **fence** is resolved by the one status + query, not re-proposed. A **stale** fence is not reattempted at all, for the reason the fence table gives. **The seven phases and the six steps are two cuts through the same stop, and the mapping is stated rather than left to be inferred.** The numbered sequence below is what the daemon's owner *does*; the phases are what each part of it -is *bounded by*. Phase 1 is step 1's call to the relay. **Phases 2 to 5 are +is *bounded by*. Phases 1a and 1b are step 1: 1a is the owner's call to the +relay, 1b is the owner's wait afterwards. **Phases 2 to 5 are inside `quiesce/1`** — they are core's to enforce, because core owns the admission, the cancellation, the fence and the coordinator, and the daemon passes no deadline in — and together they are step 2. Of the four, only @@ -2334,17 +2376,40 @@ the owner fixes. even pass through the relay. Quiesce would then have been snapshotting a set of sessions that could still grow underneath it. - So the cut is a call. The owner calls the **relay** — whose scope this + So the cut is a call **and then a wait**, which an earlier revision folded + into one five-second step it could not possibly contain. The owner calls + the **relay** — whose scope this extends to cover `session.create` and `session.attach` as well as every - ticketed mutation, ten calls in all — and - the relay **acknowledges only when admissions are closed and every ticket - it holds has settled**. Not "settled or recorded": a recorded ticket is a - call still running inside core, and quiesce would then enumerate `Control` - while an admission, a create or an attach was still changing it. Until that - acknowledgement returns - the owner does nothing else; after it, no work can enter core through the - daemon at all, which is what lets quiesce treat `Control` as a set that no - longer moves. A command arriving on an open connection after the cut is + ticketed mutation, ten calls in all — and the relay **closes admissions and + answers at once**: that is phase **1a**, an acknowledgement of a state + change, five seconds being a bound on the relay's responsiveness and on + nothing else. The owner then **waits for the tickets already inside core to + settle**, which is phase **1b**, bounded at the deepest ticket kind's own + Store-call depth. + + Folding the two together was the defect: a ticket settles only when its + core call answers, a prompt's commit is bounded by the Store's 30 s and by + core's one retry, and `SessionCoordinator.command/3` waits `:infinity` for + it (`session_coordinator.ex:146-149`) — so a `SIGTERM` arriving during any + ordinary prompt would have blown a five-second acknowledgement and turned + an operator stop into `relay_lost`. Refusing new work is instant; waiting + for admitted work is not, and the two now have their own bounds. + + **At 1b's bound the stop proceeds**, and what that costs is stated. A + ticket still settling is a core call still running, so `Control` is not + quite the frozen set an unconditional wait would have given: a still-running + mutation leaves its session `:active`, which drains and fences exactly as + any other active session does, and a still-running **create or resume** + leaves it **`:acquiring`**, because that is the status `Control` writes + while an owner is being started. So the `:acquiring` row in the + classification table below is **live on this path, not defensive**, and it + is classified `unsettled` and fenced for the reason given there. An attach + still settling changes nothing about the classification at all: it installs + into the dispatcher, not into `Control`. + + After the cut, no work can enter core through the + daemon at all. A request of **any kind** arriving on an open connection + after it is refused **`daemon_stopping`**, a generation-2 error code added for it. Nothing is written to clients yet and nothing is closed: the connections @@ -2585,17 +2650,32 @@ carried: it described three outcomes and returned none of them. (`session_coordinator.ex:4806-4815`). Admitting session A's abort therefore begins A's cleanup while session B's abort is still unwritten. - So quiesce **splits admission from cleanup**, and the split is the change - to that path: under a drain, a coordinator admits the abort and **pauses at + So quiesce **splits admission from cleanup**, and that split is the first + of the **two halves** of core change 4's coordinator change: under a drain, + a coordinator admits the abort and **pauses at exactly the point `begin_admitted_cleanup/1` would have begun** — the record is committed, the queued steer and follow-up are resolved as they - already are, and no cancellation runs. The admission path is otherwise - untouched: `propose_new/3` for `%{type: :abort}` writes the same + already are, and no cancellation runs. + + **The second half is that a drained abort commits without the retry**, and + an earlier revision missed it by saying the admission path was "otherwise + untouched" four lines above a rule that an ambiguous admission is not + retried. Both cannot hold: an abort taking the ordinary path goes through + `resolve_transaction/2`, which re-presents once on `commit_unknown` + (`session_coordinator.ex:1752-1768`). Under a drain it presents **once** + and an unknown answer is an unknown answer, which is what makes phase 2's + third call the last one it can make and what lets the session be fenced + rather than waited on. Two halves, one clause, one change. + + **What is genuinely untouched is the record**: `propose_new/3` for + `%{type: :abort}` writes the same `command_admitted` record with `"command_type" => "abort"` and `"admission" => "accepted"` (`session_state.ex:1684-1700`), and answers `"admission" => "rejected_no_active_run"` where nothing is running (`:1750-1761`), which is the right answer for an idle session and needs no - special case. + special case. Nothing about what is written changes; what changes is + whether the commit is presented a second time and whether cleanup begins on + the reply. 2. **Phase 3 of the stop, the cancellation: it is released, concurrently, only once every admission has resolved.** Core waits for phase 2 to finish for every @@ -2890,19 +2970,26 @@ carried: it described three outcomes and returned none of them. | `:active` with a live coordinator | The ordinary case | `settled` or `unsettled`, by whether its cancellation finished inside the budget | Only when `unsettled` | | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes**, for the same reason: there is no coordinator, and there may be a transaction | - | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | **Cannot be reached after the cut** — see below — and, if one is found, `unsettled` | **Yes** | + | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No | - **`:acquiring` cannot exist once the cut has answered**, and the reason is - the cut rather than an assumption about timing. Only `session.create` and - `session.resume` put an entry into that status, both of them start a - coordinator inside the call, and both are **ticketed**; the cut answers only - when every ticket has **settled**, so no create and no resume is in flight - when quiesce begins. The daemon is the only host on this runtime, so there - is no other caller to have started one. It is nonetheless given a row — - treated as `unsettled` and fenced — because a classification that omits a - status the code can write is a classification a reviewer cannot check, and - fencing is the safe answer for a session whose ownership may be moving. + **`:acquiring` is reachable, and an earlier revision called it unreachable.** + That revision's argument was the cut: only `session.create` and + `session.resume` write that status, both start a coordinator inside the + call, both are ticketed, and the cut waited for every ticket to settle — so + none could be in flight. The argument died with the phase split. Phase 1b + waits for the admitted tickets and then **proceeds at its bound**, and a + resume whose replay is paging a long history is exactly the ticket most + likely to still be running when it does. So an `:acquiring` entry is an + ordinary outcome of a stop that fell back on its bound, not a defect. + + It is classified `unsettled` and **fenced**, which is the safe answer and + also the right one: the session's ownership is mid-advance, so either the + owner transaction commits — and the fence, reading a head that has moved, + is superseded and says so — or it does not, and the fence moves the epoch + under a candidate that will then be refused. Both are decided outcomes. + Quiesce admits no abort for it, because there is no ready coordinator to + admit one. **Where "reports" lands, since a list in a return value is not a surface.** The daemon has two places to put what quiesce answers, and it uses both: @@ -3878,7 +3965,10 @@ what `Loopex.create_session/3` forwards to a released embedded caller (`loopex.ex:87-95`), which is a compatibility break bought for a daemon's bookkeeping. Direct code cannot supply them, because the only alternative is inferring the answer from side effects, -which is a race. **One bounded `quiesce/1`** — which unifies nothing today and says so: +which is a race. **One bounded `quiesce/1`, and the one coordinator change it needs** — the +admit-and-pause split and the non-retrying drained commit, which are two +halves of one clause rather than two changes, and neither of which is +reachable from outside a drain. It unifies nothing today and says so: its only caller is the daemon's orderly stop, and the app-server host does not drain by hand, because `LoopexComposition.with_runtime/2` brackets a runtime that lives and dies with one client's stdin and has nothing to drain @@ -3946,14 +4036,15 @@ line; M5 introduces none of its own. | Socket path bound, over `/daemon/daemon.sock` | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | -| Phase 1, the admission cut | **5_000 ms**, the teardown number reused; an unanswered cut becomes the `relay_lost` fail-stop | This plan | -| Phase 2, abort admission | a fixed **60 s** — two sequential Store calls at the adapter's own 30 s `@call_timeout`, the admission waiting out at most one transaction already in the coordinator's serial lane and then making its own; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` | +| Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | +| Phase 1b, settling the admitted | **180 s** — six sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from `control.ex:960` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407` | +| Phase 2, abort admission | a fixed **90 s** — three sequential Store calls at the adapter's own 30 s `@call_timeout`: the two of a transaction already in the coordinator's serial lane, which retries a `commit_unknown` once, then the drain's own admission, which does not; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:1752-1768` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | | Phase 4, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | -| Maximum graceful stop | `budget_ms` + **195 s**, the sum of the six fixed phases above | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **405 s**, the sum of the seven fixed phases above; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 97d313218..348e0bc62 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -51,7 +51,9 @@ process-level exclusion its callees need, before any message is delivered, together with the one `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys, which is what keeps the credential token out of an entry on its way to the adapter; `quiesce/1`, the bounded settle an orderly stop -drains through; and two plain fields on **two new runtime-side functions beside** create and +drains through — which carries one coordinator change in two halves, an +admission that pauses where cleanup would have begun and a commit that does +not re-present itself on an ambiguous answer, both in the same clause; and two plain fields on **two new runtime-side functions beside** create and resume — `create_session_detailed/3` and `resume_session_detailed/3`, so the existing pair keeps its exact return and the embedded facade forwards what it forwards today — `disposition`, saying whether the call was fresh or a replay, @@ -426,12 +428,17 @@ command on its own authority at all. **A graceful stop has a stated maximum**, because an operator configuring a service manager needs one, and it is the **sum of seven bounded phases** rather than one clock that has to cover everything: five seconds for the admission -cut, sixty for admitting every session's abort, the drain budget **core +cut — which is two phases, because closing admissions is instant and waiting +for what was already admitted is not: five seconds for the close and a hundred +and eighty for the settle, after which the stop proceeds. Then ninety for +admitting every session's abort, the drain budget **core derives and reports** for the cancellation, ninety for the fence, five for terminating the coordinators that did not settle, five for every non-Store action after the drain — the stop records, the closes, the lease owners and -the edges — and thirty for the Store stop that releases the marker. Six of the -seven are fixed, so the maximum is **`budget_ms` plus 195 seconds**. Every one +the edges — and thirty for the Store stop that releases the marker. Seven of +the eight are fixed, so the maximum is **`budget_ms` plus 405 seconds** — a +worst case assembled from the store adapter's ceiling for a wedged +filesystem, not the cost of an ordinary stop, which finishes in milliseconds. Every one of the six is a count of the adapter's own thirty-second call timeout, or the coordinator's own shutdown value, rather than a figure this plan invented: a phase that makes two Store calls in sequence is bounded at sixty and one that From 9de5c58778d354e31d792acec75ca718f6b1bc26 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:11:37 -0700 Subject: [PATCH 138/585] plan(M5): narrow the ticket claim to Control and the journal P0-2. The relay's ten tickets were said to cover "every core call that mutates core state, and nothing else", and three calls falsify it. Generation 2 inherits ADR 0023's artifact-transfer methods -- `artifact.open_transfer`, `artifact.read_chunk`, `artifact.close_transfer` (`0023-technical:175-177`), which M5 reuses unchanged -- and they reach core through `Runtime.open_artifact_transfer/2`, `read_artifact_chunk/3` and `close_artifact_transfer/2` (`runtime.ex:279-288`, `:295-306`, `:312-321`) and write dispatcher state at `event_dispatcher.ex:323`, `:351`, `:386`. The claim is narrowed to what the cut actually has to protect: every core call that mutates `Control` or the journal, plus `session.attach` because the daemon counts attachments. A transfer touches neither, only per-attachment state that dies with the attachment, so it cannot disturb quiesce's enumeration. Ticketing all thirteen is recorded as rejected: it would put a read of an artifact chunk in the way of a stop for no property the stop needs. Two consequences are stated rather than left to inference. After the cut, **every** request on an open connection is refused `daemon_stopping` whatever its method -- transfers and reads included -- because the refusal is about the daemon's state, not about the request's effect. And a transfer in flight when the cut answers either completes or ends in phase 6 with its connection: the connection process ends, core change 1's monitor drops its attachment, and the transfer state goes with the attachment it hung from. --- ...tachment-residency-and-replay-technical.md | 6 ++- ...controller-lease-and-takeover-technical.md | 8 +++- docs/plans/M5-technical.md | 39 ++++++++++++++++--- 3 files changed, 45 insertions(+), 8 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 6d76f7dca..e784e4a53 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -605,7 +605,11 @@ ticket it holds has **settled** — not merely been recorded, a recorded ticket being a call still running — and nothing enters core through the daemon after that answer. A connection that is still open — and every connection is, because the cut precedes the closes — may still send a frame. -It is answered with a **correlated** `daemon_stopping` carrying that request's +**Every** method is refused after it, whatever it would have done — the eight +lease-authorized mutations, `session.create`, `session.attach`, the queries, +and ADR 0023's three artifact-transfer methods alike — because the refusal is +about the daemon's state rather than about the request's effect. It is +answered with a **correlated** `daemon_stopping` carrying that request's `request_id` and nothing else: no `event_cursor`, no session state, and it closes nothing on its own. The connection is closed a moment later by step 3 of the stop sequence, which is where a client is told the reason it is going diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 9d958dc46..bea5a83d1 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -85,9 +85,13 @@ it, and so are two calls that carry no epoch: `session.create`, whose ticket the connection process takes because no lease owner exists for a session that does not exist yet, and `session.attach`, whose second leg mutates the runtime's dispatcher. Ten in all. Nothing else is: reads are not ticketed, -since a read changes no core state, grants nothing, orders nothing, and a +since a read grants nothing, orders nothing, and a blocking read would otherwise hold a takeover -for as long as an observer sat on it. Neither the create ticket nor the attach +for as long as an observer sat on it — and neither are ADR 0023's three +artifact-transfer methods, which do write per-attachment dispatcher state but +touch neither `Control` nor the journal, so they cannot disturb what a drain +enumerates. The plan's companion states that boundary and what becomes of a +transfer in flight at the cut. Neither the create ticket nor the attach ticket blocks a grant — the first names no session yet, the second grants nothing a successor could overtake — and both exist so that the daemon's orderly stop can close admissions with an acknowledgement covering diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 719405759..f4e51c261 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -1516,8 +1516,35 @@ So one fixed, daemon-owned process holds what the lease owners cannot — and three details of it are the difference between closing the window and looking as though it does: -- **Tickets cover every core call the daemon makes that mutates core state, - and nothing else — ten of them.** Eight are the lease-authorized +- **Tickets cover every core call that mutates `Control` or the journal, plus + `session.attach` because the daemon counts attachments — ten of them.** The + claim is that narrow on purpose, and an earlier revision's wider one — + "every core call that mutates core state, and nothing else" — was false. + Generation 2 inherits ADR 0023's three **artifact transfer** methods + (`artifact.open_transfer`, `artifact.read_chunk`, `artifact.close_transfer`, + `0023-…-technical.md:175-177`), which M5 reuses unchanged; they reach core + through `Runtime.open_artifact_transfer/2`, `read_artifact_chunk/3` and + `close_artifact_transfer/2` (`runtime.ex:279-288`, `:295-306`, `:312-321`) + and they **do write** dispatcher state — the transfer map on the attachment, + at `event_dispatcher.ex:323`, `:351` and `:386`. They carry no ticket, and + that is correct rather than an omission: what the cut protects is quiesce's + enumeration of `Control` and the journal it drains, and a transfer touches + **neither** — only per-attachment state that belongs to the attachment and + dies with it. Ticketing all thirteen was the alternative and is rejected: it + would put a read of an artifact chunk in the way of a stop for no property + the stop needs. + + What holds for them is the rule stated once and for every kind: **after the + cut, every request on an open connection is refused `daemon_stopping` + whatever its method** — transfers included, and reads included, the refusal + being about the daemon's state and not about what the request would have + done. A transfer already in flight when the cut answers either completes on + its own or ends in phase 6 with its connection: the connection process ends, + core change 1's monitor drops its attachment, and the transfer state goes + with the attachment it was hanging from. Nothing about it is durable and + nothing about it can disturb the drain. + + Of the ten, eight are the lease-authorized existing-session mutations ADR 0033 lists: `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, @@ -1637,8 +1664,10 @@ as though it does: ticketed call is bounded by core's own work rather than by a client, and a ticket that cannot settle is the `relay_lost` case this section already defines. That answer is what makes "after this instant nothing enters core - through the daemon" a fact rather than a policy, and it is why every call - that changes core state goes through this one process. + through the daemon **that could change what quiesce is about to read**" a + fact rather than a policy, and it is why every call that mutates `Control` + or the journal goes through this one process. The narrower claim is the true + one; the transfer methods above are the reason it has to be narrow. That is the ordering claim ADR 0033's owner-loss section now rests on: a successor's first call cannot be issued while an older call for the same @@ -3859,7 +3888,7 @@ links rather than one of them, and an earlier revision headed eleven rows | **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | | **Connections**, one per accepted client | The listener | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | | **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time, except phase 6's lease-owner sweep, which spawns one per lease owner at once and so is bounded by the 512 above | Nothing: monitored, never linked | -| **Relay tasks**, one per ticketed call — the eight lease-authorized mutations, `session.create` and `session.attach` | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | +| **Relay tasks**, one per ticketed call — the eight lease-authorized mutations, `session.create` and `session.attach`; **not** the three artifact-transfer methods, which mutate neither `Control` nor the journal | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | **Core's processes, as groups with their owner.** The runtime root supervises seven children under `:rest_for_one` (`runtime/supervisor.ex:64-90`, strategy From eabf48c6e540e3ef41456487d6b006cbd249c1ac Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:13:05 -0700 Subject: [PATCH 139/585] plan(M5): six smaller repairs from the rotated pass P1-4. Phase 5's five seconds had no qualifier. It is per phase and concurrent across the unsettled coordinators, and it is a ceiling nothing approaches: a coordinator does not trap exits -- `init/1` sets no flag (`session_coordinator.ex:260-292`) and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns -- so it runs no `terminate/2` and dies at once. P1-5. The reservation table had a prepared-capability row, which described a call the daemon must not make: `Runtime.prepare_resume_session/3` (`runtime.ex:186-192`) would be an activation begun outside the relay's account and therefore outside the admission cut -- a hole no reservation row could have covered. The row is deleted and the exclusion stated. P1-6. A refused `0.1.0` client was told to "send `loopex.experimental/1` instead", on a connection ADR 0023 gives no second negotiation attempt (`0023-technical:357-358`). It must reconnect first, and the sentence says so. P2-7. Phase 6 swept the lease owners and left the 512 connections implicitly sequential. They get the same treatment and the same reason, plus the one that is specific to them: the processes must actually end, because core change 1's monitor releases each attachment on that process's `DOWN`, not on its socket being closed. P2-8. `control.ex:908` is `:909-918`. P2-9. `lease_term_ms` carried two contracts -- the lease and the new handshake deadline -- so a later change to one would silently move the other. Generation 2 gains a separate advertised key, `initialize_deadline_ms`, with the same value derived from the lease term rather than chosen, in the limits table and the digest statement. --- ...tachment-residency-and-replay-technical.md | 22 +++++++--- docs/plans/M5-technical.md | 41 +++++++++++++++---- 2 files changed, 50 insertions(+), 13 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index e784e4a53..00118bfc6 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -345,6 +345,7 @@ added keys are enumerated so the digest covers them: | Limit key | Value | | --- | --- | | `connections_per_daemon` | 512 | +| `initialize_deadline_ms` | 30,000 | | `attachments_per_session` | 64 | | `attachments_per_daemon` | 512 | | `session_list_page_max` | 256 | @@ -387,11 +388,20 @@ Nothing else releases such a connection — there is no attachment to evict, no lease to expire, and ADR 0023's connection-state rules govern what a connection may *do* before `initialize`, not how long it may take. So an accepted connection that has not completed `initialize` within the **lease -term, 30 seconds**, is closed. That number is reused rather than chosen: it is -already this milestone's one connection-lifetime bound, fixed by ADR 0033 and -listed in this pair's limits as `lease_term_ms`, and a `initialize` handshake -is one frame each way on a local socket, so thirty seconds is a ceiling no -honest client approaches. The close carries no record — the connection has +term, 30 seconds**, is closed, under its **own** advertised limit key, +`initialize_deadline_ms`. It is a separate key carrying the same value as +`lease_term_ms`, and the separation is the point: one key meaning two +contracts would let a later change to the lease term silently move the +handshake deadline, or the reverse, and a client reading `lease_term_ms` to +decide when to renew would be reading a number that also governs something it +has nothing to do with. **The value is derived rather than chosen**: thirty +seconds because that is the one connection-lifetime bound this milestone +already fixes, so the daemon introduces no number — and if the two ever need +to differ, they can, which is what having two keys buys. An `initialize` +handshake is one frame each way on a local socket, so thirty seconds is a +ceiling no honest client approaches. Adding the key changes generation 2's +limits input and therefore its digest, which is stated here so the pinned +literal is computed over it. The close carries no record — the connection has negotiated nothing, so there is no generation whose error shape it could be sent in — exactly as the peer-credential refusal closes before initialize. @@ -443,7 +453,7 @@ limits — five inputs, and generation 2 changes **all five**: | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` and `daemon.notice` | | **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 reuses for the connection ceiling | -| **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `connections_per_daemon`, `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | +| **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `connections_per_daemon`, `initialize_deadline_ms`, `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 makes a lease owner's failure session-scoped: the daemon closes that session's diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index f4e51c261..720d46e97 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -543,8 +543,12 @@ retired root is reached only by reopening that root. sends `loopex.session.v1-experimental` in its `initialize` generations list. Against a `0.2.0` server that list has no common generation, so the server refuses with `unsupported_generation` — the refusal ADR 0023 already defines -for exactly this — and the client's remedy is to send `loopex.experimental/1` -instead. Nothing else about that client changes: same framing, same methods, +for exactly this — and the client's remedy is to **reconnect** and send +`loopex.experimental/1` on the new connection. Reconnecting is part of the +remedy rather than a detail: ADR 0023 gives a refused connection no second +negotiation attempt and leaves it uninitialized +(`0023-…-technical.md:357-358`), so a client that retried `initialize` on the +same socket would be refused again for a different reason. Nothing else about that client changes: same framing, same methods, same limits, same records. **The repository's own Node client is updated in the same change**, so the independent-client evidence is written against the new string rather than against a shim. @@ -997,7 +1001,7 @@ detailed functions behaves exactly as it does now. neat one.** The brief for this change asked whether a fresh create can be refused *before* core starts the coordinator. It cannot, from the daemon: the coordinator is started inside the same call that would tell the daemon the -create was fresh (`start_owner` in the `true` branch at `:908`), so by the +create was fresh (`start_owner` in the `true` branch at `:909-918`), so by the time the daemon could act, the coordinator exists and the daemon has no API to stop it. So the rule at the ceiling is the blunt one: **at the activation ceiling the daemon refuses every `session.create`, replayed or fresh**, with @@ -1122,12 +1126,21 @@ leaked until the daemon restarts: | Create, `:historical` with `control_entry: :dormant` | Released — a replay starts nothing. `:dormant` here covers both a `Control` entry that is `:unavailable` and no entry at all: neither is a live coordinator, and neither was charged | | Resume, `disposition: :fresh` | **Converted** — a coordinator started | | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | -| Resume answering a **prepared** capability, where the activation is begun but not finished | **Held**: the reservation stays until that activation resolves, then converts on success and releases on abandonment. It is the one branch that is neither yet | | Any of the three refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, an attach whose first leg answers `{:error, :runtime_unavailable}` on its 5 s default, any other `{:error, _}` | Released. An attach refused at its first leg is the same case as any other refusal, because that leg mutates nothing (`control.ex:1235-1251`) | | A **resume** whose connection is lost while the call is in flight | **Held, then resolved by the relay**, which holds the call's real answer whether or not the process that asked is still there; where the daemon must re-establish it later, the client's replay under its original `command_id` carries the same `disposition`/`control_entry`. The existence query cannot answer this — it says `present` either way | | A **create** whose connection is lost while the call is in flight | **Held, then resolved by the relay** the same way; a later replay under the same `command_id` returns the historical result and starts no coordinator (`control.ex:901-907`), carrying the same two fields. Same reservation key, so no second slot | | An **attach whose connection process ends before it answers** | **Released with the connection**: the reservation is keyed by the connection, ADR 0032 binding a connection to at most one attachment, and core change 1 monitoring the attaching process. The daemon closes that connection, its process ends, and the dispatcher's `DOWN` handler drops the attachment. Nothing is observed, because nothing needs to be | +**The daemon never calls `Runtime.prepare_resume_session/3`**, which is why +the prepared-capability row an earlier revision carried is gone. That function +exists (`runtime.ex:186-192`) and answers `{:ok, {:prepared, …}}` for a caller +that wants to hold an activation open — and a daemon that used it would have +an **unticketed** entry into core, an activation begun outside the relay's +account and therefore outside the admission cut, which is a hole no +reservation row could have covered. The daemon uses +`resume_session_detailed/3` and nothing else, so there is no "held until the +activation resolves" branch to describe. + **Those rows used to say "crashing or timing out", and the timing-out half was false.** An earlier revision rested it on a default: `Loopex.Runtime`'s `control_call/3` and `dispatcher_call/3` do default to a **five-second** reply @@ -2155,7 +2168,7 @@ that already exists somewhere, and the operator maximum is the sum: | 2 | **Abort admission** | **90 s** — **three** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission may wait behind the transaction the coordinator already has in flight, which is itself two calls because core's ordinary path retries a `commit_unknown` once; then the drain's own admission, which is one call because it does **not** retry | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | -| 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`) | The value core already gives a coordinator to stop in | +| 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across the unsettled coordinators | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | | 6 | **Daemon teardown** | **5 s** | This plan's one chosen number, covering the notice, the closes, the lease owners, the relay and the edges | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | @@ -2456,7 +2469,21 @@ the owner fixes. where it is.** Each open connection gets one `daemon.stopping` naming `operator_stop`, bounded best-effort as ADR 0032 fixes — one write attempt into the existing 4 MiB output buffer — and is closed, and the listening - socket is closed with them. **Nothing unlinks the pathname**, on this path + socket is closed with them. + + **This is a collective sweep too, for the same arithmetic as the lease + owners.** Up to 512 connections exist, and the write and the close are each + microseconds — one non-blocking `send` into a buffer the daemon already + holds, and one `close` — so the work is trivial; what is not trivial is + doing 512 of them in sequence and then waiting for 512 process exits one + after another inside phase 6. So the owner writes and closes **all of + them at once**, then waits **once** for every connection process to exit, + killing whatever is left at the phase's end. The processes must actually + end, not merely stop being written to: core change 1's monitor is what + releases each connection's attachment, and it fires on that process's + `DOWN`. A connection killed here loses a buffered record it had not + finished writing, which is the case ADR 0032 already admits when it says a + client may learn of a shutdown only by its socket closing. **Nothing unlinks the pathname**, on this path or any other: the next daemon to prove it holds the marker removes it before binding, which is the only safe moment there is. 4. **Every lease owner stops as one sweep, then the admission relay**, inside @@ -4050,7 +4077,7 @@ line; M5 introduces none of its own. | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | | Concurrent connections per daemon | 512, the attachment number reused; the 513th is refused `capacity_exceeded` at `initialize` and closed | ADR 0032 | -| Time an accepted connection may take to complete `initialize` | 30 s, the lease term reused, after which it is closed with no record; without it the connection ceiling would bound nothing | ADR 0032, against ADR 0033's `lease_term_ms` | +| Time an accepted connection may take to complete `initialize` | 30 s, advertised under its own limits key `initialize_deadline_ms`, after which the connection is closed with no record; without it the connection ceiling would bound nothing | ADR 0032, its value derived from ADR 0033's lease term rather than chosen, and carried as a separate key so neither contract moves the other | | Attachments per session | 64 | ADR 0032 | | Attachments per daemon | 512 | ADR 0032, its attachment-lifecycle list, with the limit key in its limits table | | Core event-count queue per attachment | 1,024 events | ADR 0032 | From 472bfd99645938e1aee443b2dbb05cd0131aefce Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:14:53 -0700 Subject: [PATCH 140/585] plan(M5): adversarial pass over the rotated round MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Class 7, stale counts: four places still said seven phases after the cut split into 1a and 1b, and the limits table's total said "the seven fixed phases" without saying how many phases there now are. Eight phases, seven of them fixed. Class 5, Concept versus Technical: ADR 0032's Concept listed the exact limits and carried neither the handshake deadline nor the idle exemption the companion now states. Both are in the list. Class 25, unobservable resolution: Outcome 1 still described the cut as one call that waits for settlement, so its witnesses could not distinguish the design that was just replaced. They now assert what the split exists for -- a 1a acknowledgement that returns while a prompt commit is still in flight, which the old five-second cut would have failed into `relay_lost`, and a resume held past 1b's bound with the stop proceeding and its session reported `unsettled` from an `:acquiring` entry. An `artifact.read_chunk` after the cut is asserted refused beside the ticketed methods, which is what proves the refusal covers an unticketed one. Class 30, result totality: the quiesce witness list had a case for an `:unavailable` entry and none for `:acquiring`, which this round made reachable. It has one. Class 1, cross-ADR citations: the last `0033-…-technical.md:188-191` is a section reference, on the rule this round already applied to ADR 0032 -- those line numbers had drifted again with this round's own edits. --- .../0032-daemon-attachment-residency-and-replay.md | 7 +++++-- docs/plans/M5-technical.md | 14 +++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index ee9450860..805ed1e12 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -156,12 +156,15 @@ directory can claim that. Lineage, lifecycle state and committed sequence are not list fields: a client that needs them attaches and reads the snapshot. The proposed limits are exact and are bound at acceptance: 512 concurrent connections per -daemon, 64 attachments per session, +daemon, thirty seconds for an accepted connection to complete `initialize` +before it is closed — a value derived from the lease term but carried as a key +of its own, so neither contract moves the other — 64 attachments per session, 512 attachments per daemon, a 1,024-event core queue per attachment, a 4,096-event resident window per session, 4 MiB of encoded output buffered per connection, 16 MiB of encoded resident-window events per session, 512 MiB of aggregate retained encoded events per daemon, ten minutes of idle time -before eviction, 64 sessions activated per daemon lifetime, 4,096 recorded +before an **observer** connection is evicted — a lease holder being exempt +while it holds its lease — 64 sessions activated per daemon lifetime, 4,096 recorded index entries per root, 256 sessions per list page, and the ADR 0023 frame ceiling unchanged. Count and byte ceilings apply together; an event that would diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 720d46e97..191a7a04f 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call to the relay that answers only when admissions are closed and **every ticket it holds has settled** — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation whose ticket was recorded in the instant *before* the acknowledgement is asserted to have settled by the time the acknowledgement returns, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create` and `session.attach` sent after the cut refused the same way, the two cases that would fail if either bypassed the relay, and a third asserting no `Control` entry changes between the acknowledgement and quiesce's enumeration; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -345,7 +345,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -1564,7 +1564,7 @@ as though it does: `session.respond_interaction`, `session.admit_resources` and `session.activate_skill` — the calls that carry `writer_epoch` and are admitted only from the recorded holder - (`0033-…-technical.md:188-191`). The ninth is **`session.create`**, which + (ADR 0033's methods-and-fields section). The ninth is **`session.create`**, which carries no epoch and has no lease owner, because the session it makes does not exist yet; its ticket is taken by the **connection process** rather than by a lease owner, and it takes no part in the per-session grant-blocking @@ -2150,7 +2150,7 @@ between the owner's death and the monitor's `DOWN` being handled. In both routes the class is `owner_lost` on `stderr`, and it is the one class no linked component produces. -**Seven phases, each with a named bound, and the stop is their sum.** Earlier +**Eight phases, each with a named bound, and the stop is their sum.** Earlier revisions called this "three clocks" and then let two of them overlap: the drain budget was the largest cancellation backstop — at the smallest admitted grace that is already **22,001 ms** (`cancellation_bounds/1`, @@ -2237,7 +2237,7 @@ are these: query, not re-proposed. A **stale** fence is not reattempted at all, for the reason the fence table gives. -**The seven phases and the six steps are two cuts through the same stop, and +**The eight phases and the six steps are two cuts through the same stop, and the mapping is stated rather than left to be inferred.** The numbered sequence below is what the daemon's owner *does*; the phases are what each part of it is *bounded by*. Phases 1a and 1b are step 1: 1a is the owner's call to the @@ -2302,7 +2302,7 @@ stopped after them. Its session's controller connection is already gone, step `control_owner_lost` and there is nothing left to send one to. **`budget_ms` is still core's to derive and report**, for the reason below; -what changed is that it is one phase among seven rather than the whole drain. +what changed is that it is one phase among eight rather than the whole drain. The budget is derived rather than chosen because the cancellation it waits on is already bounded by core: `cli_backstop_ms` is the number core itself says a @@ -4100,7 +4100,7 @@ line; M5 introduces none of its own. | Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | -| Maximum graceful stop | `budget_ms` + **405 s**, the sum of the seven fixed phases above; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **405 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | From acc699adde513faeeac52cb6f4bcf9c9e64c07bd Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:34:33 -0700 Subject: [PATCH 141/585] plan(M5): recount phase 1b from a traced run and require executed counts H1. A fresh `session.create` executes **nine** adapter calls, ten with the one retry -- not the six an earlier revision read off the source. Two errors, both of the kind only a run finds. `load_pages/4` always makes a terminating empty-page call (`session_coordinator.ex:7090-7114`), so `load_all_records` over a session that already holds its genesis record is two calls, not one; that revision had assumed a fresh session reads empty, and it does not. And the genesis commit was never counted: `create_session/2` calls `create_command_absent?/2` for one `Store.runtime_command` (`control.ex:959- 965`) and *then* `Store.create_session/3` through `resolve_transaction/2` (`:896-897`, `:1679-1684`), which is a second adapter call and retries once at `:1681`. The traced order is `runtime_command`, `transact`, `load_records` x2, `ownership_head`, `transact`, `load_records` x2, `load_events`. Phase 1b is therefore ten calls, **300 s**, and the operator maximum is **`budget_ms` + 525 s**. The "no Store operation begins without its own timeout remaining" invariant said the rule "never fires on the intended sequence". That was true of a count that had missed four calls and false in practice, so it is restated as the proviso it is: the rule holds provided the count is right, and its service is to catch a miscount by stopping at the bound rather than running past it. And a rule is added to the verification section rather than a note to this one case: **every bound this plan derives from a sequential call count carries a witness that executes the path and asserts the exact count**, by tracing the adapter with `:erlang.trace_pattern({Loopex.Store.Local, :_, :_}, true, [:global])` where it is reachable and the suite's controllable store's call log where it is not. Three cases, named to file, case and lane, all core witnesses because all three paths are core's: nine for a fresh create, three for a drained abort admission, three for a fence. Asserting an exact number rather than "at most N" is what makes a later change to the path fail there instead of at an operator's `TimeoutStopSec`. H5. Seven phase bounds became eight, six constants seven, and "six of the seven" "seven of the eight" -- in the operator obligation and in M5.md. The claim that every fixed term is an adapter count or the coordinator's shutdown value is false for two of them: phase 1a's five seconds and phase 6's are this plan's own chosen numbers, and both files now say so. L4. M5.md's worked example still read a phase off at sixty seconds, which no phase is any more. --- docs/plans/M5-technical.md | 114 ++++++++++++++++++++++++++++--------- docs/plans/M5.md | 22 ++++--- 2 files changed, 101 insertions(+), 35 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 191a7a04f..311e6eb92 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -293,17 +293,20 @@ because both are facts an operator cannot derive from the software and a reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop as the sum - of the seven phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 405 s**, being 5 s for closing admissions, 180 s for + of the eight phase bounds**, in the form the lifecycle section fixes: + **`budget_ms` + 525 s**, being 5 s for closing admissions, 300 s for settling what was already admitted, 90 s for abort admission, `budget_ms` for cancellation, 90 s for the fence, 5 s for coordinator termination, 5 s for daemon teardown and 30 s for the Store — together with the sentence that keeps the number from being read as a - duration: every fixed term counts the Store's thirty-second ceiling for a - wedged filesystem, and an ordinary stop finishes in milliseconds — - with the six constants written out beside the one derived term, so an + duration: **five** of the seven fixed terms count the Store's + thirty-second ceiling for a wedged filesystem — and the other two, the five + seconds for closing admissions and the five for the teardown, are this + plan's own chosen numbers, which the page says rather than implying every + term is derived — and an ordinary stop finishes in milliseconds — + with the seven constants written out beside the one derived term, so an operator setting a `TimeoutStopSec` adds up numbers rather than trusting a - total. It must say that six of the seven are fixed and + total. It must say that seven of the eight are fixed and that the drain term alone is **not** read off the daemon's own `--cleanup-grace-ms`, because each session drains under the grace it committed and a root may carry sessions composed earlier, so the page must @@ -345,7 +348,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `a drained abort admission executes three store calls`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -367,6 +370,34 @@ lifetime suite proves the drain happens in the stop sequence a real operator triggers, and the adapter's credential suite proves a real invocation is not traceable. Neither can reach the branches above, and neither is asked to. +**Every bound derived from a call count carries a witness that executes the +path and asserts the count.** This is a rule of this plan rather than a remark +about one case, and it exists because two independent readings of the create +path produced two wrong numbers before a traced run produced the right one: +six by reading, then nine — ten with the retry — by executing. A count read +off the source is a hypothesis; only a run is evidence, and a bound built on a +miscount is a bound the stop silently exceeds. + +So each of the three derived phase bounds has a case that **counts adapter +calls while the path runs**, by tracing the adapter module — +`:erlang.trace_pattern({Loopex.Store.Local, :_, :_}, true, [:global])` where +the adapter is reachable, and the suite's controllable store's own call log +where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and +`Loopex.Store.Local` is not) — and asserts an exact number, not a bound: + +| Bound | What the case executes and counts | File | Case | Lane | +| --- | --- | --- | --- | --- | +| Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | +| Phase 2, three calls | A drained abort admitted behind one in-flight transaction, asserting **three** — two for the transaction already in the lane, one for the drained abort, which does not retry | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admission executes three store calls` | fast | +| Phase 4, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | + +All three are **core** witnesses, because all three paths are core's: the +daemon contributes no Store call of its own to any of them. A case that +asserted "at most N" would pass on a path that had grown shorter *or* been +restructured into something the phase no longer bounds; asserting the exact +number is what makes a later change to the path fail here rather than at an +operator's `TimeoutStopSec`. + **Test honesty.** Future test bodies are written with their implementation; a missing witness is never a pass. **Every witness named in this plan pair names three things: the exact file, the case @@ -2164,7 +2195,7 @@ that already exists somewhere, and the operator maximum is the sum: | # | Phase | Bound | Where the number comes from | | --- | --- | --- | --- | | 1a | **Close admissions** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement of a **state change**, not of any work: the relay sets a flag, refuses everything after it, and answers. It has nothing to finish, so this bound measures the relay's own responsiveness and nothing else; a relay that does not answer inside it is a relay the daemon has lost, and the stop becomes the `relay_lost` fail-stop | -| 1b | **Settle the admitted** | **180 s** — **six** Store calls deep, the deepest ticket kind; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | +| 1b | **Settle the admitted** | **300 s** — **ten** Store calls deep, the deepest ticket kind, counted from a traced run rather than from the code; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | | 2 | **Abort admission** | **90 s** — **three** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission may wait behind the transaction the coordinator already has in flight, which is itself two calls because core's ordinary path retries a `commit_unknown` once; then the drain's own admission, which is one call because it does **not** retry | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | @@ -2172,8 +2203,8 @@ that already exists somewhere, and the operator maximum is the sum: | 6 | **Daemon teardown** | **5 s** | This plan's one chosen number, covering the notice, the closes, the lease owners, the relay and the edges | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 5 s + 180 s + 90 s + `budget_ms` + 90 s + 5 s + -> 5 s + 30 s = `budget_ms` + 405 s**, and `budget_ms` is the one term an +> **Maximum graceful stop = 5 s + 300 s + 90 s + `budget_ms` + 90 s + 5 s + +> 5 s + 30 s = `budget_ms` + 525 s**, and `budget_ms` is the one term an > operator cannot compute in advance. **That is a worst case nobody approaches, and saying so is part of stating @@ -2198,17 +2229,42 @@ are these: | Ticket kind | Sequential Store calls before the ticket settles | Where | | --- | --- | --- | - | The seven non-resume lease-authorized mutations — `prompt`, `steer`, `follow_up`, `abort`, `respond_interaction`, `admit_resources`, `activate_skill` | **2** | One `OwnerLane.transact/2`, retried once on `commit_unknown` (`session_coordinator.ex:1761-1764`). The wait-behind does **not** apply: this call *is* the session's one in-flight transaction, and the coordinator's `command/3` waits `:infinity` for it (`:146-149`) | - | `session.create`, fresh | **6** | `Store.runtime_command/2` for the genesis command (`control.ex:960`); then the coordinator it starts must reach `:ready` before the reply, which is `load_all_records` (one empty page, `:1302-1309`, `:7076-7081`, `@page_size 1_024` at `:49`), `ownership_head` (`:1338`), the owner `OwnerLane.transact` (`:1363`), then `recover_committed_owner`'s `load_all_records` and `load_all_events` (`:1397-1400`) before `phase: :ready` at `:1407` | - | `session.attach` | **1 + ⌈events ÷ 1,024⌉** | The dispatcher's snapshot scan pages the session's events (`event_dispatcher.ex:169-199`, `:926`) | - | `session.resume`, fresh | **6 + the pages its history needs** | The same six as a create minus the genesis command, plus `prior_transaction_resolved`'s `transaction_status` (`:1324-1335`), and with every one of the three `load_*` calls paged over real history rather than over an empty session | - - **The maximum over the kinds whose depth is a constant is six**, which is a - fresh create, so 1b is bounded at six calls. **Two kinds have no constant - depth** — attach and resume both page over the root's history at 1,024 rows - a call — and that is stated rather than papered over with an average, - because it is the reason 1b is a **bounded wait that then proceeds** rather - than a guarantee that everything has settled. + | The seven non-resume lease-authorized mutations — `prompt`, `steer`, `follow_up`, `abort`, `respond_interaction`, `admit_resources`, `activate_skill` | **2** | One `OwnerLane.transact/2`, retried once on `commit_unknown` (`session_coordinator.ex:1752-1768`). The wait-behind does **not** apply: this call *is* the session's one in-flight transaction, and the coordinator's `command/3` waits `:infinity` for it (`:146-149`) | + | `session.create`, fresh | **9**, or **10** with the one retry | Traced, not counted by eye — see below | + | `session.attach` | **2 + ⌈events ÷ 1,024⌉** | The dispatcher's snapshot scan pages the session's events (`event_dispatcher.ex:169-199`, `:926`) | + | `session.resume` | **no constant** | The create sequence without the genesis pair, plus `prior_transaction_resolved`'s `transaction_status` (`:1324-1335`), with all three `load_all_*` calls paged over real history | + + **A fresh create executes nine adapter calls, and the earlier figure of six + was a reading of the code rather than a run of it.** Two errors, both of + them the kind only execution finds: + + 1. **`load_pages/4` always makes a terminating empty-page call.** It recurses + while a page comes back non-empty and returns on `{:ok, []}` + (`session_coordinator.ex:7090-7114`), so `load_all_records` over a session + that holds its genesis record is **two** calls, not one — a page with the + row, then a page without. An earlier revision counted one, having assumed + a fresh session reads empty; it does not, because the genesis record is + already there. + 2. **The genesis commit was never counted at all.** + `create_session/2` calls `create_command_absent?/2` — one + `Store.runtime_command` (`control.ex:959-965`) — and *then* + `Store.create_session/3` with `resolve_transaction/2` + (`:896-897`, `:1679-1684`), which is a second adapter call and which + retries once on `commit_unknown` at `:1681`. Two calls inside `Control` + before the coordinator is started at all. + + The executed sequence, in order: `runtime_command`, `transact` (both + `Control`); then `load_records` ×2, `ownership_head`, `transact`, + `load_records` ×2, `load_events` (the coordinator reaching `:ready` — + `:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`; `load_events` is one + because a fresh session has no events yet). **Nine, or ten with the retry.** + + **The maximum over the kinds whose depth is a constant is ten**, which is a + fresh create, so 1b is bounded at ten calls — **300 s**. **Two kinds have no + constant depth** — attach and resume both page over the root's history at + 1,024 rows a call — and that is stated rather than papered over with an + average, because it is the reason 1b is a **bounded wait that then proceeds** + rather than a guarantee that everything has settled. - **Phase 2 is three.** The abort admission goes to a **live coordinator**, whose lane is serial — `OwnerLane.transact/2` is a plain synchronous call the coordinator makes from its own process (`store/owner_lane.ex:83-99`, called @@ -2255,9 +2311,15 @@ bounded by nobody. counts above it can always be honoured.** *No Store operation begins without at least its own 30 s remaining in its phase.* Because each phase's bound **is** its worst sequential call count times 30 s, a phase -that has reached its *k*th call still has at least 30 s left, so the rule never -fires on the intended sequence; it is a guard against a sequence longer than -the one counted, not a routine exit. +that has reached its *k*th call still has at least 30 s left **provided the +count is right**. That proviso is the whole of the invariant now, and it is +stated as a proviso rather than as a guarantee: an earlier revision said the +rule "never fires", which was true of a count that had missed four calls and +would have been false in practice. The rule is what catches a miscount — a +sequence deeper than the one this plan counted reaches its bound and stops +there rather than running past it — which is exactly the service it has to +perform, and the executed-count witnesses below are what keep it from being +needed. **The escape an earlier revision gave it is deleted, because it was circular.** That revision said a fence with four seconds left is not attempted @@ -4093,14 +4155,14 @@ line; M5 introduces none of its own. | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | -| Phase 1b, settling the admitted | **180 s** — six sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from `control.ex:960` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407` | +| Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | | Phase 2, abort admission | a fixed **90 s** — three sequential Store calls at the adapter's own 30 s `@call_timeout`: the two of a transaction already in the coordinator's serial lane, which retries a `commit_unknown` once, then the drain's own admission, which does not; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:1752-1768` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | | Phase 4, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | -| Maximum graceful stop | `budget_ms` + **405 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **525 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 348e0bc62..d5f352c29 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -429,21 +429,25 @@ command on its own authority at all. service manager needs one, and it is the **sum of seven bounded phases** rather than one clock that has to cover everything: five seconds for the admission cut — which is two phases, because closing admissions is instant and waiting -for what was already admitted is not: five seconds for the close and a hundred -and eighty for the settle, after which the stop proceeds. Then ninety for +for what was already admitted is not: five seconds for the close and three +hundred for the settle, after which the stop proceeds. Then ninety for admitting every session's abort, the drain budget **core derives and reports** for the cancellation, ninety for the fence, five for terminating the coordinators that did not settle, five for every non-Store action after the drain — the stop records, the closes, the lease owners and the edges — and thirty for the Store stop that releases the marker. Seven of -the eight are fixed, so the maximum is **`budget_ms` plus 405 seconds** — a +the eight are fixed, so the maximum is **`budget_ms` plus 525 seconds** — a worst case assembled from the store adapter's ceiling for a wedged -filesystem, not the cost of an ordinary stop, which finishes in milliseconds. Every one -of the six is a count of the adapter's own thirty-second call timeout, or the -coordinator's own shutdown value, rather than a figure this plan invented: a -phase that makes two Store calls in sequence is bounded at sixty and one that -makes three at ninety, and the drain retries nothing, which is what keeps -those counts finite. The drain term is core's because each session drains under the grace it +filesystem, not the cost of an ordinary stop, which finishes in milliseconds. **Five** of the seven are counts of the +adapter's own thirty-second call timeout, or the coordinator's own shutdown +value: a phase that makes three Store calls in sequence is bounded at ninety +and one that makes ten at three hundred, and the drain retries nothing, which +is what keeps those counts finite. The other two — the five seconds for +closing admissions and the five for the teardown — are **this plan's own +numbers**, chosen rather than derived, and the technical companion says so +where it names them. Every count is taken from a traced run of the path +rather than from reading it, because reading it is how an earlier revision +missed four calls. The drain term is core's because each session drains under the grace it committed, which a daemon reading its own flag would not know for a session composed earlier. A service manager that kills the daemon sooner turns the stop into a forced From 97d9e80c4a89e8ec970b03c4d67e8a9471c38f1f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:36:25 -0700 Subject: [PATCH 142/585] plan(M5): supersession becomes conditional, and DOWN releases transfers H3. Core change 1 removes the same-session supersession block, and that block is the **sole** caller of `release_transfers/2` -- the call at `event_dispatcher.ex:817` inside the block at `:812-818`, the function defined at `:1105` with no other call site. Removing it would leave accepted ADR 0028 unsatisfied, its companion requiring that "detaching releases every transfer the attachment opened" (`0028-technical:28-30`). The dispatcher's `DOWN` removal now makes that call, the conditional replacement path makes it for the attachment it supersedes, and a case in `concurrent_attachments_test.exs` asserts an attachment released by its process exiting leaves no transfer behind. H4. ADR 0032 kept explicit-replacement semantics three paragraphs after deleting the only mechanism, and described that mechanism wrongly. Checked rather than assumed: **core never sees `replace`**. ADR 0023 puts the optional boolean on `session.attach` (`0023-technical:165`) and requires a second attach to refuse unless it names replacement (`:359`); the app server parses it (`mapping.ex:162`, `:458`) and uses it only to decide whether one connection may hold a second attachment (`attachable/3`, `:466-470`), then builds core's options without it (`attach_options/1`, `:450-456`) -- `validate_attach_options/1` would refuse it anyway, its defaults naming four other keys (`control.ex:1293-1310`). So the unconditional same-session block **is** the implementation of replace. The change is therefore stated as what it is: supersession becomes conditional on `replace` and narrows to the attaching process's own prior attachment. Generation 1 is behaviour-identical, one connection there holding one attachment. Generation 2 needs both halves: without the condition a second connection detaches the first, and without the narrowed scope one connection's `replace: true` detaches every other connection's attachment to that session. And "invalidates only the named prior incarnation" is corrected, there being no name on the wire -- `replace` is a boolean. H2. The quiesce witness list still named a case that rereads the head and attempts once more, which the no-second-attempt decision reversed two rounds ago, and named `fences[id] == :unknown` where the value carries the head. --- ...tachment-residency-and-replay-technical.md | 71 +++++++++++++++++-- docs/plans/M5-technical.md | 17 +++-- docs/plans/M5.md | 20 +++++- 3 files changed, 96 insertions(+), 12 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 00118bfc6..02f5bfc10 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -162,11 +162,68 @@ concurrent-attachment change removes, because coexisting attachments are the point. So that change has two halves and this pair states both: supersession stops -removing attachments, **and the dispatcher keeps its monitor after install and +removing attachments **unconditionally**, **and the dispatcher keeps its +monitor after install and removes the attachment on that process's `DOWN`**. Without the second half M5 would leave core with no release path at all, and every attachment ever made would live until the runtime stopped. +**The `DOWN` removal must release the attachment's transfers, and saying so is +not optional.** The supersession block is the **sole** caller of +`release_transfers/2` — the call is at `event_dispatcher.ex:817`, inside the +block at `:812-818`, and the function is defined at `:1105` with no other call +site in the module. Removing the block without moving that call would leave +accepted **ADR 0028** unsatisfied, its technical companion requiring that +"detaching releases every transfer the attachment opened" +(`0028-…-technical.md:28-30`). So the dispatcher's `DOWN` handler calls +`release_transfers/2` for the attachment it drops, and the conditional +replacement path below calls it for the attachment it supersedes. ADR 0028 is +thereby satisfied on both of the two paths that end an attachment, where today +it is satisfied on one; its witness is a case in +`apps/loopex/test/concurrent_attachments_test.exs` asserting that an +attachment with an open transfer, released by its process exiting, leaves no +transfer behind. + +**And supersession becomes conditional rather than disappearing, because +today it *is* the implementation of `replace`.** That took checking rather +than assuming, and the answer is not what ADR 0032 said. ADR 0023 puts an +optional `replace` boolean on `session.attach` +(`0023-…-technical.md:165`) and requires that a second attach refuse "unless +it names explicit replacement, which detaches the first at its last completely +emitted cursor" (`:359`). **Core never sees that flag.** The app server reads +it (`mapping.ex:162`, `:458`) and uses it for one thing only — whether a +connection already holding an attachment may open a second +(`attachable/3`, `:466-470`) — and then builds core's options without it +(`attach_options/1`, `:450-456`); `Control.validate_attach_options/1` would +refuse it anyway, its `Keyword.validate/2` defaults naming only +`after_event_sequence`, `request_id`, `client_id` and `attachment_key` +(`control.ex:1293-1310`). What actually replaces the attachment is core's +**unconditional same-session** block, which reads no flag and supersedes +*every* attachment of that session. + +So the change is stated as what it is: **the same-session supersession becomes +conditional on `replace`, and narrows its scope to the attaching process's own +prior attachment** for that session. Core's attach options gain `replace`, the +app server passes the flag it already parses, and the block fires only when it +is set. + +- **Generation 1 is behaviour-identical**, which is what ADR 0023 requires and + what this milestone promises for the foreground server: that host maps one + connection to one attachment, so its supersession only ever fired behind a + `replace: true` the app server had already admitted, and narrowing the scope + to the attaching process changes nothing where there is one attacher. +- **Generation 2 needs both halves of the change.** Without the condition, a + daemon's second connection would detach the first — the thing concurrent + attachment exists to stop. Without the narrowed scope, a `replace: true` + from one connection would detach *every other connection's* attachment to + that session, which is worse. +- **"The named prior incarnation" is corrected.** An earlier revision of this + pair said explicit replacement "invalidates only the named prior + incarnation at its last emitted cursor". There is no name on the wire — + `replace` is a boolean — so what it invalidates is the attaching process's + own prior attachment for that session, at its last completely emitted + cursor, with `release_transfers/2` called for it. + For the daemon this needs no API: it attaches from its **per-connection process**, so a connection that closes — because the client went away, because the daemon is stopping, or because the daemon gave up on a request that never @@ -190,7 +247,9 @@ The core EventDispatcher and Control retain multiple live attachment IDs and incarnations for one session. A new distinct attachment does not implicitly detach another session attachment or cancel its pending read. Repetition of the same attachment request returns its live attachment; explicit replacement -invalidates only the named prior incarnation at its last emitted cursor. +— `replace: true` — invalidates the attaching process's own prior attachment +for that session at its last completely emitted cursor, and releases its +transfers. Snapshot barriers, queued durable delivery, stale-handle checks and detach remain core operations. The daemon neither copies the snapshot into a second fan-out owner nor reads coordinator state to repair an attachment race. @@ -1142,8 +1201,12 @@ sequence and event ID. ### Evidence Tests prove: two core attachments to one session keep independent live handles, -snapshots and cursors with no implicit replacement; an explicit replacement -invalidates only its named incarnation; snapshot-then-contiguous at-least-once +snapshots and cursors with no implicit replacement; an explicit `replace: true` +invalidates only the attaching process's own prior attachment for that session, +releasing its transfers, while every other connection's attachment to it +continues; an attachment released by its process exiting leaves no transfer +behind, which is accepted ADR 0028's requirement on the path that replaces the +only caller `release_transfers/2` has today; snapshot-then-contiguous at-least-once delivery with no gap across the window boundary; the same delivery cases run again with the resident window disabled, byte for byte identical, and with the window dropped mid-stream, proving the cache establishes nothing; deterministic diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 311e6eb92..4cf73256a 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -346,9 +346,9 @@ core-internal states a daemon cannot construct through the socket. | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | +| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `a drained abort admission executes three store calls`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch rereads the head and attempts once more`; `a fence refused stale_journal_version is superseded, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == :unknown`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `a drained abort admission executes three store calls`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -3492,7 +3492,7 @@ nothing proves. Each is named where it is used: | Surface | Created by | Read by | | --- | --- | --- | -| The dispatcher's release on `DOWN` | Core change 1 | The concurrent-attachment cases and the attach connection-loss case | +| The dispatcher's release on `DOWN`, and the transfers it releases with it | Core change 1 | The concurrent-attachment cases, the ADR 0028 transfer case and the attach connection-loss case | | The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | | `Control`'s excluded-pid set, and `Entry`'s redaction of a keyword pair under its own key | Core change 3 | The trace-exclusion cases, and the render pair that must differ | | `quiesce/1`'s three lists, `budget_ms`, `drain_id` and the per-session `fences` map | Core change 4 | The drain cases, the fence cases and the stop line | @@ -4056,9 +4056,14 @@ the two callers that need the edges assembled, `RuntimeOwner` and the daemon's owner, and which direct code cannot replace because the alternative is a second copy of the whole wiring layer. One socket listener, **one narrow core concurrent-attachment change with two halves** — supersession stops removing -an attachment, and the dispatcher monitors the attaching process and removes -on its `DOWN` — because the first half alone would leave core with no release -path at all, supersession being the only one there is today. **One +an attachment *unconditionally*, becoming conditional on ADR 0023's existing +`replace` flag and scoped to the attaching process's own prior attachment, and +the dispatcher monitors the attaching process and removes +on its `DOWN`, releasing that attachment's transfers — because the first half +alone would leave core with no release +path at all, supersession being the only one there is today, and would leave +the only caller of `release_transfers/2` with no replacement, which accepted +ADR 0028 forbids. **One trace-exclusion call, `Loopex.Trace.exclude_self(capability, functions: [mfa])`** — which unifies nothing and is not asked for by this milestone's features at all: it exists diff --git a/docs/plans/M5.md b/docs/plans/M5.md index d5f352c29..06a32d184 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -1004,8 +1004,24 @@ finishes, and `disconnect/2` marks an attachment disconnected without removing it. Made as written, that change would have left core with no attachment release path at all, and every attachment ever made would have lived until the runtime stopped. Core change 1 therefore has two halves: supersession stops -removing, and the dispatcher keeps its monitor and removes on the attaching -process's `DOWN`. An explicit detach API was the alternative and was rejected, +removing **unconditionally** — it becomes conditional on the `replace` flag +ADR 0023 already puts on `session.attach`, and narrows to the attaching +process's own prior attachment for that session — and the dispatcher keeps its +monitor and removes on the attaching +process's `DOWN`, **releasing that attachment's transfers as it goes**. + +Both qualifications were found by reading the dispatcher rather than the +design. Core never sees `replace`: the app server parses it and uses it only +to decide whether one connection may hold a second attachment, then builds +core's options without it — so what actually replaces an attachment today is +an unconditional same-session block, and *that* block is the implementation of +explicit replacement. Making it conditional preserves the foreground server's +behaviour exactly, since one connection there holds one attachment, and is +what generation 2 needs, since a second connection must not detach the first. +And that same block is the **only** caller of the function that releases an +attachment's open transfers, which accepted ADR 0028 requires of every detach — +so the `DOWN` path takes that call over rather than leaving the requirement +with nothing to satisfy it. An explicit detach API was the alternative and was rejected, since it needs a call on every exit path including the ones where the caller is already gone. The daemon needs nothing new: it attaches from its per-connection process. From daa43751dbfd509917c047fc29358610a0a1e46b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:37:56 -0700 Subject: [PATCH 143/585] plan(M5): phase 6 stops the runtime; the inventory leaves the archive MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit H6. Phase 6's justification -- "of the processes stopped here only the transfers owner runs a `terminate/2` at all" -- is false, because step 5, the runtime stop, is inside phase 6. `Supervisor.stop(runtime_supervisor, :normal, remaining)` brings down a tree whose `OwnerGroup` children trap exits, carry `shutdown: :infinity` and have a `terminate/2` that stops their own worker supervisor with `:infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), and nothing bounds that from inside. The sentence is deleted and replaced with the rule this file already argues for the kill path: the runtime stop is attempted with what remains of phase 6 and killed at the bound, crash-equivalent in the only sense this plan claims -- about the journal, not about processes -- with trapping descendants unwinding afterwards on their own clock, which the daemon does not wait for and the halt ends. Five seconds is a ceiling for the work the phase performs, not a promise about the subtree, and the drain is why that is affordable. The runtime is enumerated in phase 6 in the phase table, the limits row and M5.md. H7. `SOURCE_INVENTORY` could not have existed. `git archive` exports the **committed** bytes of tracked files, and `export-subst` substitutes a fixed set of `$Format:…$` placeholders into a file's contents -- none of which expands to a path list -- so a tracked file cannot learn at staging time what the tree contains. The previous design asked the extraction to carry an answer only the repository has, as the design before it had asked it to consult a `.git` that is not there. The inventory moves outside the archive to the party that has the repository: closure evidence records `git ls-files -z` at the candidate and its SHA-256 beside the archive's digest and commit, and the extracted-build witness compares the built tree's path set and bytes against that recorded inventory. The extraction carries only `SOURCE_IDENTITY`, which `export-subst` genuinely can fill. That is also the more honest arrangement: an inventory shipped inside the thing it describes is checkable only against itself. --- docs/plans/M5-technical.md | 91 ++++++++++++++++++++++++++------------ docs/plans/M5.md | 5 ++- 2 files changed, 65 insertions(+), 31 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 4cf73256a..d53f0b6ec 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -696,34 +696,48 @@ and one shared resolver they both call: source digest, so an identity naming a commit whose tree is not what was built is detectable rather than merely trusted. -**The unchanged-tree check needs an inventory, because an extraction has no -index.** An earlier revision said the resolver hashes "the extracted tracked -source paths" — but *tracked* is a fact held in `.git`, and `git archive` -leaves none, so there is nothing to enumerate and the check would either -compute over an empty set or fall back to a glob nobody stated. The archive -therefore carries the enumeration with it: - -- a tracked **`SOURCE_INVENTORY`** file, generated from - `git ls-files -z` at the moment the archive is staged and written as the - sorted list of every path in it, so the extraction holds the same answer the - checkout would have given; -- **both** halves are compared, before the build and again after: the **path - set**, so a file created or deleted during the build is caught even if every - file it names is byte-identical, and the **bytes**, as a SHA-256 over each - path's contents in inventory order; +**The unchanged-tree check needs an inventory, and the inventory cannot ride +inside the archive.** An earlier revision said the resolver hashes "the +extracted tracked source paths" — but *tracked* is a fact held in `.git`, and +`git archive` leaves none. A later one put a tracked `SOURCE_INVENTORY` in the +archive, "generated at the moment the archive is staged", which cannot happen +either: `git archive` exports the **committed** bytes of tracked files, and +`export-subst` substitutes a fixed set of `$Format:…$` placeholders into a +file's contents — there is no placeholder that expands to a path list, so a +tracked file cannot learn what the tree contains at staging time. Both designs +asked the extraction to carry an answer only the repository has. + +So the inventory stays **outside** the archive, with the party that has the +repository: + +- **the closure evidence records the candidate's inventory**: the output of + `git ls-files -z` at that commit, and its SHA-256, retained on + `docs/evidence/M5-closure-runs.md` **beside the archive's own digest and + commit**. The closure runner is in the checkout when it stages the archive, + so this costs one command it is already positioned to run; +- **the extracted-build witness compares against that recorded inventory**, + not against anything inside the extraction: it takes the built tree's + **path set**, so a file created or deleted during the build is caught even + if every file it names is byte-identical, and its **bytes**, as a SHA-256 + over each path's contents in inventory order, and requires both to match + what was recorded; - exactly **one** exclusion, named rather than implied: the build-output roots `_build/` and `deps/`, which the build is supposed to create. Nothing else is excluded, and the list of exclusions is part of the retained evidence, so a later exclusion cannot quietly widen what "unchanged" means. -Its witness is the one an inventory-free check could not have: a file is +The extracted tree therefore needs to carry only `SOURCE_IDENTITY`, which +`export-subst` genuinely can fill, and the inventory is evidence rather than a +build input — which is also the more honest arrangement, an inventory shipped +inside the thing it describes being checkable only against itself. + +Its witness is the one neither earlier design could have: a file is created **inside the extraction and outside the excluded roots** during the -build, and the resolver is asserted to **refuse** with the changed-tree -reason — where the same build without it succeeds. An empty or missing -`SOURCE_INVENTORY` is itself a refusal, on the same rule as an unsubstituted -identity, so a check that enumerated nothing cannot read as a pass. The -inventory, the exclusion list and both digests are retained with the closure -runs beside the archive's own SHA-256. +build, and the comparison against the recorded inventory is asserted to +**refuse** with the changed-tree reason — where the same build without it +succeeds. A missing or empty recorded inventory is itself a closure refusal, +on the same rule as an unsubstituted identity, so a check that compared +against nothing cannot read as a pass. The **mismatch** case is proved where the external truth exists: the release check stages the archive with `git archive` from a known commit, retains the @@ -2200,7 +2214,7 @@ that already exists somewhere, and the operator maximum is the sum: | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | | 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across the unsettled coordinators | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | -| 6 | **Daemon teardown** | **5 s** | This plan's one chosen number, covering the notice, the closes, the lease owners, the relay and the edges | +| 6 | **Daemon teardown** | **5 s** | One of this plan's two chosen numbers, covering the notice, the closes, the lease owners, the relay, **the runtime tree** and the edges. The runtime stop is attempted with what remains and killed at the bound; its trapping descendants unwind afterwards on their own clock, which the daemon does not wait for | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | > **Maximum graceful stop = 5 s + 300 s + 90 s + `budget_ms` + 90 s + 5 s + @@ -2398,11 +2412,30 @@ the failed-start reverse cleanup, for the same reason. formula.** An earlier revision named the clock and never gave it a value, which left the operator bound unstatable and every "what remains" reference undefined. Five -seconds is chosen, not derived: nothing under this deadline waits on a -session, an effect or a filesystem sync — the notification writes are one -attempt into an existing buffer, the closes are closes, and of the processes -stopped here only the transfers owner runs a `terminate/2` at all — so the -budget is a ceiling for a set of actions that are each milliseconds. It is +seconds is **chosen, not derived**: the notification writes are one +attempt into an existing buffer, the closes are closes, the lease owners and +the daemon's own processes run no `terminate/2`, and the transfers owner's +closes the descriptors it holds — each of them milliseconds. + +**One process under this deadline is not like the others, and an earlier +revision's justification was false for it.** That revision said "of the +processes stopped here only the transfers owner runs a `terminate/2` at all", +which forgets that **step 5, the runtime stop, is inside phase 6**: +`Supervisor.stop(runtime_supervisor, :normal, remaining)` brings down a tree +whose `OwnerGroup` children trap exits, carry `shutdown: :infinity` and have a +`terminate/2` that stops their own worker supervisor with `:infinity` +(`owner_group.ex:14-19`, `:50`, `:86-90`). Nothing bounds that from inside. + +So the rule is the one this file already argues for the kill path, applied +honestly here: **the runtime stop is attempted with what remains of phase 6 +and killed at the bound.** A tree killed that way is crash-equivalent in the +only sense this plan ever claims — about the journal, not about processes — +and its trapping descendants go on unwinding on their own clock afterwards, +which the daemon does not wait for and the halt at the end of the sequence +ends. Five seconds is therefore a ceiling for the work phase 6 *performs*, not +a promise about what the runtime's subtree has finished, and the drain is why +that is affordable: by the time step 5 runs, every coordinator quiesce could +not settle has already been fenced and terminated inside core. It is recorded in the limits table with that rationale. **Phase 6's deadline starts when phase 5 ends**, and it covers every @@ -4165,7 +4198,7 @@ line; M5 introduces none of its own. | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | | Phase 4, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | -| Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep and every non-Store stop | This plan. Chosen, not derived: nothing under it waits on a session, an effect or a filesystem sync, so it is a ceiling for actions that are each milliseconds | +| Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Maximum graceful stop | `budget_ms` + **525 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 06a32d184..fe3fd05c4 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -434,8 +434,9 @@ hundred for the settle, after which the stop proceeds. Then ninety for admitting every session's abort, the drain budget **core derives and reports** for the cancellation, ninety for the fence, five for terminating the coordinators that did not settle, five for every non-Store -action after the drain — the stop records, the closes, the lease owners and -the edges — and thirty for the Store stop that releases the marker. Seven of +action after the drain — the stop records, the closes, the lease owners, the +runtime tree and the edges, the runtime being attempted with what remains and +killed at the bound — and thirty for the Store stop that releases the marker. Seven of the eight are fixed, so the maximum is **`budget_ms` plus 525 seconds** — a worst case assembled from the store adapter's ceiling for a wedged filesystem, not the cost of an ordinary stop, which finishes in milliseconds. **Five** of the seven are counts of the From 75ca9f47dcb4018fef3e9a7eb09dbcfc19d61aa0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:41:32 -0700 Subject: [PATCH 144/585] plan(M5): name the phase enforcers, and seven smaller repairs M3. Phases 2, 4 and 5 had bounds and no enforcer, and the call that does the work cannot be one: a coordinator's `command/3` waits `:infinity` by design (`session_coordinator.ex:146-149`) and must, a timeout there being evidence of nothing. Quiesce runs each session's admission and each session's fence in its own task and bounds the task -- `Task.async/1`, one `Task.yield/2` against what remains of the phase's absolute deadline, `Task.shutdown/2` for the rest. Both shutdowns get classification rows: a phase-2 admission that did not answer is ambiguous, so no cleanup is released and the session is fenced; a phase-4 fence that did not answer is `{:unknown, head}` with the domain fenced. Phase 5 needs no task, the coordinator's own `shutdown: 5_000` being the enforcer. M1. The admission relay had a row in the process table and no startup step, so the one process the cut depends on had no place in the order. It is step 6, after the runtime it needs and before the socket, in the sequence, the drain-and-check list and the startup-failure matrix. M2. `control_entry` was two values because `:acquiring` was argued to be unobservable. It is observable on both **replayed** branches: a replayed create takes the second arm at `control.ex:902-919` and a replayed resume `:311-312`, both replying immediately whatever the entry holds, so a replay concurrent with another connection's resume -- which sets `:acquiring` at `:1185-1192` -- reads it. The field is `:active | :acquiring | :dormant`, with a reservation row releasing on a replayed `:acquiring` because the concurrent call holds its own, and a row stating a fresh resume can never answer it. M4. "The negotiation list a server advertises carries both" -- no server advertises both: the foreground server serves generation 1 and the daemon generation 2, one each. M5. One lease per connection, in both ADRs. It is what makes "close the controller's connection" name exactly one session, and without it the session-scoped close was ambiguous. M6. Fifteen files carry the retired generation string; the rename edits thirteen. The two it does not are the `CHANGELOG` entry recording what `0.1.0` shipped, which stays true beside a new `0.2.0` entry, and ADR 0032-technical, which carries it inside this set and is changed by the ADR work rather than by the search-and-replace. M7. The fence's `tx_id` and incarnation took identical inputs through `owner_identity/3`, which hashes the namespace with them -- so under one namespace they would be the same string. Two namespaces, `"drain_fence"` and `"drain_fence_incarnation"`, as the coordinator already does with `"owner_tx"` and `"owner_incarnation"` (`session_coordinator.ex:1222-1224`). L1 "the socket path is already gone" is a residue of the design that unlinked; it is left in place. L2 the fail-stop's operator bound is stated: 5 s + 30 s = 35 s, no derived term, 5 s on the two store classes. L3 `control.ex:894`, `bin/loopex:60`. --- ...tachment-residency-and-replay-technical.md | 12 +- ...controller-lease-and-takeover-technical.md | 10 ++ docs/plans/M5-technical.md | 140 +++++++++++++----- docs/plans/M5.md | 12 +- 4 files changed, 133 insertions(+), 41 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 02f5bfc10..2ca3406d9 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -147,8 +147,10 @@ is a malformed request, answered with ADR 0023's `invalid_request`, and never well-formed to put through it. Every other field of those requests is ADR 0023's, unchanged. A connection is one attachment after `session.attach`; generation 2 permits a connection to -hold at most one attachment at a time and a client process to hold as many -connections as the residency limits admit. +hold at most one attachment at a time — **and at most one controller lease**, +which ADR 0033 fixes for the same reason and which is what makes closing "the +controller's connection" name exactly one session — and a client process to +hold as many connections as the residency limits admit. **An attachment never outlives the process that attached it, and M5 is what makes that true.** The mechanism is a monitor, not a detach call. Today the @@ -555,8 +557,10 @@ recomputed and re-pinned alongside generation 2's, with every other input to it byte-identical. Its two published manifests are not touched: they already declare `loopex.experimental/1`, so the rename makes the code agree with them rather than changing them. The -negotiation list a server advertises therefore carries `loopex.experimental/1` -and `loopex.experimental/2`, and neither carries the old name. +generations the two servers advertise are therefore `loopex.experimental/1` +from the foreground server and `loopex.experimental/2` from the daemon — +**neither advertises both**, each serving exactly one generation, which is what +the exact-generation rule means here — and neither carries the old name. ### Generation 2, at the precision literal vectors need diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index bea5a83d1..36793f3c8 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -158,6 +158,16 @@ lease record by another name, which this decision rejects for its own reasons. The relay is not that: it holds no lease and no authority, only the fact that a call it made has not yet been accounted for. +**One lease per connection.** A connection holds at most one controller lease +at a time, so a client that wants to drive two sessions opens two connections. +That is the same shape ADR 0032 already gives attachments — one per +connection — and it is what makes the session-scoped close exact: when a lease +owner dies, "close the controller's connection" names one session's controller +and cannot take a second session's control down with it. Without the rule the +close would be ambiguous, and a second acquisition on a connection that +already holds a lease refuses `control_held` for its own session rather than +being quietly admitted. + A holder's connection is **exempt from ADR 0032's idle eviction while the lease is held**, for the reason that decision states: evicting it would close the connection the lease is bound to, and only an explicit diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d53f0b6ec..a049863ce 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -595,8 +595,8 @@ foreground server on the same root exactly as it would without this decision; what a `0.1.0` *client* then talks to is a `0.1.0` server, which speaks the old string again. -**The fourteen files that carry the string today**, named here so workstream 3 -can be checked against a list rather than a grep: +**Fifteen files carry the string today; the rename edits thirteen**, named +here so workstream 3 can be checked against a list rather than a grep: `apps/loopex_app_server/lib/loopex_app_server.ex` and its three tests (`app_server_test.exs`, `initialization_test.exs`, `stdio_probe_test.exs`); `apps/loopex_protocol/lib/loopex_protocol/session.ex:32` with @@ -610,12 +610,18 @@ the code is being made to agree with; The documents are closure obligations under the docs gate, which reads every tracked file in `docs/operator` and `docs/developer`, so none can be missed. -**`CHANGELOG.md` is the fourteenth and is deliberately *not* rewritten.** It -carries the string in the entry that records what `0.1.0` shipped, and that +**Two carriers are deliberately *not* rewritten, which is why fifteen and +thirteen are both right.** `CHANGELOG.md` carries the string in the entry that +records what `0.1.0` shipped, and that entry stays true: `0.1.0` did serve `loopex.session.v1-experimental`. The -rename is recorded as a `0.2.0` entry instead. An earlier list of these files -had thirteen and omitted it, which would have left the rename either missing -from the changelog or silently editing history. +rename is recorded as a **new** `0.2.0` entry instead, so the changelog is +touched without that occurrence moving. And +**`docs/adr/0032-daemon-attachment-residency-and-replay-technical.md` is the +fifteenth**: it carries the retired name inside *this* set, in the passage +that explains the rename, and it is changed by this milestone's own ADR work +rather than by workstream 3's search-and-replace. An earlier revision said +"fourteen files that carry it" and then listed thirteen edits, which is the +arithmetic this paragraph exists to close. Rollback to `0.1.0` is stopping the daemon. Removing it restores the M4 foreground server and the CLI on the same root with no durable dependency on @@ -976,21 +982,32 @@ carries two plain fields beside the session ID:** | Field | Values | What the daemon does with it | | --- | --- | --- | | `disposition` | `:fresh` \| `:historical` | Charge an activation for `:fresh`; charge nothing for `:historical` | -| `control_entry` | `:active` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | +| `control_entry` | `:active` \| `:acquiring` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | -**`control_entry` is two values over three statuses, and the mapping is -stated rather than left to be guessed.** `Control` holds `:active`, +**`control_entry` is three values over three statuses plus no-entry, and an +earlier revision argued one of them away.** `Control` holds `:active`, `:acquiring` and `:unavailable`, and a session may have no entry at all -(`control.ex:569`, `:620`, `:818`, `:862`, `:1030`, `:1150`, `:1189`). -`control_entry` answers the only question the daemon has — *is there a live -coordinator for this session right now?* — so `:active` maps to `:active`, -and **`:unavailable` and no-entry both map to `:dormant`**, there being no -coordinator either way. `:acquiring` is never observed by the caller of a -**completed** create or resume: it is the status while that very call is -starting an owner, and the call does not answer until the owner is ready or -the attempt has failed, at which point the entry is `:active` or -`:unavailable`. A caller therefore cannot see it, and the field does not need -a third value to be total. +(`control.ex:569`, `:620`, `:818`, `:862`, `:1030`, `:1150`, `:1189`). The +mapping is `:active` → **`:active`**; `:acquiring` → **`:acquiring`**; +`:unavailable` and no-entry → **`:dormant`**, there being no coordinator +either way. + +That revision said `:acquiring` "is never observed by the caller of a +completed create or resume", reasoning that the status exists only while that +very call is starting an owner. The reasoning is wrong on both **replayed** +branches, which are the branches the daemon most cares about. A replayed +create takes the second arm of the `cond` at `control.ex:902-919` and replies +`{:ok, session_id}` **immediately, whatever the entry holds**; a replayed +resume replies the same way at `:311-312`. Neither starts an owner and +neither waits for one. So a client replaying a create while another connection +is concurrently resuming that same session — which sets `:acquiring` at +`:1185-1192` — reads `:acquiring`, from a call that completed without +touching it. + +The field therefore carries it, and the reservation table says what to do +with it: a **replay** that sees `:acquiring` **releases** its reservation, +because some other call is doing the activating and holds its own; a **fresh** +resume can never answer `:acquiring`, having waited for its own owner. **It is `control_entry`, not `residency`, and the rename is the point.** `residency` is a **daemon** fact on the wire — what `session.list` reports @@ -1031,7 +1048,7 @@ So core change 5 adds **two daemon-facing functions beside them**, `Loopex.Runtime.create_session_detailed/3` and `resume_session_detailed/3`, answering `{:ok, %{session_id: binary(), disposition: :fresh | :historical, -control_entry: :active | :dormant}} | {:error, term()}`. The existing pair +control_entry: :active | :acquiring | :dormant}} | {:error, term()}`. The existing pair keeps its exact spec and its exact return, implemented as a projection of the detailed one, so `loopex.ex:87-95` and `:110-117` forward what they forward today and no embedded caller sees anything move. The daemon calls the detailed pair, @@ -1169,6 +1186,8 @@ leaked until the daemon restarts: | Create, `disposition: :fresh` | **Converted** — a coordinator started | | Create, `:historical` with `control_entry: :active` | Released — that session was counted when it was activated | | Create, `:historical` with `control_entry: :dormant` | Released — a replay starts nothing. `:dormant` here covers both a `Control` entry that is `:unavailable` and no entry at all: neither is a live coordinator, and neither was charged | +| Create or resume, `:historical` with `control_entry: :acquiring` | Released — another call is activating that session **and holds its own reservation**; charging this one too would spend two slots for one coordinator. The replay started nothing, which is what `:historical` says | +| Resume, `disposition: :fresh`, `control_entry: :acquiring` | **Cannot occur**, and the row says so rather than omitting it: a fresh resume waits for its own owner, so by the time it answers the entry it created is `:active` or the call has failed | | Resume, `disposition: :fresh` | **Converted** — a coordinator started | | Resume, `:historical` | Released — the replayed result is returned without starting an owner (`control.ex:311-312`) | | Any of the three refusing — `runtime_command_conflict`, `store_unavailable`, an invalid identifier, a placement mismatch, an attach whose first leg answers `{:error, :runtime_unavailable}` on its 5 s default, any other `{:error, _}` | Released. An attach refused at its first leg is the same case as any other refusal, because that leg mutates nothing (`control.ex:1235-1251`) | @@ -1375,13 +1394,19 @@ runtime — rather than against a staged one the plan would have to invent: never reads, unlinks or binds the socket path. 5. **Read the session directory and build the index**, refusing at the recorded-entry bound. -6. **Create the `0700` subdirectory, remove any stale socket pathname, and +6. **Start the admission relay.** It is the ninth of the ten linked + processes and the last before the listener: it needs the runtime step 4 + returned, and it must exist before any connection can be accepted, because + every call that changes core state goes through it. An earlier + revision gave it a row in the process table and no step here, which left + the one process the admission cut depends on with no place in the order. +7. **Create the `0700` subdirectory, remove any stale socket pathname, and bind the `0600` socket**, then read back and verify ownership and mode. Removing the stale pathname is this daemon's right and only this daemon's: it holds the verified marker, which is the only moment at which removing a socket file is unambiguously correct. A predecessor that left one — every fail-stop leaves one — is cleaned up here rather than by itself. -7. **Begin accepting**, then **print the readiness line**. +8. **Begin accepting**, then **print the readiness line**. No lease owner exists at this point, and none is started here: one is started when a session is activated, which cannot happen before a client connects. @@ -1455,6 +1480,7 @@ Four rules, each narrow: as the only account of an acquisition that already happened. - **The owner drains and checks before every acquisition it performs itself.** Before taking the marker, before calling the composition function, before + starting the relay, before binding the socket and before printing the readiness line, the owner reads whatever is in its mailbox for a stop message or an `{:EXIT, …}` and checks that every component it has already started is alive. Any of those aborts @@ -2116,7 +2142,7 @@ handler and `:os.set_signal/2` refuses the name outright, which the command (`interrupt.ex:13-17`). So a terminal `Ctrl-C` reaches a daemon the only way a reserved signal can — from outside the emulator. `apps/loopex_cli/bin/loopex` traps `INT TERM HUP QUIT` and forwards -`kill -TERM` to its child (`bin/loopex:51-60`), so **`SIGINT` is a launcher +`kill -TERM` to its child (`bin/loopex:60`), so **`SIGINT` is a launcher concern and `SIGTERM` is the escript's**. A daemon started without that launcher has no `SIGINT` behaviour to specify, and the plan says so rather than implying one. @@ -2139,7 +2165,7 @@ defaults. rather than giving one answer for two different processes.** It has to, because `apps/loopex_cli/bin/loopex` traps **`INT TERM HUP QUIT`** and forwards every one of them to its child as `kill -TERM` -(`bin/loopex:51-60`) — so what a signal means is decided by whether it lands +(`bin/loopex:60`) — so what a signal means is decided by whether it lands on the launcher or on the escript: | Signal | Sent to the **launcher** | Sent to the **escript** directly | @@ -2321,6 +2347,32 @@ and covers steps 3, 4, 5 and the non-Store part of step 6. Phase 7 is the Store stop at the end of step 6. Nothing is bounded twice and nothing is bounded by nobody. +**Who enforces a phase, since a bound with no enforcer is a wish.** Phases 2, +4 and 5 are core's, and none of them can be bounded by the call that does the +work: a coordinator's `command/3` waits `:infinity` by design +(`session_coordinator.ex:146-149`), and must, because a timeout there is not +evidence of anything. So quiesce runs **each session's admission and each +session's fence in its own task**, and bounds the task rather than the call: +`Task.async/1` per session, one `Task.yield/2` against what remains of the +phase's absolute deadline, then `Task.shutdown/2` for whatever has not +answered. That is the ordinary bounded-task idiom, it needs no new mechanism, +and it is what makes "concurrent across sessions" and "bounded per phase" +the same sentence rather than two hopes. + +What a shutdown means is decided, not left open, and the classification table +below carries both rows: + +- **a phase-2 admission that does not answer** leaves the session's abort + neither known-committed nor known-refused, which is the ambiguous case this + section already handles: **no cleanup is released for it and it is fenced**; +- **a phase-4 fence that does not answer** is exactly a fence whose outcome + the drain cannot read, so it is reported **`{:unknown, head}`** and the + domain stays fenced — the same disposition a `commit_unknown` gets, reached + by a different route; +- **phase 5 needs no task**, being `Supervisor`-shaped already: terminating a + coordinator is bounded by the `shutdown: 5_000` its own child specification + carries (`session_coordinator.ex:134-142`), which is the enforcer. + **One rule keeps a phase from starting work it cannot finish, and with the counts above it can always be honoured.** *No Store operation begins without at least its own 30 s remaining in its phase.* Because @@ -2390,7 +2442,7 @@ not the sum — is what keeps the bound flat as sessions multiply. **And core derives it because the daemon cannot.** Each `g_i` is the grace that session **committed**, read from its durable state (`session_coordinator.ex:422`); the daemon's `--cleanup-grace-ms` is the -default a *new* session is composed with (`control.ex:890-891`), not a fact +default a *new* session is composed with (`control.ex:894`), not a fact about sessions already in the root. A root carrying sessions created under an earlier composition therefore holds graces the daemon has never seen. An earlier revision had the daemon compute the budget from its own option, which @@ -2643,8 +2695,9 @@ the owner fixes. executor first, since stopping it is what sets its Port-owning workers terminating the captured process groups. Then the tracing capability, custody and the registry, which hold nothing durable. Then the Store, whose `terminate/2` releases the writer marker — - see the marker invariant in ADR 0031. The socket path is already gone, - left in place by step 3 for the next marker holder to remove, so the last + see the marker invariant in ADR 0031. The socket path is **left in place** + by step 3 for the next marker holder to remove — "already gone" was a + residue of the design that unlinked — so the last act is the halt: **`0`**, or the class, in the case above where something failed on the way out. @@ -3021,8 +3074,16 @@ carried: it described three outcomes and returned none of them. ID bound to the canonical mutation digest (`vision-technical.md:710-716`), and a random incarnation is what breaks that binding. So the fence's incarnation derives from the same three inputs - the `tx_id` does, through the same `owner_identity/3` discipline, and a - re-presentation is **byte-identical**. + the `tx_id` does, through the same `owner_identity/3` discipline, **under a + second namespace**: `"drain_fence"` for the transaction id and + `"drain_fence_incarnation"` for the incarnation. The two namespaces matter + rather than being tidiness — `owner_identity/3` hashes the namespace with + its inputs, so one namespace over identical inputs would make the + incarnation and the transaction id the *same string*. The coordinator + already does exactly this, deriving both from `owner_identity/3` under + `"owner_tx"` and `"owner_incarnation"` + (`session_coordinator.ex:1222-1224`). A + re-presentation is then **byte-identical**. A `:tx_id_conflict` is nonetheless given a row, because a rule with no answer for a result the adapter can return is not total: it is handled @@ -3123,6 +3184,8 @@ carried: it described three outcomes and returned none of them. | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes**, for the same reason: there is no coordinator, and there may be a transaction | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No | + | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused | `unsettled`, with no cleanup released | **Yes** | + | **A phase-4 fence that did not answer** inside the phase, its task shut down | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | **`:acquiring` is reachable, and an earlier revision called it unreachable.** That revision's argument was the cut: only `session.create` and @@ -3329,7 +3392,17 @@ to write. `executor_lost` there is no executor left to read the lease holder's `DOWN` at all. 6. Write the class on `stderr`, then **halt with the non-zero status** for - that class. Nothing restarts anything: the owner `start_link`s its fixed + that class. + + **A fail-stop has an operator bound too, and it is much smaller than an + orderly stop's.** Only two of its steps can wait: the executor stop, under + the same five seconds phase 6 uses, and the Store stop, in its own fixed + thirty. Nothing else waits on anything — there is no drain, no admission, + no fence, no coordinator to terminate and no runtime tree to bring down. + So **the maximum for any fatal class is 5 s + 30 s = 35 s**, with no + derived term in it at all, which is the one number an operator setting a + restart policy needs and which an earlier revision left them to infer. On + the two store classes it is 5 s, the Store being already gone. Nothing restarts anything: the owner `start_link`s its fixed set and restarts none, so an exit it did not cause is fatal by its own clause — which is why this path exists at all rather than being a restart. @@ -3498,7 +3571,7 @@ opposite for the same failure. The rule is the bind: | Where the start failed | Socket pathname | `daemon/` subdirectory | | --- | --- | --- | -| **Before the bind** — path resolution, signal install, the registry, custody or capability, composition and the marker, the index read, the subdirectory create | **None exists**; nothing was bound, so nothing is left | Removed **only if this start created it and it is empty**; a subdirectory that was already there, or that holds anything, is left exactly as found | +| **Before the bind** — path resolution, signal install, the registry, custody or capability, composition and the marker, the index read, the relay, the subdirectory create | **None exists**; nothing was bound, so nothing is left | Removed **only if this start created it and it is empty**; a subdirectory that was already there, or that holds anything, is left exactly as found | | **At or after the bind** — the permission read-back, the accept, the readiness write, or any component dying during those | **Left in place**, closed but not unlinked, like every other exit path | **Left in place**, because it holds that pathname | Both halves follow from one rule already stated and one plain fact: **no @@ -3728,7 +3801,7 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. Four cases send `INT`, `TERM`, `HUP` and `QUIT` **to the launcher**, `apps/loopex_cli/bin/loopex`, and each asserts the **orderly sequence** — because the launcher traps all four and forwards `kill -TERM` - (`bin/loopex:51-60`), so through the shipped path all four mean stop. Four + (`bin/loopex:60`), so through the shipped path all four mean stop. Four more send the same signals **to the escript process itself**: `TERM` asserts the orderly sequence, and `HUP` and `QUIT` assert the emulator's own behaviour with **no** orderly stop — no `daemon.stopping` record, no drain — @@ -4200,6 +4273,7 @@ line; M5 introduces none of its own. | Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | +| Maximum fail-stop exit | **35 s** — 5 s for the executor stop and the Store's own fixed 30 s, the only two steps of that path that wait; 5 s on the two store classes, where the Store is already gone | This plan, as the sum of its parts | | Maximum graceful stop | `budget_ms` + **525 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index fe3fd05c4..85e328abd 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -824,10 +824,14 @@ lease — and the companion's rejoin order says where each part goes. module — means restructuring it per generation, which is where that restructuring is owned. **The generation rename lands here too**, in that same restructuring: `loopex.experimental/1` replacing - `loopex.session.v1-experimental` across the fourteen files that carry it - today — the app-server module and its three tests, the protocol module and - its two suites, the Node client, five documents, and a new `CHANGELOG` - entry rather than an edit to the `0.1.0` one — with generation 1's schema + `loopex.session.v1-experimental` across the **thirteen** files the rename + edits — the app-server module and its three tests, the protocol module and + its two suites, the Node client, and five documents under `docs/developer/` + and `docs/operator/` — plus a **new** `CHANGELOG` entry rather than an edit + to the `0.1.0` one, which stays true. Fifteen files carry the string today; + the two the rename does not edit are that `CHANGELOG` entry and ADR + 0032-technical, which carries it inside this very set and has already been + changed here — with generation 1's schema digest recomputed and re-pinned as part of it, and its two manifest file digests left alone, because those manifests already carry the new name. Then the daemon's side: the listener, its owner-only peer check and path bound, the startup ordering From 638ba28d1ef97599a9349d8b0a902ccd8ea446f0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:43:03 -0700 Subject: [PATCH 145/585] plan(M5): adversarial pass over the third round Class 30, result totality: M3's task-bounded phases introduced a shutdown whose disposition the fence map could not express. A phase-4 task shut down **before** its head read answered has no head, so there is no identity a successor could recompute and nothing was proposed; it is `{:unknown, :no_head}`, distinct from the `{:unknown, head}` of a fence that was actually attempted, and the type carries both. Class 2, conflicts with accepted ADRs: making supersession conditional touches a rule ADR 0023 states, so both files now say explicitly that **ADR 0023 is unamended** -- its `replace` field, its refusal of an unnamed second attachment and the foreground server's behaviour are all unchanged. What changes is which side of the boundary honours the flag: the app server keeps its connection-level check and passes the flag through, and core stops superseding without being told to. No wire field moves, so no digest input does. Class 5, Concept versus Technical: ADR 0032's Concept described the core change as "coexist without replacing one another" and carried neither the condition nor the transfer release the companion now requires. Both are in it. Checked and clean: no residue of 405, 180 s or "six of the seven"; the startup renumbering has no cross-references to repair, the "step 5" mentions elsewhere being the shutdown sequence and the `:go` ordering table. --- ...daemon-attachment-residency-and-replay-technical.md | 7 +++++++ .../adr/0032-daemon-attachment-residency-and-replay.md | 10 +++++++++- docs/plans/M5-technical.md | 4 +++- 3 files changed, 19 insertions(+), 2 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 2ca3406d9..ce8435493 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -219,6 +219,13 @@ is set. attachment exists to stop. Without the narrowed scope, a `replace: true` from one connection would detach *every other connection's* attachment to that session, which is worse. +- **ADR 0023 stays unamended.** Its `replace` field is unchanged, its rule + that a second attachment refuses unless replacement is named is unchanged, + and what the foreground server does is unchanged. What changes is on which + side of the boundary the flag is honoured: the app server keeps its + connection-level check and now also passes the flag through, and core stops + superseding without being told to. No wire field moves, so no digest input + moves either. - **"The named prior incarnation" is corrected.** An earlier revision of this pair said explicit replacement "invalidates only the named prior incarnation at its last emitted cursor". There is no name on the wire — diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 805ed1e12..6034547bb 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -70,7 +70,15 @@ ADR 0023's existing no-common-generation rule and nothing durable is created; generation-1 clients keep the M4 foreground server, whose wire, one-attachment rule and behavior do not change. A narrow core change lets distinct attachments to the same session coexist without replacing one -another; the core continues to own their independent cursor barriers and +another: the same-session supersession that replaces them today becomes +**conditional on ADR 0023's existing `replace` flag** and narrows to the +attaching process's own prior attachment, and the dispatcher's release on that +process's exit takes over releasing the attachment's open transfers, which +accepted ADR 0028 requires of every detach and which that supersession is the +only caller of today. **ADR 0023 is unamended by this**: its `replace` field, +its refusal of an unnamed second attachment and the foreground server's +behaviour are all exactly what they were, one connection there holding one +attachment; the core continues to own their independent cursor barriers and event-count queues, while the daemon owns per-connection socket output buffers, the resident window and the residency ceilings. The socket path is `daemon.sock` inside a `0700` daemon-owned subdirectory of the state root diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index a049863ce..21240d28c 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -2806,6 +2806,7 @@ Loopex.Runtime.quiesce(runtime) :: budget_ms: non_neg_integer(), drain_id: binary(), fences: %{session_id => :committed | :superseded | :not_needed + | {:unknown, :no_head} | {:unknown, %{owner_epoch: non_neg_integer(), journal_version: non_neg_integer()}}} }} @@ -3185,7 +3186,8 @@ carried: it described three outcomes and returned none of them. | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No | | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused | `unsettled`, with no cleanup released | **Yes** | - | **A phase-4 fence that did not answer** inside the phase, its task shut down | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | + | **A phase-4 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | + | **A phase-4 task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | **`:acquiring` is reachable, and an earlier revision called it unreachable.** That revision's argument was the cut: only `session.create` and From 7fe2c17e7f10069606652058af631d2e24780dd7 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 14:59:24 -0700 Subject: [PATCH 146/585] plan(M5): phase 2 blocks on a callback, and phase 4 fences everything A1. Phase 2 counted Store calls where the thing that blocks is a **callback**. `SessionCoordinator.command/3` is a `GenServer` call (`session_coordinator.ex: 146-149`), so the drained abort waits behind whatever callback the coordinator is running, to completion -- and a callback can make more than one adapter call. The deepest traced makes a commit that re-presents once on `commit_unknown` (`:1752-1768`), two calls, and then a records load in the same callback, the shape the acquisition path shows plainly where `transact_owner/1`'s commit at `:1363` runs on into `recover_committed_owner/1`'s loads at `:1397-1400` without returning. Three, then the drain's own non-retrying admission. **Four calls, 120 s**, and the sum is **`budget_ms` + 555 s**. The witness is rewritten to **construct** the deepest callback rather than wait for one, and to assert that three of the four calls belonged to one callback -- which is what makes the unit the callback rather than the call. A2. Phase 7 reopened the hole phase 4 exists to close. The runtime is killed at phase 6's bound and `OwnerGroup` traps exits with `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so a trapping descendant of a **settled** session's coordinator can still be unwinding -- and phase 7 keeps the Store **alive** for thirty seconds more. A settled session was not fenced, so that straggler's commit would have landed after the census that called it settled. The paragraph claiming such a call "reaches a stopped Store... a refusal, never a write" was false for the whole of phase 7: the Store is not stopped yet. Phase 4 now fences **every session quiesce enumerated** -- settled, unsettled and absent alike, one `advance_owner` each, concurrent, inside the same 90 s, the phase being three sequential calls whatever the session count is. After quiesce returns, no transaction for any of them can commit. The claim survives with a stronger mechanism under it: it holds whether the Store is alive or not. `:not_needed` survives for one decidable case, a session for which no coordinator ever existed in this runtime. The cost is stated -- one ordinary epoch step at the next activation, and two extra journal records per session rather than one, both replayed without a migration -- and the witness is the case that would have failed: a settled session's straggler released during phase 7, asserted refused `:stale_owner_epoch`. A3. The narrowed replacement scope named a set nothing could compute. `install_attachment/3` records no attacher pid (`event_dispatcher.ex:764-803`), supersession splits on `session_id` alone (`:812-818`), and the scan's monitor is dropped at `:455`. Core change 1 therefore keeps the attacher's pid and the monitor reference **on the installed attachment**. That is not a third half: the change already has to keep the monitor for the `DOWN` release, and a `DOWN` carries exactly those two values. One addition, two uses -- the `DOWN` lookup becomes a map lookup, and the replacement scope becomes a filter on a field that exists. --- ...tachment-residency-and-replay-technical.md | 24 +++- docs/plans/M5-technical.md | 129 +++++++++++++----- docs/plans/M5.md | 22 ++- 3 files changed, 133 insertions(+), 42 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index ce8435493..bac14f866 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -156,7 +156,9 @@ hold as many connections as the residency limits admit. makes that true.** The mechanism is a monitor, not a detach call. Today the dispatcher monitors the attaching process only while its snapshot scan is in flight and **demonitors it the moment the scan finishes** -(`event_dispatcher.ex:455`), after which nothing watches that process at all; +(`event_dispatcher.ex:455`), after which nothing watches that process at all +and the installed attachment records neither its pid nor a monitor +(`:764-803`); `disconnect/2` marks an attachment disconnected and empties its queue but leaves the entry in place (`:879-886`); and the one path that actually removes an entry is same-session **supersession** (`:812-823`) — which M5's @@ -209,6 +211,26 @@ prior attachment** for that session. Core's attach options gain `replace`, the app server passes the flag it already parses, and the block fires only when it is set. +**That scope needs an identity the installed attachment does not carry today, +and core change 1 adds it.** `install_attachment/3` builds the attachment map +from the scan's result — `id`, `incarnation_id`, `session_id`, cursors, queue, +capacity, status, metadata, transfers (`event_dispatcher.ex:764-803`) — and +**no attacher pid**; the supersession that follows splits `state.attachments` +on `session_id` alone (`:812-818`); and the monitor the dispatcher held during +the scan is **demonitored the moment the scan finishes** (`:455`). There is +therefore nothing on an installed attachment that says which process attached +it, so "the attaching process's own prior attachment" is not a set anything +could compute. + +Core change 1 therefore **retains the attacher's pid and its monitor reference +on the installed attachment**. That is not a third half: the change already +has to keep the monitor rather than dropping it at `:455`, because the `DOWN` +release is the whole of the second half — and a `DOWN` carries the monitor +reference and the pid, which is exactly what the handler needs to find the +attachment to drop. Holding both on the attachment makes the `DOWN` lookup a +map lookup rather than a scan, and makes the replacement scope a filter on a +field that exists. One addition, two uses. + - **Generation 1 is behaviour-identical**, which is what ADR 0023 requires and what this milestone promises for the foreground server: that host maps one connection to one attachment, so its supersession only ever fired behind a diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 21240d28c..d76210c66 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and each unsettled or coordinator-less session fenced by a committed `advance_owner` so an older in-flight transaction is refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the session that was fenced and `:not_needed` for the one that settled, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort records the drain wrote, with the unresolved transaction and its fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only for an entry that never had a coordinator — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -294,8 +294,8 @@ reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop as the sum of the eight phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 525 s**, being 5 s for closing admissions, 300 s for - settling what was already admitted, 90 s for abort + **`budget_ms` + 555 s**, being 5 s for closing admissions, 300 s for + settling what was already admitted, 120 s for abort admission, `budget_ms` for cancellation, 90 s for the fence, 5 s for coordinator termination, 5 s for daemon teardown and 30 s for the Store — together with the sentence that keeps the number from being read as a @@ -346,9 +346,9 @@ core-internal states a daemon cannot construct through the socket. | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | +| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `a drained abort admission executes three store calls`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `a drained abort admitted behind an in-flight callback spends four store calls in phase 2`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -388,7 +388,7 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | Bound | What the case executes and counts | File | Case | Lane | | --- | --- | --- | --- | --- | | Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | -| Phase 2, three calls | A drained abort admitted behind one in-flight transaction, asserting **three** — two for the transaction already in the lane, one for the drained abort, which does not retry | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admission executes three store calls` | fast | +| Phase 2, four calls | A drained abort admitted behind the **deepest callback**, constructed rather than waited for: the coordinator is made to run a commit that answers `commit_unknown` once — two calls — and to load records in that same callback, and the drained abort is admitted behind it. Asserts **four**, and asserts that the three of them belonged to **one** callback, which is what makes the unit the callback rather than the call | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind an in-flight callback spends four store calls in phase 2` | fast | | Phase 4, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | All three are **core** witnesses, because all three paths are core's: the @@ -2236,15 +2236,15 @@ that already exists somewhere, and the operator maximum is the sum: | --- | --- | --- | --- | | 1a | **Close admissions** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement of a **state change**, not of any work: the relay sets a flag, refuses everything after it, and answers. It has nothing to finish, so this bound measures the relay's own responsiveness and nothing else; a relay that does not answer inside it is a relay the daemon has lost, and the stop becomes the `relay_lost` fail-stop | | 1b | **Settle the admitted** | **300 s** — **ten** Store calls deep, the deepest ticket kind, counted from a traced run rather than from the code; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | -| 2 | **Abort admission** | **90 s** — **three** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission may wait behind the transaction the coordinator already has in flight, which is itself two calls because core's ordinary path retries a `commit_unknown` once; then the drain's own admission, which is one call because it does **not** retry | +| 2 | **Abort admission** | **120 s** — **four** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** the coordinator is already running, which is up to three calls, and then makes its own, which is one | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | | 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across the unsettled coordinators | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | | 6 | **Daemon teardown** | **5 s** | One of this plan's two chosen numbers, covering the notice, the closes, the lease owners, the relay, **the runtime tree** and the edges. The runtime stop is attempted with what remains and killed at the bound; its trapping descendants unwind afterwards on their own clock, which the daemon does not wait for | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 5 s + 300 s + 90 s + `budget_ms` + 90 s + 5 s + -> 5 s + 30 s = `budget_ms` + 525 s**, and `budget_ms` is the one term an +> **Maximum graceful stop = 5 s + 300 s + 120 s + `budget_ms` + 90 s + 5 s + +> 5 s + 30 s = `budget_ms` + 555 s**, and `budget_ms` is the one term an > operator cannot compute in advance. **That is a worst case nobody approaches, and saying so is part of stating @@ -2305,15 +2305,24 @@ are these: 1,024 rows a call — and that is stated rather than papered over with an average, because it is the reason 1b is a **bounded wait that then proceeds** rather than a guarantee that everything has settled. -- **Phase 2 is three.** The abort admission goes to a **live coordinator**, whose - lane is serial — `OwnerLane.transact/2` is a plain synchronous call the - coordinator makes from its own process (`store/owner_lane.ex:83-99`, called - at `session_coordinator.ex:1242`, `:1363`, `:1702`) — so the admission may - wait out one transaction already in flight and then make its own. The - wait-behind is **two** calls, not one: an ordinary commit goes through - `resolve_transaction/2`, which re-presents once on `commit_unknown` - (`:1752-1768`). The drain's own admission is **one**, because it does not — - see the non-retrying commit below. Three, in sequence. +- **Phase 2 is four, and the unit that blocks is the callback rather than the + call.** The abort admission goes to a **live coordinator**, and + `SessionCoordinator.command/3` is a `GenServer` call + (`session_coordinator.ex:146-149`): what it waits behind is not one Store + transaction but **whatever callback that coordinator is currently running**, + to completion. A callback can make more than one adapter call. The deepest + one traced makes a **commit** — `resolve_transaction/2`, which re-presents + once on `commit_unknown` (`:1752-1768`), so two calls — and then **a records + load in the same callback**, the shape the acquisition path shows plainly + where `transact_owner/1`'s commit at `:1363` runs on into + `recover_committed_owner/1`'s loads at `:1397-1400` without returning. + Three, and then the drain's own admission, which is **one** because it does + not retry — see the non-retrying commit below. **Four, in sequence.** + + An earlier revision counted two and then three, both times by counting Store + calls where the thing that blocks is a callback. It is the same error the + create recount made from the other direction: a count taken from the shape + of the code rather than from a run of it. - **Phase 4 is three at worst.** A head read, then the `advance_owner`, then, only where that answers `commit_unknown`, **one** `transaction_status` query. - **And the drain retries nothing, which is a change to the coordinator rather @@ -2777,11 +2786,22 @@ the owner fixes. Stopping it last makes the marker outlive **every operation the owner can end**, which is the honest form of a claim an earlier draft overstated. On the ordinary path that is every operation. On the timeout path it is not: - an orphaned owner-group worker may still be unwinding when the Store goes, - and any call it then makes reaches a stopped Store and **fails as it would - after a VM death**. That is a refusal, never a write — the Store is gone, - so nothing can be appended behind the daemon's back — and it is why the - durability claim is about the journal rather than about quiescence. + an orphaned owner-group worker may still be unwinding when the runtime is + killed at phase 6's bound, and it goes on unwinding **while the Store is + still alive**, because phase 7 gives that stop its own thirty seconds. + + **What refuses its commit is the fence, not a dead Store**, and an earlier + revision had this exactly backwards. It said such a call "reaches a stopped + Store and fails as it would after a VM death… a refusal, never a write", + which is false for the whole of phase 7: the Store is not stopped yet, and + a straggler's `session_commit` in that window would be an ordinary, + acceptable transaction. It is refused because **phase 4 has already moved + that session's owner epoch** — every enumerated session's, settled ones + included, for exactly this reason — so the adapter answers + `:stale_owner_epoch` (`state.ex:548-551`). The claim survives with a + different mechanism under it, and it is a stronger mechanism: it holds + whether the Store is alive or not, where "the Store is gone" only ever held + after phase 7 had finished. One dependency this step relies on is worth naming rather than assuming: `Loopex.Store.Local` **traps exits**, so even an owner that crashes rather @@ -3134,7 +3154,38 @@ carried: it described three outcomes and returned none of them. | The fence **commits** | The epoch has moved; any older `session_commit` linearized afterwards is refused `:stale_owner_epoch` (`state.ex:548-551`) | `:committed` | `unsettled`, fenced | | The fence is refused **`:stale_owner_epoch`** or **`:stale_journal_version`** | The one transaction that could still have been in flight linearized **first**. The fence lost the race on the epoch or on the version; either way the state it read is no longer the state there is, and there is **nothing left to fence** | `:superseded` | Classified **from the journal**, as whatever that commit made it. **No second attempt.** It is not reported as fenced, because it was not | | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | `{:unknown, head}` | Resolved by **one** `Store.transaction_status/4` query under the same derived `tx_id`; an answer that is still unknown after it leaves the session `unsettled` with `{:unknown, head}` carrying the head the fence read, and the domain fenced | - | **No fence is attempted** | The session is in `settled` — its own work ended, so there is nothing ambiguous to fence | `:not_needed` | As its own work left it | + | **No fence is attempted** | No coordinator ever existed for this session in this runtime, so nothing can write for it | `:not_needed` | As the entry left it | + + **Phase 4 fences every session quiesce enumerated — settled, unsettled and + absent alike — and an earlier revision fenced only the ones that had not + settled.** That was a hole, and phase 7 is where it opened. The stop kills + the runtime supervisor at phase 6's bound; `OwnerGroup` traps exits and + carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so + a trapping descendant of a **settled** session's coordinator can still be + unwinding afterwards — and phase 7 then keeps the Store **alive** for up to + thirty seconds more. A straggler's `session_commit` in that window would + land on a session the drain had already reported `settled`, after the + census was taken and with no fence to refuse it. + + So the fence is not a remedy for sessions that failed to settle; it is what + makes the census true for **all** of them. One `advance_owner` per + enumerated session, concurrent, inside the same 90 s — the phase is three + sequential calls whatever the session count is — and after `quiesce/1` + returns, **no transaction for any enumerated session can commit**: the + epoch has moved and the adapter refuses it `:stale_owner_epoch` + (`state.ex:548-551`). + + `:not_needed` therefore survives for one case only, and it is decidable + from the entry rather than from the outcome: a session for which **no + coordinator ever existed in this runtime** — an entry that reached + `:unavailable` without one — where there is nothing that could write and + nothing to fence. + + The cost is stated: a settled session's next activation spends one ordinary + epoch step, exactly as an unsettled one's does, and the journal a drained + root carries holds one fence record per enumerated session beside the + admitted abort. Both are records the released reader replays without a + migration, which is the property the rollback claim rests on. **A stale refusal ends the fence rather than starting a second one, and the reason is the serial lane.** An earlier revision rereads the head and makes @@ -3180,7 +3231,7 @@ carried: it described three outcomes and returned none of them. | What `Control` holds | Why it can be there | Which list | Fenced? | | --- | --- | --- | --- | - | `:active` with a live coordinator | The ordinary case | `settled` or `unsettled`, by whether its cancellation finished inside the budget | Only when `unsettled` | + | `:active` with a live coordinator | The ordinary case | `settled` or `unsettled`, by whether its cancellation finished inside the budget | **Yes, either way** — see below | | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes**, for the same reason: there is no coordinator, and there may be a transaction | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | @@ -3600,7 +3651,7 @@ nothing proves. Each is named where it is used: | Surface | Created by | Read by | | --- | --- | --- | -| The dispatcher's release on `DOWN`, and the transfers it releases with it | Core change 1 | The concurrent-attachment cases, the ADR 0028 transfer case and the attach connection-loss case | +| The dispatcher's release on `DOWN`, the attacher pid and monitor reference it keeps on the attachment to do it, and the transfers it releases with it | Core change 1 | The concurrent-attachment cases, the ADR 0028 transfer case, the scoped-replacement case and the attach connection-loss case | | The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | | `Control`'s excluded-pid set, and `Entry`'s redaction of a keyword pair under its own key | Core change 3 | The trace-exclusion cases, and the render pair that must differ | | `quiesce/1`'s three lists, `budget_ms`, `drain_id` and the per-session `fences` map | Core change 4 | The drain cases, the fence cases and the stop line | @@ -3741,13 +3792,22 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. The journal after this path is **not** byte-identical to an abrupt death at the same instant, and the case asserts the difference rather than the old - equality: it holds exactly one more record per drained session, the admitted - abort. What remains identical is what the abrupt-death case actually needs: - the unresolved transaction, its fence, and the outcome reconciliation - produces. + equality: it holds exactly **two** more records per enumerated session — the + admitted abort, and the `advance_owner` that fences it. An earlier revision + said one, from the revision in which only unsettled sessions were fenced. + What remains identical is what the abrupt-death case actually needs: + the unresolved transaction and the outcome reconciliation produces. + + **A settled session's straggler is the case this fence exists for**, and it + has its own assertion here: a transaction for a session the drain reported + `settled` is held inside the Store and released during **phase 7**, while + the Store is still alive and the runtime has already been killed. It is + asserted refused `:stale_owner_epoch` and absent from the journal. Before + every enumerated session was fenced, that commit would have landed after the + census that called its session settled. **And the rollback assertion sits here**, because this is the path that - writes the extra record: after the drain, the **released foreground + writes the extra records: after the drain, the **released foreground surface** opens that same root on the same adapter, replays it, and resumes the session — no migration, no recovery step, no version refusal. That is the proof that a drained root is still an ordinary root, and it is asserted @@ -4166,7 +4226,8 @@ second copy of the whole wiring layer. One socket listener, **one narrow core concurrent-attachment change with two halves** — supersession stops removing an attachment *unconditionally*, becoming conditional on ADR 0023's existing `replace` flag and scoped to the attaching process's own prior attachment, and -the dispatcher monitors the attaching process and removes +the dispatcher monitors the attaching process, keeps that monitor and the +attacher pid **on the installed attachment**, and removes on its `DOWN`, releasing that attachment's transfers — because the first half alone would leave core with no release path at all, supersession being the only one there is today, and would leave @@ -4269,14 +4330,14 @@ line; M5 introduces none of its own. | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | | Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | -| Phase 2, abort admission | a fixed **90 s** — three sequential Store calls at the adapter's own 30 s `@call_timeout`: the two of a transaction already in the coordinator's serial lane, which retries a `commit_unknown` once, then the drain's own admission, which does not; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:1752-1768` | +| Phase 2, abort admission | a fixed **120 s** — four sequential Store calls at the adapter's own 30 s `@call_timeout`: the three of the deepest **callback** the coordinator may already be running — a commit that re-presents once, then a records load in the same callback — and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1363`, `:1397-1400`, `:1752-1768` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | | Phase 4, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Maximum fail-stop exit | **35 s** — 5 s for the executor stop and the Store's own fixed 30 s, the only two steps of that path that wait; 5 s on the two store classes, where the Store is already gone | This plan, as the sum of its parts | -| Maximum graceful stop | `budget_ms` + **525 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **555 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 85e328abd..361b92cdf 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -407,7 +407,11 @@ the same thing a third time would have cost a persistent-schema decision for nothing. It then drives what is in flight through the cancellation sequence a coordinator already runs for an abort, under the bounds core already derives from that session's committed cleanup grace. And at the deadline it **terminates every coordinator that has not settled -and then commits a Store-linearized owner-epoch fence for it**, so an older +and commits a Store-linearized owner-epoch fence for every session it +enumerated — the ones that settled as well as the ones that did not**, +because the runtime is killed at the teardown bound while the Store stays +alive for its own phase, so a settled session's straggler could otherwise +commit after the census that called it settled; so an older transaction still in flight either wins before the fence and is observed or loses after it and is refused as stale. **That fence's identity is derived from the session's own durable head**, not from anything the daemon holds in @@ -430,19 +434,19 @@ service manager needs one, and it is the **sum of seven bounded phases** rather than one clock that has to cover everything: five seconds for the admission cut — which is two phases, because closing admissions is instant and waiting for what was already admitted is not: five seconds for the close and three -hundred for the settle, after which the stop proceeds. Then ninety for -admitting every session's abort, the drain budget **core +hundred for the settle, after which the stop proceeds. Then a hundred and +twenty for admitting every session's abort, the drain budget **core derives and reports** for the cancellation, ninety for the fence, five for terminating the coordinators that did not settle, five for every non-Store action after the drain — the stop records, the closes, the lease owners, the runtime tree and the edges, the runtime being attempted with what remains and killed at the bound — and thirty for the Store stop that releases the marker. Seven of -the eight are fixed, so the maximum is **`budget_ms` plus 525 seconds** — a +the eight are fixed, so the maximum is **`budget_ms` plus 555 seconds** — a worst case assembled from the store adapter's ceiling for a wedged filesystem, not the cost of an ordinary stop, which finishes in milliseconds. **Five** of the seven are counts of the adapter's own thirty-second call timeout, or the coordinator's own shutdown -value: a phase that makes three Store calls in sequence is bounded at ninety -and one that makes ten at three hundred, and the drain retries nothing, which +value: a phase that makes four Store calls in sequence is bounded at a hundred +and twenty and one that makes ten at three hundred, and the drain retries nothing, which is what keeps those counts finite. The other two — the five seconds for closing admissions and the five for the teardown — are **this plan's own numbers**, chosen rather than derived, and the technical companion says so @@ -1013,7 +1017,11 @@ removing **unconditionally** — it becomes conditional on the `replace` flag ADR 0023 already puts on `session.attach`, and narrows to the attaching process's own prior attachment for that session — and the dispatcher keeps its monitor and removes on the attaching -process's `DOWN`, **releasing that attachment's transfers as it goes**. +process's `DOWN`, **releasing that attachment's transfers as it goes** — for +which the dispatcher keeps the attacher's pid and that monitor's reference +**on the installed attachment**, which it records neither of today, and which +both halves need: the `DOWN` handler to find the attachment to drop, and the +narrowed replacement to know whose prior attachment it may supersede. Both qualifications were found by reading the dispatcher rather than the design. Core never sees `replace`: the app server parses it and uses it only From 3eb3e8a689ba1d2c5346d2b8654ed5d81afdd8ad Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:01:33 -0700 Subject: [PATCH 147/585] plan(M5): traced per-kind depths, seventeen carriers, three wordings B1. The per-kind table had attach at `2 + pages` where it is `1 + pages`, and it left resume as "no constant" without a traced figure. Resume of a twelve-record, eight-event session executes **eleven**: `Store.runtime_command` (`control.ex:310`), `load_records` x2, `transaction_status` (`:1324-1335`), `ownership_head`, **two** `transact` calls -- the staged owner attempt `owner_stage_tx` (`:1162-1167`) and then the advance (`:1363`) -- and then `load_records` x2 and `load_events` x2. Resume makes the `runtime_command` and makes two commits, neither of which the table said. That eleven is worth more than the correction. A small session already exceeds phase 1b's bound of ten, which is not an argument for raising the bound -- no number covers an unbounded history -- but the plainest demonstration that 1b is a bounded wait that **proceeds**, and that the `:acquiring` classification row is an ordinary outcome rather than a remote one. Both kinds get executed-count witnesses at fixed sizes, so the claim that they have no constant is itself checked: attach at 0 and 8 events, resume at 12 records and 8 events. B2 the per-kind heading still said six. B3 M5.md still said seven bounded phases. B4. Seventeen files carry the retired generation string, not fifteen; the rename still edits thirteen. The four it does not are the `CHANGELOG` entry recording what `0.1.0` shipped and the **three carriers inside this planning set** -- ADR 0032-technical, M5.md and M5-technical.md -- each carrying the name only in the passage explaining why it is retired. Counting them is the point: a reviewer running the grep should read seventeen as agreement rather than as drift, which is what happened twice. C1 the phase-2 witness name now says what it measures. C3 it is the **core-witness table** that carries file, case and lane for the ADRs' witnesses, not the Outcome rows, which name a file per outcome and describe the rest in prose. C2. A phase-2 task shut down mid-call does not cancel the call it made: the coordinator admits the abort, writes the same `command_admitted` record and pauses at the split with no cancellation released. The drain does not know which happened, which is why the session is fenced rather than cancelled -- and the journal it leaves is exactly what an unsettled session's journal holds on every other route. Stated, with a witness. --- docs/plans/M5-technical.md | 78 +++++++++++++++++++++++++++----------- docs/plans/M5.md | 12 +++--- 2 files changed, 62 insertions(+), 28 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d76210c66..3e28a3ff9 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -348,7 +348,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `a drained abort admitted behind an in-flight callback spends four store calls in phase 2`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind an in-flight callback spends four store calls in phase 2`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -388,6 +388,7 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | Bound | What the case executes and counts | File | Case | Lane | | --- | --- | --- | --- | --- | | Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | +| The two history-paged kinds, at **fixed** sizes, so the claim that they have no constant is itself checked | `session.attach` over an empty session asserting **1**, and over an eight-event session asserting **2**; `session.resume` of a **twelve-record, eight-event** session asserting **11**, in the traced order, including **two** `transact` calls — the staged owner attempt and the advance | `apps/loopex/test/runtime_quiesce_test.exs` | `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls` | fast | | Phase 2, four calls | A drained abort admitted behind the **deepest callback**, constructed rather than waited for: the coordinator is made to run a commit that answers `commit_unknown` once — two calls — and to load records in that same callback, and the drained abort is admitted behind it. Asserts **four**, and asserts that the three of them belonged to **one** callback, which is what makes the unit the callback rather than the call | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind an in-flight callback spends four store calls in phase 2` | fast | | Phase 4, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | @@ -411,10 +412,13 @@ to both and then named an enforcement point that cannot enforce it.** ADR 0031, 0032 and 0033 describe their evidence in prose, as accepted ADRs in this repository do, and rewriting three proposed ADRs into three-column tables buys nothing a reader needs: the decisions are what those files are for. So the -obligation sits where the tables already are — **this pair's witness tables -carry the file, case and lane for every witness the ADRs describe**, and a -witness an ADR names with no row here is a gap this pair closes, not a defect -in that ADR. That is the smaller of the two changes and it is the one taken. +obligation sits where the tables already are — **this pair's core-witness +table carries the file, case and lane for every witness the ADRs describe**, +and a witness an ADR names with no row there is a gap this pair closes, not a +defect in that ADR. It is that table specifically, and not the Outcome rows: +those name a witness **file** per outcome and then describe what it must +prove in prose, which is the right shape for an outcome and the wrong one for +finding a case by name. That is the smaller of the two changes and it is the one taken. And the enforcement point is **review**, stated plainly. The earlier revision pointed at the derived documentation checklist in Outcome 5's evidence row, @@ -595,7 +599,7 @@ foreground server on the same root exactly as it would without this decision; what a `0.1.0` *client* then talks to is a `0.1.0` server, which speaks the old string again. -**Fifteen files carry the string today; the rename edits thirteen**, named +**Seventeen files carry the string today; the rename edits thirteen**, named here so workstream 3 can be checked against a list rather than a grep: `apps/loopex_app_server/lib/loopex_app_server.ex` and its three tests (`app_server_test.exs`, `initialization_test.exs`, `stdio_probe_test.exs`); @@ -610,18 +614,20 @@ the code is being made to agree with; The documents are closure obligations under the docs gate, which reads every tracked file in `docs/operator` and `docs/developer`, so none can be missed. -**Two carriers are deliberately *not* rewritten, which is why fifteen and +**Four carriers are deliberately *not* rewritten, which is why seventeen and thirteen are both right.** `CHANGELOG.md` carries the string in the entry that records what `0.1.0` shipped, and that entry stays true: `0.1.0` did serve `loopex.session.v1-experimental`. The rename is recorded as a **new** `0.2.0` entry instead, so the changelog is -touched without that occurrence moving. And -**`docs/adr/0032-daemon-attachment-residency-and-replay-technical.md` is the -fifteenth**: it carries the retired name inside *this* set, in the passage -that explains the rename, and it is changed by this milestone's own ADR work -rather than by workstream 3's search-and-replace. An earlier revision said -"fourteen files that carry it" and then listed thirteen edits, which is the -arithmetic this paragraph exists to close. +touched without that occurrence moving. The other three are **inside this +planning set**, each carrying the retired name only in the passage that +explains why it is being retired: +`docs/adr/0032-daemon-attachment-residency-and-replay-technical.md`, +`docs/plans/M5.md` and this file. They are changed by this milestone's own +planning work rather than by workstream 3's search-and-replace, and they are +counted here so a reviewer running the grep finds seventeen and reads it as +agreement rather than as drift. Earlier revisions said fourteen, then +fifteen, each time counting the carriers they had happened to look at. Rollback to `0.1.0` is stopping the daemon. Removing it restores the M4 foreground server and the CLI on the same root with no durable dependency on @@ -2263,7 +2269,7 @@ is the same 30 s: `transact/2` at `local.ex:111-113`, `ownership_head/3` at **(the worst sequential count of Store calls in it) × 30 s**, and the counts are these: -- **Phase 1b is six, and the derivation is per ticket kind.** A ticket settles +- **Phase 1b is ten, and the derivation is per ticket kind.** A ticket settles when its core call answers, and what that call does before answering is not the same for all ten. Counted from the code, in sequence: @@ -2271,8 +2277,8 @@ are these: | --- | --- | --- | | The seven non-resume lease-authorized mutations — `prompt`, `steer`, `follow_up`, `abort`, `respond_interaction`, `admit_resources`, `activate_skill` | **2** | One `OwnerLane.transact/2`, retried once on `commit_unknown` (`session_coordinator.ex:1752-1768`). The wait-behind does **not** apply: this call *is* the session's one in-flight transaction, and the coordinator's `command/3` waits `:infinity` for it (`:146-149`) | | `session.create`, fresh | **9**, or **10** with the one retry | Traced, not counted by eye — see below | - | `session.attach` | **2 + ⌈events ÷ 1,024⌉** | The dispatcher's snapshot scan pages the session's events (`event_dispatcher.ex:169-199`, `:926`) | - | `session.resume` | **no constant** | The create sequence without the genesis pair, plus `prior_transaction_resolved`'s `transaction_status` (`:1324-1335`), with all three `load_all_*` calls paged over real history | + | `session.attach` | **1 + ⌈events ÷ 1,024⌉** — traced at 1 over an empty session and 2 over eight events | The dispatcher's snapshot scan pages the session's events (`event_dispatcher.ex:169-199`, `:926`) | + | `session.resume` | **no constant**, and traced at **11** over a twelve-record, eight-event session | `Store.runtime_command` (`control.ex:310`), then `load_records` ×2, `transaction_status` (`:1324-1335`), `ownership_head`, **`transact` ×2** — the staged owner attempt `owner_stage_tx` (`:1162-1167`) and then the advance (`:1363`) — then `load_records` ×2 and `load_events` ×2 | **A fresh create executes nine adapter calls, and the earlier figure of six was a reading of the code rather than a run of it.** Two errors, both of @@ -2300,11 +2306,20 @@ are these: because a fresh session has no events yet). **Nine, or ten with the retry.** **The maximum over the kinds whose depth is a constant is ten**, which is a - fresh create, so 1b is bounded at ten calls — **300 s**. **Two kinds have no - constant depth** — attach and resume both page over the root's history at - 1,024 rows a call — and that is stated rather than papered over with an - average, because it is the reason 1b is a **bounded wait that then proceeds** - rather than a guarantee that everything has settled. + fresh create — constant because a fresh session holds exactly its genesis + record and no events, so its two `load_records` and one `load_events` are + fixed. So 1b is bounded at ten calls — **300 s**. + + **Two kinds have no constant depth**, attach and resume, both paging over + the root's history at 1,024 rows a call. And the resume trace is worth + reading rather than filing: a **twelve-record, eight-event** session — a + small one by any measure — already executes **eleven**, one more than the + bound. That is not an argument for raising the bound to cover it, because no + number covers a session whose history is unbounded; it is the plainest + possible demonstration that **1b is a bounded wait that then proceeds**, and + that the `:acquiring` row in the classification table is an ordinary + outcome rather than a remote one. An operator whose daemon is stopping with + resumes in flight should expect the stop to reach 1b's bound and go on. - **Phase 2 is four, and the unit that blocks is the callback rather than the call.** The abort admission goes to a **live coordinator**, and `SessionCoordinator.command/3` is a `GenServer` call @@ -2382,6 +2397,23 @@ below carries both rows: coordinator is bounded by the `shutdown: 5_000` its own child specification carries (`session_coordinator.ex:134-142`), which is the enforcer. +**Shutting down a task does not cancel the call it made**, and the phase-2 +row's consequence is worth writing out rather than leaving as an +implication. `Task.shutdown/2` ends the task; the `GenServer` call that task +already delivered runs to completion in the coordinator regardless, which is +the same property that makes a dead caller's transaction commit and a dead +relay task's mutation reach core. So a phase-2 admission the drain gave up on +still **lands**: the coordinator admits the abort, writes the same +`command_admitted` record, and **pauses at the split** with no cancellation +released, because the drained path is what it is running. The drain simply +does not know which of those happened, which is why the session is fenced +rather than cancelled. + +That is the right outcome and not a regrettable one: the journal ends up with +an admitted abort and no cleanup, which is exactly what an unsettled session's +journal holds on every other route to it. What the drain must not do — release +a cancellation for a command it cannot confirm — it does not do. + **One rule keeps a phase from starting work it cannot finish, and with the counts above it can always be honoured.** *No Store operation begins without at least its own 30 s remaining in its phase.* Because @@ -3236,7 +3268,7 @@ carried: it described three outcomes and returned none of them. | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes**, for the same reason: there is no coordinator, and there may be a transaction | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No | - | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused | `unsettled`, with no cleanup released | **Yes** | + | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | | **A phase-4 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | | **A phase-4 task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 361b92cdf..3c04e6d4d 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -430,7 +430,7 @@ the second loop this milestone forbids, and it could not admit a durable command on its own authority at all. **A graceful stop has a stated maximum**, because an operator configuring a -service manager needs one, and it is the **sum of seven bounded phases** rather +service manager needs one, and it is the **sum of eight bounded phases** rather than one clock that has to cover everything: five seconds for the admission cut — which is two phases, because closing admissions is instant and waiting for what was already admitted is not: five seconds for the close and three @@ -832,10 +832,12 @@ lease — and the companion's rejoin order says where each part goes. edits — the app-server module and its three tests, the protocol module and its two suites, the Node client, and five documents under `docs/developer/` and `docs/operator/` — plus a **new** `CHANGELOG` entry rather than an edit - to the `0.1.0` one, which stays true. Fifteen files carry the string today; - the two the rename does not edit are that `CHANGELOG` entry and ADR - 0032-technical, which carries it inside this very set and has already been - changed here — with generation 1's schema + to the `0.1.0` one, which stays true. **Seventeen** files carry the string today; + the four the rename does not edit are that `CHANGELOG` entry and the three + carriers inside this planning set — ADR 0032-technical, this file and its + companion — each of which carries the retired name only in the passage + explaining why it is retired, and each changed by the milestone's own + planning work — with generation 1's schema digest recomputed and re-pinned as part of it, and its two manifest file digests left alone, because those manifests already carry the new name. Then the daemon's side: the listener, its owner-only peer check and path bound, the startup ordering From ad6b1aa1528ae0ad68fac132539d51f4969073ec Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:03:00 -0700 Subject: [PATCH 148/585] plan(M5): adversarial pass over the fourth round Class 7, stale vocabulary: widening the fence to every enumerated session left three places describing the old scope -- the `fences` key gloss, the `:not_needed` definition in the per-call rule, and quiesce's part 3, which said core "fences and terminates every unsettled coordinator". Terminating and fencing are now stated as two different sets on purpose: only an unsettled coordinator needs ending, and every enumerated session needs its epoch moved. Class 7 again, in the operator obligation: it said five of the seven fixed terms count the Store's ceiling and the other two are chosen, which omits phase 5 -- the coordinator's own shutdown value, neither a Store count nor a number this plan picked. Four, one and two. Class 12, boundary rule: A3 puts a pid on an installed attachment, and the vision fences PIDs out of durable and public or executor contracts. The dispatcher's `state.attachments` is none of those -- it is runtime-local process state, exactly as the `caller_monitor` it already holds on a pending scan is (`event_dispatcher.ex:186-192`) -- and nothing about the pid is journaled, sent on the wire, put in a snapshot or handed to an executor. Said, rather than left for a reviewer to work out. Class 33, derived numbers need executed counts: checked that every derived bound in the set now has one. 1b at ten, phase 2 at four, phase 4 at three, and the two history-paged kinds at fixed sizes. Phases 1a and 6 are chosen numbers with nothing to count, phase 5 is a child specification's value, and phase 7 is one call. --- ...tachment-residency-and-replay-technical.md | 8 ++++++ docs/plans/M5-technical.md | 26 ++++++++++++------- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index bac14f866..826ddfa49 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -231,6 +231,14 @@ attachment to drop. Holding both on the attachment makes the `DOWN` lookup a map lookup rather than a scan, and makes the replacement scope a filter on a field that exists. One addition, two uses. +**A pid on an attachment crosses no boundary the vision fences.** The rule is +about durable and public or executor contracts; the dispatcher's +`state.attachments` is neither — it is runtime-local process state, exactly as +the `caller_monitor` it already holds on a pending scan is +(`event_dispatcher.ex:186-192`). Nothing about the attachment's pid is +journaled, sent on the wire, put in a snapshot or handed to an executor, and +the snapshot and `attached` records a client receives are unchanged. + - **Generation 1 is behaviour-identical**, which is what ADR 0023 requires and what this milestone promises for the foreground server: that host maps one connection to one attachment, so its supersession only ever fired behind a diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 3e28a3ff9..98e20b365 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -299,8 +299,9 @@ reviewer can check against this sentence at closure. admission, `budget_ms` for cancellation, 90 s for the fence, 5 s for coordinator termination, 5 s for daemon teardown and 30 s for the Store — together with the sentence that keeps the number from being read as a - duration: **five** of the seven fixed terms count the Store's - thirty-second ceiling for a wedged filesystem — and the other two, the five + duration: **four** of the seven fixed terms — 1b, 2, 4 and 7 — count the + Store's thirty-second ceiling for a wedged filesystem, **one** is the + coordinator's own shutdown value, and the remaining **two**, the five seconds for closing admissions and the five for the teardown, are this plan's own chosen numbers, which the page says rather than implying every term is derived — and an ordinary stop finishes in milliseconds — @@ -2433,10 +2434,12 @@ circular.** That revision said a fence with four seconds left is not attempted and "the session is reported `fence: :not_needed` if the head already moved and `:unknown` otherwise" — but deciding whether the head moved *is* a Store read, which is the very thing the rule has just refused. There is no way to -take that branch. `:not_needed` now means one thing only, decided without -reading anything: **quiesce does not fence a session it reports `settled`**, -its own work having already ended. Unsettled and absent sessions are fenced, -and their entry is `:committed`, `:superseded` or `:unknown`. +take that branch. `:not_needed` now means one thing only, decided from the +`Control` entry without reading the Store: **a session for which no +coordinator ever existed in this runtime**, where there is nothing that could +write. Every other enumerated session is fenced — settled, unsettled and +absent alike, for the reason phase 4 gives — and its entry is `:committed`, +`:superseded` or `{:unknown, …}`. **Phase 6 stops the lease owners as a collective sweep, not one at a time.** Up to 512 of them exist, and stopping them in sequence inside five seconds was @@ -2883,7 +2886,7 @@ can hold. `budget_ms` is the drain budget core derived and used. `drain_id` is the label this drain reports, and `fences` is what the fence below actually did for each session it touched — `:committed` where the epoch moved, `:superseded` where the one transaction that could still linearize won the -race first, `:not_needed` where the session settled and needed no fence, and +race first, `:not_needed` where no coordinator ever existed for the session so nothing could write for it, and `{:unknown, head}` where the Store could not say, **carrying the head the fence was built from**, because that head is the only thing a successor can discriminate on. **Without `fences` a fence's failure is @@ -3025,9 +3028,12 @@ carried: it described three outcomes and returned none of them. at the price of a one-way root. 3. **A Store-linearized fence at the deadline, because terminating a - coordinator is not one.** When the budget is spent, core fences and - terminates every unsettled coordinator and waits for its `DOWN` before - returning. An earlier revision stopped there and claimed nothing could be + coordinator is not one.** When the budget is spent, core terminates every + **unsettled** coordinator and waits for its `DOWN`, and then fences **every + session it enumerated** — settled, unsettled and absent alike — before + returning. Terminating and fencing are two different sets on purpose: only + an unsettled coordinator needs ending, and every session needs its epoch + moved, for the reason the fence table gives. An earlier revision stopped there and claimed nothing could be appended for that session afterwards. **That claim was false**, and the reason is worth stating because it is the general shape of this whole class of bug: a coordinator commits through a *synchronous* call — From 213ae6879f7c7a69be48755c88033064b34c6762 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:18:34 -0700 Subject: [PATCH 149/585] plan(M5): admit only into ready, and terminate before fencing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P0-1. "The deepest callback is three" was false in both directions, and the callback it described was the acquisition one: `handle_continue(:acquire_owner, …)` (`session_coordinator.ex:378`) runs `advance_acquisition/1` (`:1142-1145`) into `discover_and_advance_owner/1` (`:1186-1203`), `transact_owner/1` (`:1362-1395`, a direct `OwnerLane.transact` at `:1363` with no retry) and `recover_committed_owner/1` (`:1397-1426`) without returning -- three paging loops (`:1303`, `:1399`, `:1400`), a status query, a head read and a commit, re-enterable up to `@max_historical_attempts` 1,024 (`:83`). That is not three calls; it is unbounded. It is also not what an admission waits behind. Quiesce admits an abort **only into a session whose `Control` entry is `:active`**, which `Control` writes at the instant the owner is ready and not before (`control.ex:575-591`: `:acquiring` until `owner_ready` sets `status: :active` at `:579` and replies at `:590`). A session still acquiring has no ready coordinator and no active run, so there is nothing to abort: it skips phases 2 and 3 and meets 4 and 5 like any other, terminated then fenced -- the ordinary outcome of 1b proceeding at its bound. So the wait-behind is the deepest **ready** callback, and I traced the module rather than reasoning about it. Every adapter call it makes is at one of nine sites. Six are acquisition-only (`:1214`, `:1242`, `:1265`, `:1325`, `:1338`, `:1363`). The two paging helpers (`:7077`, `:7088`) have no caller outside `discover_prior_tx_id/1` (`:1303`) and `recover_committed_owner/1` (`:1399-1400`), both acquisition -- so **no ready callback pages**. The ninth is `resolve_transaction/2` (`:1761-1762`), which every ready commit goes through, via `apply_transaction/3` (`:1702`) or `commit_internal_result/2` (`:6423`): one call, or two on `commit_unknown`. And **no ready callback commits twice** -- each of the thirteen commit sites is in its own function, and a committing callback ends by sending itself `:advance_work` (`:1720`) rather than continuing, so any further commit is a later callback the admission is no longer behind. Maximum over the ready callbacks: **two**. Phase 2 is three, **90 s**. P0-2. The fence's no-retry premise is "the coordinator is dead", and the previous revision terminated only the **unsettled** coordinators while fencing every session. For a settled session that premise was simply false: its coordinator was alive and could begin a transaction between the fence's head read and its advance, which is the one window the argument assumes cannot produce a second writer. Termination now covers **every** enumerated coordinator and runs **before** any fence. P0-3. That splits into two phases and they are renumbered: **4 is termination** (5 s, concurrent, coordinators do not trap) and **5 is the fence** (90 s). Table, mapping paragraph, enforcer list, limits rows, classification rows, witnesses, Outcome 1 and M5.md all follow. **Recomputed sum: 5 + 300 + 90 + `budget_ms` + 5 + 90 + 5 + 30 = `budget_ms` + 525 s.** P2-5. The phase-2 correction is applied in the lifecycle derivation and in the limits table, and the executed-count witness now constructs a **ready** coordinator's deepest callback, with a second case asserting no abort is admitted into an `:acquiring` entry. --- docs/plans/M5-technical.md | 189 +++++++++++++++++++++++++------------ docs/plans/M5.md | 21 +++-- 2 files changed, 141 insertions(+), 69 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 98e20b365..3de736a51 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only for an entry that never had a coordinator — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline fencing and terminating every coordinator that did not settle before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only for an entry that never had a coordinator — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -294,10 +294,10 @@ reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop as the sum of the eight phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 555 s**, being 5 s for closing admissions, 300 s for - settling what was already admitted, 120 s for abort - admission, `budget_ms` for cancellation, 90 s for the fence, 5 s for - coordinator termination, 5 s for daemon teardown and 30 s for the Store — + **`budget_ms` + 525 s**, being 5 s for closing admissions, 300 s for + settling what was already admitted, 90 s for abort + admission, `budget_ms` for cancellation, 5 s for coordinator termination, + 90 s for the fence, 5 s for daemon teardown and 30 s for the Store — together with the sentence that keeps the number from being read as a duration: **four** of the seven fixed terms — 1b, 2, 4 and 7 — count the Store's thirty-second ceiling for a wedged filesystem, **one** is the @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind an in-flight callback spends four store calls in phase 2`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a ready coordinator's in-flight callback spends three store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -390,8 +390,8 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | --- | --- | --- | --- | --- | | Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | | The two history-paged kinds, at **fixed** sizes, so the claim that they have no constant is itself checked | `session.attach` over an empty session asserting **1**, and over an eight-event session asserting **2**; `session.resume` of a **twelve-record, eight-event** session asserting **11**, in the traced order, including **two** `transact` calls — the staged owner attempt and the advance | `apps/loopex/test/runtime_quiesce_test.exs` | `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls` | fast | -| Phase 2, four calls | A drained abort admitted behind the **deepest callback**, constructed rather than waited for: the coordinator is made to run a commit that answers `commit_unknown` once — two calls — and to load records in that same callback, and the drained abort is admitted behind it. Asserts **four**, and asserts that the three of them belonged to **one** callback, which is what makes the unit the callback rather than the call | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind an in-flight callback spends four store calls in phase 2` | fast | -| Phase 4, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | +| Phase 2, three calls | A drained abort admitted behind the deepest callback a **ready** coordinator can be running, constructed rather than waited for: that coordinator is made to run a commit which answers `commit_unknown` once — two calls — and the drained abort is admitted behind it. Asserts **three**, and asserts that the two of them belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it** | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a ready coordinator's in-flight callback spends three store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead` | fast | +| Phase 5, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | All three are **core** witnesses, because all three paths are core's: the daemon contributes no Store call of its own to any of them. A case that @@ -2243,15 +2243,15 @@ that already exists somewhere, and the operator maximum is the sum: | --- | --- | --- | --- | | 1a | **Close admissions** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement of a **state change**, not of any work: the relay sets a flag, refuses everything after it, and answers. It has nothing to finish, so this bound measures the relay's own responsiveness and nothing else; a relay that does not answer inside it is a relay the daemon has lost, and the stop becomes the `relay_lost` fail-stop | | 1b | **Settle the admitted** | **300 s** — **ten** Store calls deep, the deepest ticket kind, counted from a traced run rather than from the code; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | -| 2 | **Abort admission** | **120 s** — **four** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** the coordinator is already running, which is up to three calls, and then makes its own, which is one | +| 2 | **Abort admission** | **90 s** — **three** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** a **ready** coordinator is already running, which is at most two calls, and then makes its own, which is one | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | -| 4 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | -| 5 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across the unsettled coordinators | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | +| 4 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across **every** enumerated coordinator | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | +| 5 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | | 6 | **Daemon teardown** | **5 s** | One of this plan's two chosen numbers, covering the notice, the closes, the lease owners, the relay, **the runtime tree** and the edges. The runtime stop is attempted with what remains and killed at the bound; its trapping descendants unwind afterwards on their own clock, which the daemon does not wait for | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 5 s + 300 s + 120 s + `budget_ms` + 90 s + 5 s + -> 5 s + 30 s = `budget_ms` + 555 s**, and `budget_ms` is the one term an +> **Maximum graceful stop = 5 s + 300 s + 90 s + `budget_ms` + 5 s + 90 s + +> 5 s + 30 s = `budget_ms` + 525 s**, and `budget_ms` is the one term an > operator cannot compute in advance. **That is a worst case nobody approaches, and saying so is part of stating @@ -2321,25 +2321,62 @@ are these: that the `:acquiring` row in the classification table is an ordinary outcome rather than a remote one. An operator whose daemon is stopping with resumes in flight should expect the stop to reach 1b's bound and go on. -- **Phase 2 is four, and the unit that blocks is the callback rather than the - call.** The abort admission goes to a **live coordinator**, and - `SessionCoordinator.command/3` is a `GenServer` call +- **Phase 2 is three, and the unit that blocks is the callback rather than the + call — of a coordinator that is *ready*.** The abort admission goes to a + coordinator through `SessionCoordinator.command/3`, a `GenServer` call (`session_coordinator.ex:146-149`): what it waits behind is not one Store transaction but **whatever callback that coordinator is currently running**, - to completion. A callback can make more than one adapter call. The deepest - one traced makes a **commit** — `resolve_transaction/2`, which re-presents - once on `commit_unknown` (`:1752-1768`), so two calls — and then **a records - load in the same callback**, the shape the acquisition path shows plainly - where `transact_owner/1`'s commit at `:1363` runs on into - `recover_committed_owner/1`'s loads at `:1397-1400` without returning. - Three, and then the drain's own admission, which is **one** because it does - not retry — see the non-retrying commit below. **Four, in sequence.** - - An earlier revision counted two and then three, both times by counting Store - calls where the thing that blocks is a callback. It is the same error the - create recount made from the other direction: a count taken from the shape - of the code rather than from a run of it. -- **Phase 4 is three at worst.** A head read, then the `advance_owner`, then, + to completion. A callback can make more than one adapter call, so the + question is which callbacks the admission can actually meet. + + **It can only meet a ready coordinator's, and that is a rule rather than an + observation.** Quiesce admits an abort **only into a session whose `Control` + entry is `:active`**, which `Control` writes at the instant the owner is + ready and not before (`control.ex:575-591`: the entry is `:acquiring` until + `owner_ready` replaces it with `status: :active` at `:579` and replies to the + waiting caller at `:590`). A session still acquiring has no ready + coordinator, no active run and therefore **nothing to abort**: quiesce + admits nothing for it, and it is terminated and fenced exactly as an + unsettled session is. That is the ordinary outcome of phase 1b proceeding at + its bound, not an exception to anything — the `:acquiring` row in the + classification table is where it lands. + + **That matters because the acquisition callback is enormous and the ready + ones are not.** `handle_continue(:acquire_owner, …)` (`:378`) runs + `advance_acquisition/1` (`:1142-1145`) into `discover_and_advance_owner/1` + (`:1186-1203`), `transact_owner/1` (`:1362-1395`) and + `recover_committed_owner/1` (`:1397-1426`) **without returning**: three + paging loops (`:1303`, `:1399`, `:1400`, each `load_pages/4` at + `:7090-7114`, `@page_size 1_024` at `:49`), a `transaction_status`, an + `ownership_head` and a commit, and it may re-enter itself up to + `@max_historical_attempts` — **1,024** (`:83`). An earlier revision took + *that* callback as phase 2's wait-behind and called it three calls, which + under-counted it by an unbounded factor while over-counting what phase 2 + actually waits for. Both errors are fixed by admitting only into `:active`. + + **The ready coordinator's callbacks, traced.** Every adapter call this + module makes is at one of nine sites, and they divide cleanly: + + | Site | Callback | On the ready path? | + | --- | --- | --- | + | `transaction_status` `:1214`, `OwnerLane.transact` `:1242`, `runtime_command` `:1265`, `transaction_status` `:1325`, `ownership_head` `:1338`, `OwnerLane.transact` `:1363` | acquisition only | **no** | + | `load_records` `:7077`, `load_events` `:7088` | reached only from `discover_prior_tx_id/1` (`:1303`) and `recover_committed_owner/1` (`:1399-1400`) | **no** | + | `OwnerLane.transact` `:1761-1762`, inside `resolve_transaction/2` | every ready commit, through `apply_transaction/3` (`:1702`) or `commit_internal_result/2` (`:6423`) | **yes** | + + So a ready callback makes **one commit and nothing else**, and that commit + is **one adapter call, or two** where `resolve_transaction/2` re-presents on + `commit_unknown` (`:1752-1768`). **No ready callback pages**, the two paging + helpers having no caller outside acquisition. And **no ready callback + commits twice**: each of the thirteen commit sites sits in its own function + and each callback reaches one of them, because a committing callback ends by + *sending itself* `:advance_work` (`:1720`) rather than continuing — so + scheduling and any further commit happen in a **later** callback, which the + admission is no longer behind. + + **Maximum over the ready callbacks: two.** Plus the drain's own admission, + which is **one** because it does not retry — see the non-retrying commit + below. **Three, in sequence.** +- **Phase 5 is three at worst.** A head read, then the `advance_owner`, then, only where that answers `commit_unknown`, **one** `transaction_status` query. - **And the drain retries nothing, which is a change to the coordinator rather than a statement about it.** Core's ordinary commit path retries a @@ -2364,7 +2401,8 @@ below is what the daemon's owner *does*; the phases are what each part of it is *bounded by*. Phases 1a and 1b are step 1: 1a is the owner's call to the relay, 1b is the owner's wait afterwards. **Phases 2 to 5 are inside `quiesce/1`** — they are core's to enforce, because core owns the -admission, the cancellation, the fence and the coordinator, and the daemon +admission, the cancellation, the coordinator's termination and the fence, and +the daemon passes no deadline in — and together they are step 2. Of the four, only phase 3's actual value is returned, as `budget_ms`; the other three are fixed numbers an operator adds to it. Phase 6 begins the instant `quiesce/1` returns @@ -2373,11 +2411,12 @@ Store stop at the end of step 6. Nothing is bounded twice and nothing is bounded by nobody. **Who enforces a phase, since a bound with no enforcer is a wish.** Phases 2, -4 and 5 are core's, and none of them can be bounded by the call that does the -work: a coordinator's `command/3` waits `:infinity` by design +3, 4 and 5 are core's, and the admission and the fence cannot be bounded by +the call that does the work: a coordinator's `command/3` waits `:infinity` by design (`session_coordinator.ex:146-149`), and must, because a timeout there is not -evidence of anything. So quiesce runs **each session's admission and each -session's fence in its own task**, and bounds the task rather than the call: +evidence of anything. So quiesce runs **each session's admission (phase 2) and each +session's fence (phase 5) in its own task**, and bounds the task rather than +the call: `Task.async/1` per session, one `Task.yield/2` against what remains of the phase's absolute deadline, then `Task.shutdown/2` for whatever has not answered. That is the ordinary bounded-task idiom, it needs no new mechanism, @@ -2390,11 +2429,11 @@ below carries both rows: - **a phase-2 admission that does not answer** leaves the session's abort neither known-committed nor known-refused, which is the ambiguous case this section already handles: **no cleanup is released for it and it is fenced**; -- **a phase-4 fence that does not answer** is exactly a fence whose outcome +- **a phase-5 fence that does not answer** is exactly a fence whose outcome the drain cannot read, so it is reported **`{:unknown, head}`** and the domain stays fenced — the same disposition a `commit_unknown` gets, reached by a different route; -- **phase 5 needs no task**, being `Supervisor`-shaped already: terminating a +- **phase 4 needs no task**, being `Supervisor`-shaped already: terminating a coordinator is bounded by the `shutdown: 5_000` its own child specification carries (`session_coordinator.ex:134-142`), which is the enforcer. @@ -2438,7 +2477,7 @@ take that branch. `:not_needed` now means one thing only, decided from the `Control` entry without reading the Store: **a session for which no coordinator ever existed in this runtime**, where there is nothing that could write. Every other enumerated session is fenced — settled, unsettled and -absent alike, for the reason phase 4 gives — and its entry is `:committed`, +absent alike, for the reason phase 5 gives — and its entry is `:committed`, `:superseded` or `{:unknown, …}`. **Phase 6 stops the lease owners as a collective sweep, not one at a time.** @@ -2534,7 +2573,8 @@ that is affordable: by the time step 5 runs, every coordinator quiesce could not settle has already been fenced and terminated inside core. It is recorded in the limits table with that rationale. -**Phase 6's deadline starts when phase 5 ends**, and it covers every +**Phase 6's deadline starts when phase 5 ends**, which is when `quiesce/1` +returns, and it covers every remaining non-Store action: the stop records, the connection closes, the listener close, and every stop from the lease owners through the registry. Every helper under it is given `remaining(teardown_deadline)` and nothing @@ -2830,7 +2870,7 @@ the owner fixes. Store and fails as it would after a VM death… a refusal, never a write", which is false for the whole of phase 7: the Store is not stopped yet, and a straggler's `session_commit` in that window would be an ordinary, - acceptable transaction. It is refused because **phase 4 has already moved + acceptable transaction. It is refused because **phase 5 has already moved that session's owner epoch** — every enumerated session's, settled ones included, for exactly this reason — so the adapter answers `:stale_owner_epoch` (`state.ex:548-551`). The claim survives with a @@ -3027,13 +3067,30 @@ carried: it described three outcomes and returned none of them. was available and was declined, because it would buy a journal annotation at the price of a one-way root. -3. **A Store-linearized fence at the deadline, because terminating a - coordinator is not one.** When the budget is spent, core terminates every - **unsettled** coordinator and waits for its `DOWN`, and then fences **every - session it enumerated** — settled, unsettled and absent alike — before - returning. Terminating and fencing are two different sets on purpose: only - an unsettled coordinator needs ending, and every session needs its epoch - moved, for the reason the fence table gives. An earlier revision stopped there and claimed nothing could be +3. **Terminate every coordinator, then fence every session — two phases, in + that order, over the same set.** When the budget is spent, core terminates + **every enumerated coordinator** — settled, unsettled and acquiring alike — + and waits for every `DOWN`; that is **phase 4**, bounded at the 5 s the + coordinator's own child specification carries and concurrent across them, + which is a ceiling nothing approaches because a coordinator does not trap + exits. Only then does it fence **every session it enumerated**, which is + **phase 5**. + + **The order is the whole of it, and an earlier revision had the sets + different.** That revision terminated only the *unsettled* coordinators + while fencing every session, and then justified the fence's no-retry rule + with "the coordinator is dead". For a settled session that was simply not + true: its coordinator was still alive and still able to begin a transaction + **between the fence's head read and its advance**, which is the one window + the whole no-second-attempt argument assumes cannot produce a second + writer. Terminating first makes the premise true for every session the + fence touches, which is what the fence table's reasoning has always + required and now actually gets. + + Terminating a settled session's coordinator costs nothing it was still + doing: it settled. What it buys is that after phase 4 no enumerated session + has a process that could start a transaction at all, so phase 5's fence + races nothing. An earlier revision stopped there and claimed nothing could be appended for that session afterwards. **That claim was false**, and the reason is worth stating because it is the general shape of this whole class of bug: a coordinator commits through a *synchronous* call — @@ -3194,8 +3251,9 @@ carried: it described three outcomes and returned none of them. | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | `{:unknown, head}` | Resolved by **one** `Store.transaction_status/4` query under the same derived `tx_id`; an answer that is still unknown after it leaves the session `unsettled` with `{:unknown, head}` carrying the head the fence read, and the domain fenced | | **No fence is attempted** | No coordinator ever existed for this session in this runtime, so nothing can write for it | `:not_needed` | As the entry left it | - **Phase 4 fences every session quiesce enumerated — settled, unsettled and - absent alike — and an earlier revision fenced only the ones that had not + **Phase 5 fences every session quiesce enumerated — settled, unsettled and + absent alike, every one of them with its coordinator already terminated in + phase 4 — and an earlier revision fenced only the ones that had not settled.** That was a hole, and phase 7 is where it opened. The stop kills the runtime supervisor at phase 6's bound; `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so @@ -3207,7 +3265,7 @@ carried: it described three outcomes and returned none of them. So the fence is not a remedy for sessions that failed to settle; it is what makes the census true for **all** of them. One `advance_owner` per - enumerated session, concurrent, inside the same 90 s — the phase is three + enumerated session, concurrent, inside phase 5's 90 s — the phase is three sequential calls whatever the session count is — and after `quiesce/1` returns, **no transaction for any enumerated session can commit**: the epoch has moved and the adapter refuses it `:stale_owner_epoch` @@ -3229,9 +3287,12 @@ carried: it described three outcomes and returned none of them. reason is the serial lane.** An earlier revision rereads the head and makes one new attempt — which would be right if more transactions could keep arriving, and none can. By the time a fence is attempted the coordinator is - **dead** (quiesce terminates it and waits for the `DOWN` first), and while - it was alive it held **at most one** Store transaction in flight for that - session, because `OwnerLane.transact/2` is a synchronous call the + **dead**, and that holds for **every** session phase 5 fences because + **phase 4 terminates every enumerated coordinator first** and waits for + every `DOWN` — which is the change this premise needed, an earlier revision + having terminated only the unsettled ones while fencing them all. While a + coordinator was alive it held **at most one** Store transaction in flight + for that session, because `OwnerLane.transact/2` is a synchronous call the coordinator makes from its own process and threads the returned lane through its state (`store/owner_lane.ex:83-99`, `session_coordinator.ex:1242`, `:1363`, `:1702`). So at most one transaction can linearize after the @@ -3275,8 +3336,18 @@ carried: it described three outcomes and returned none of them. | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No | | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | - | **A phase-4 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | - | **A phase-4 task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | + | **A phase-5 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | + | **A phase-5 task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | + + **Quiesce admits no abort into an `:acquiring` entry, and that is a rule + rather than an accident of timing.** ADR 0023 admits a cancellation only + for a run, and a session still acquiring has no ready coordinator and no + active run, so there is nothing to abort; `Control` marks an entry + `:active` only when the owner is ready (`control.ex:575-591`). Phase 2 + therefore touches `:active` entries alone — which is also what keeps its + bound honest, the acquisition callback being far deeper than any ready one. + An `:acquiring` session skips phases 2 and 3 entirely and meets phases 4 + and 5 like any other: terminated, then fenced. **`:acquiring` is reachable, and an earlier revision called it unreachable.** That revision's argument was the cut: only `session.create` and @@ -4368,14 +4439,14 @@ line; M5 introduces none of its own. | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | | Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | -| Phase 2, abort admission | a fixed **120 s** — four sequential Store calls at the adapter's own 30 s `@call_timeout`: the three of the deepest **callback** the coordinator may already be running — a commit that re-presents once, then a records load in the same callback — and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1363`, `:1397-1400`, `:1752-1768` | +| Phase 2, abort admission | a fixed **90 s** — three sequential Store calls at the adapter's own 30 s `@call_timeout`: the two of the deepest callback a **ready** coordinator may be running, which is one commit re-presented once, and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. Quiesce admits only into an `:active` entry, so the acquisition callback — which pages and may re-enter itself up to 1,024 times — is never what an admission waits behind | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `control.ex:575-591` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | -| Phase 4, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | -| Phase 5, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`) | Core's existing child specification | +| Phase 4, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`), concurrent across **every** enumerated coordinator; it runs **before** the fence so that fence races no live writer | Core's existing child specification | +| Phase 5, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Maximum fail-stop exit | **35 s** — 5 s for the executor stop and the Store's own fixed 30 s, the only two steps of that path that wait; 5 s on the two store classes, where the Store is already gone | This plan, as the sum of its parts | -| Maximum graceful stop | `budget_ms` + **555 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **525 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 3c04e6d4d..0e8b997f3 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -406,9 +406,10 @@ on the way out, in `daemon.stopping` and on `stderr`, and a journal that says the same thing a third time would have cost a persistent-schema decision for nothing. It then drives what is in flight through the cancellation sequence a coordinator already runs for an abort, under the -bounds core already derives from that session's committed cleanup grace. And at the deadline it **terminates every coordinator that has not settled -and commits a Store-linearized owner-epoch fence for every session it -enumerated — the ones that settled as well as the ones that did not**, +bounds core already derives from that session's committed cleanup grace. And at the deadline it **terminates every coordinator it enumerated — the ones +that settled as well as the ones that did not — and only then commits a +Store-linearized owner-epoch fence for every one of those sessions**, in that +order, so no fence races a live writer; because the runtime is killed at the teardown bound while the Store stays alive for its own phase, so a settled session's straggler could otherwise commit after the census that called it settled; so an older @@ -434,19 +435,19 @@ service manager needs one, and it is the **sum of eight bounded phases** rather than one clock that has to cover everything: five seconds for the admission cut — which is two phases, because closing admissions is instant and waiting for what was already admitted is not: five seconds for the close and three -hundred for the settle, after which the stop proceeds. Then a hundred and -twenty for admitting every session's abort, the drain budget **core -derives and reports** for the cancellation, ninety for the fence, five for -terminating the coordinators that did not settle, five for every non-Store +hundred for the settle, after which the stop proceeds. Then ninety for +admitting every session's abort, the drain budget **core +derives and reports** for the cancellation, five for terminating every coordinator it enumerated, ninety for fencing +every one of those sessions afterwards, five for every non-Store action after the drain — the stop records, the closes, the lease owners, the runtime tree and the edges, the runtime being attempted with what remains and killed at the bound — and thirty for the Store stop that releases the marker. Seven of -the eight are fixed, so the maximum is **`budget_ms` plus 555 seconds** — a +the eight are fixed, so the maximum is **`budget_ms` plus 525 seconds** — a worst case assembled from the store adapter's ceiling for a wedged filesystem, not the cost of an ordinary stop, which finishes in milliseconds. **Five** of the seven are counts of the adapter's own thirty-second call timeout, or the coordinator's own shutdown -value: a phase that makes four Store calls in sequence is bounded at a hundred -and twenty and one that makes ten at three hundred, and the drain retries nothing, which +value: a phase that makes three Store calls in sequence is bounded at ninety +and one that makes ten at three hundred, and the drain retries nothing, which is what keeps those counts finite. The other two — the five seconds for closing admissions and the five for the teardown — are **this plan's own numbers**, chosen rather than derived, and the technical companion says so From 243dd4641e6f82923b5651321d043357b09aae4a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:19:13 -0700 Subject: [PATCH 150/585] plan(M5): record the stale_journal_version asymmetry as core's, not M5's P1-4. The coordinator maps two of the three stale results to `{:error, :superseded_owner}` and marks itself superseded -- `:stale_owner_epoch` and `:stale_owner_incarnation_id` at `session_coordinator.ex:1731-1732` -- while `:stale_journal_version` falls through to the general clause at `:1734-1735`, telling the caller the reason and marking nothing. The drain's guarantee does not pass through that clause, and the reason it does not is what the previous commit just established: every enumerated coordinator is terminated before any fence commits, so no live coordinator can receive a refusal caused by the drain's epoch move. A design that had rested the fence on the coordinator's refusal handling would have been resting it on a gap. Recorded as an observation for core rather than an M5 change, with the argument for which it is. Outside a drain the asymmetry is core's ordinary succession business under ADR 0006, where a stale journal version is a legitimate retry condition rather than proof of supersession -- which may be why the clause reads as it does. M5 changes nothing, and writes the question down so a later change that needs a live coordinator to stand down on that result finds it asked rather than discovering it. --- docs/plans/M5-technical.md | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 3de736a51..06d612284 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -3090,7 +3090,30 @@ carried: it described three outcomes and returned none of them. Terminating a settled session's coordinator costs nothing it was still doing: it settled. What it buys is that after phase 4 no enumerated session has a process that could start a transaction at all, so phase 5's fence - races nothing. An earlier revision stopped there and claimed nothing could be + races nothing. + + **The drain's guarantee rests on that termination and not on how a + coordinator handles a refusal**, which is worth saying because the + coordinator's handling is **incomplete** and a design that leaned on it + would be leaning on a gap. `apply_transaction/3` maps two of the three + stale results to `{:error, :superseded_owner}` and marks the coordinator + superseded so it performs no later run work — `:stale_owner_epoch` and + `:stale_owner_incarnation_id`, at `session_coordinator.ex:1731-1732`. The + third, **`:stale_journal_version`**, falls through to the general clause at + `:1734-1735`: the caller is told the reason, and the coordinator is **not** + marked superseded. + + **That is an observation for core, not an M5 change**, and the argument is + the one P0-2 just supplied. A drain never meets it: every enumerated + coordinator is dead before any fence commits, so no live coordinator can + receive a refusal caused by the drain's epoch move, and the fence's + correctness never passes through that clause. Outside a drain it is core's + ordinary succession business under ADR 0006, where a stale journal version + is a legitimate retry condition rather than proof of supersession — which + may well be why the clause reads as it does. M5 therefore changes nothing + here, and records the asymmetry so that a later change which *does* need a + live coordinator to stand down on `:stale_journal_version` finds the + question already asked rather than discovering it. An earlier revision stopped there and claimed nothing could be appended for that session afterwards. **That claim was false**, and the reason is worth stating because it is the general shape of this whole class of bug: a coordinator commits through a *synchronous* call — From 1935e8e0fd5a504adfc77d05bacf38549c4ef870 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:20:02 -0700 Subject: [PATCH 151/585] plan(M5): adversarial pass over the fifth round Class 7, stale vocabulary, three catches from re-reading the diff against the renumbering: Outcome 1 in M5.md still read "at the deadline fences and terminates every coordinator that did not settle" -- the old order and the old scope, in the one place a reader meets the claim first. It now states termination of every enumerated coordinator, waiting for all of them, and only then the fence. The operator obligation's breakdown said four of the seven fixed terms count the Store's ceiling and named them as 1b, 2, 4 and 7. After the renumbering phase 4 is the coordinator's shutdown value and phase 5 is the fence, so the Store-derived four are 1b, 2, 5 and 7, and phase 4 is the one that is the child specification's number. Step 5 of the shutdown sequence still justified itself with "every coordinator quiesce could not settle was fenced and terminated", which is both the old scope and the old order. Re-verified, per class 33, that no count in the set is now stated without a traced basis: phase 2 at three, phase 1b at ten, phase 5 at three, and the two history-paged kinds at fixed sizes. Phases 1a and 6 are chosen numbers, phase 4 is a child specification's value, phase 7 is one call. Grepped clean for `120 s`, `four store calls`, `555` and the fence-before-termination order. --- docs/plans/M5-technical.md | 13 +++++++------ docs/plans/M5.md | 2 +- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 06d612284..6ae8a523e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -299,9 +299,9 @@ reviewer can check against this sentence at closure. admission, `budget_ms` for cancellation, 5 s for coordinator termination, 90 s for the fence, 5 s for daemon teardown and 30 s for the Store — together with the sentence that keeps the number from being read as a - duration: **four** of the seven fixed terms — 1b, 2, 4 and 7 — count the - Store's thirty-second ceiling for a wedged filesystem, **one** is the - coordinator's own shutdown value, and the remaining **two**, the five + duration: **four** of the seven fixed terms — 1b, 2, 5 and 7 — count the + Store's thirty-second ceiling for a wedged filesystem, **one** — phase 4 — + is the coordinator's own shutdown value, and the remaining **two**, the five seconds for closing admissions and the five for the teardown, are this plan's own chosen numbers, which the page says rather than implying every term is derived — and an ordinary stop finishes in milliseconds — @@ -2726,9 +2726,10 @@ the owner fixes. consumed like any other the owner asks for — a lease owner stopped here closes no controller attachment and produces no `control_owner_lost`, because there is no attachment left to close. -5. **The runtime stops.** After the drain there is little left to end — every - coordinator quiesce could not settle was fenced and terminated inside core - before `quiesce/1` returned — so this step ends the tree rather than the +5. **The runtime stops.** After the drain there is little left to end — + **every** coordinator quiesce enumerated was terminated and then fenced + inside core before `quiesce/1` returned, the settled ones included — so + this step ends the tree rather than the work. The helper calls `Supervisor.stop(runtime_supervisor, :normal, remaining)` on the pid the composition function handed it, where `remaining` is what is left of the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 0e8b997f3..4a0a5b71f 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -69,7 +69,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — the relay answering only when every ticket it holds has **settled**, so a command admitted before the cut has finished inside core before the drain begins and one arriving after it is refused `daemon_stopping` — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline fences and terminates every coordinator that did not settle, waiting for it to be gone before answering — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — the relay answering only when every ticket it holds has **settled**, so a command admitted before the cut has finished inside core before the drain begins and one arriving after it is refused `daemon_stopping` — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline **terminates every coordinator it enumerated — the settled as well as the unsettled — waiting for every one of them to be gone, and only then fences every one of those sessions**, in that order, so no fence races a live writer — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | From 90b63edb55cb1ddf6b4980fcb08d00b33e7a8776 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:33:51 -0700 Subject: [PATCH 152/585] plan(M5): quiesce runs in the caller, because in Control it deadlocks MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit H1. The set placed `quiesce/1` in `Loopex.Runtime.Control`, reached by a blocking `control_call`, and justified it with "there is nowhere else this could live". It could not live there. `Control` is on the commit path of every coordinator in the runtime. A commit ends in `Control.post_commit/5`, a `GenServer.call(control, …, :infinity)` (`control.ex:182-209`, the call at `:199-203`, made from `session_coordinator.ex:1710` and `:6431`), and scheduling asks `Control.current_owner/3`, another `:infinity` call (`control.ex:92-98`, at `:1778`). A drain executing inside `Control`'s process would hold the very mailbox every abort it had just admitted must reach in order to commit: each coordinator blocks in `post_commit` forever, every admission times out as ambiguous, nothing settles. Not a race -- a certainty, on the first session with work to drain. `quiesce/1` is therefore a function of `Loopex.Runtime` that executes in the **caller's** process, the daemon's owner, which sits on no commit path. It asks `Control` for exactly one thing, once: the enumeration, with each entry's status, coordinator pid and owner -- the owner being what the per-session calls need to identify themselves as current. Everything else the drain does is per-session calls its own tasks make directly to coordinators and to the Store. `Control` keeps serving `post_commit` and `current_owner` throughout. The witness is the case the old design hangs on: a commit made by a coordinator **during** phase 2 completes, its `post_commit` answered while the drain is running, and its session settles. --- docs/plans/M5-technical.md | 49 ++++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 6ae8a523e..6ca03c812 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a ready coordinator's in-flight callback spends three store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a ready coordinator's in-flight callback spends three store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -3401,18 +3401,47 @@ carried: it described three outcomes and returned none of them. is therefore distinguishable from one in `settled` exactly where the difference is actionable, and nowhere it would be noise. -**Quiesce is not called through the facade's default timeout.** `control_call/3` +**Quiesce's reads are not made through the facade's default timeout.** `control_call/3` and `dispatcher_call/3` both default to `5_000` (`runtime.ex:470`, `:478`), and a drain whose budget is derived from a session's cleanup grace will routinely exceed that — a five-second reply timeout would abandon a drain that was -working and leave the daemon tearing down underneath it. `quiesce/1` therefore -calls with an explicit `:infinity` reply timeout and carries its **own** -deadline as data: the budget is enforced inside core, where the work is, and -the caller waits for the answer rather than racing it. - -`Loopex.Runtime.Control` already holds every active session and its -coordinator pid, so there is nowhere else this could live and nothing to -enumerate that core does not already have. +working and leave the daemon tearing down underneath it. The reads `quiesce/1` +makes into `Control` therefore carry explicit bounds rather than the default, +and the drain's own budget is data it holds rather than a reply timeout. + +**`quiesce/1` runs in its caller's process, and putting it inside `Control` +would deadlock the runtime.** An earlier revision said `Control` "already +holds every active session and its coordinator pid, so there is nowhere else +this could live". It could not live there. `Control` is on the commit path of +every coordinator in the runtime: a commit ends in `Control.post_commit/5`, +which is a `GenServer.call(control, …, :infinity)` +(`control.ex:182-209`, the call at `:199-203`, made at +`session_coordinator.ex:1710` and `:6431`), and scheduling asks +`Control.current_owner/3`, another `:infinity` call (`control.ex:92-98`, at +`session_coordinator.ex:1778`). A drain executing **inside** `Control`'s +process would therefore hold the mailbox that every abort it just admitted +must reach to commit: each coordinator would block in `post_commit` forever, +every admission would time out as ambiguous, and nothing would ever settle. +Not a race — a certainty, on the first session with work to drain. + +So `quiesce/1` is a function of **`Loopex.Runtime`** that executes in the +**caller's** process — the daemon's owner, which sits on no commit path — +and `Control` keeps serving `post_commit` and `current_owner` throughout. +What it asks `Control` for is exactly two bounded reads: + +- **the enumeration**, once: every session entry with its status, its + coordinator pid and its **owner**, which is what the per-session calls need + to identify themselves as the current owner; +- **nothing else.** The drain's work — admitting, cancelling, terminating, + fencing and reading status — is per-session calls the caller's own tasks + make **directly to coordinators and to the Store**, never through + `Control`. + +Neither read blocks `Control` for longer than a map projection, so a +coordinator committing in the middle of phase 2 is served as usual. That is +the witness: **a commit made by a coordinator during phase 2 completes** — its +`post_commit` answered while the drain is running — **and its session +settles**. Under the design this replaces, that case hangs. **Why core rather than the daemon.** The daemon cannot do this without reaching into coordinator internals, which the dependency direction forbids, From 424d785c533d80973b0c47a9179eccecca53829a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:35:24 -0700 Subject: [PATCH 153/585] plan(M5): a ready callback commits twice, so phase 2 is five calls MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit H2/H3. "No ready callback commits twice" rested on an argument true of one function: that a committing callback ends by sending itself `:advance_work` and so cannot continue. That send sits in `apply_transaction/3` (`:1720`) and in twelve other places (`:465`, `:627`, `:1425`, `:1996`, `:2237`, `:2249`, `:4013`, `:4051`, `:4078`, `:5894`, `:6304`, `:6775`), and reaching one is not the same as reaching it before a second commit. There are fifteen paths into `commit_internal_result/2`: the thirteen `commit_internal/2` sites and the two into `retain_terminal_operation_fact/2` (`:4062`, `:6381`). The traced double is `complete_cleanup/3` (`:5045-5068`), which commits the executor fact through `settle_executor_work/2` → `put_executor_fact/3` → `retain_terminal_operation_fact/2`, and then the run terminal through `finish_settled_cleanup/4` → `finish_cleanup/4` → `commit_terminal/4` (`:2558-2563`) -- both in one callback with no return in between. **Phase 2 is five calls, 150 s**, and the sum is **`budget_ms` + 585 s**. Never three, and that needed an argument rather than a count. The only candidate third is `settle_owned_operation/3`'s `:unconfirmed` clause (`:5399-5400`), committing a tool result at `:5437` between the two. It cannot co-occur with the executor fact, and the code says why in its own comment at `:5396-5398`: a run whose executor answered and whose fact committed has already left `effect_dispatched`, so that commit is a no-op there, and a `:cleaned` cleanup has nothing unproved to record. Mutually exclusive by the run's stage, so the callback commits the terminal plus exactly one of them. The bound now rests on two claims, both stated so a later change fails against them rather than around them: admit only into `:active`, and no ready callback reaches `commit_internal_result/2` more than twice. M3. The phase-2 witness constructs the real cleanup callback rather than a synthetic single-commit one, and a third case pins the ceiling itself -- the `:unconfirmed` branch asserted to commit twice, not three times. L2. The nine-site table enumerates calls this module makes, where the bound needs calls made in the coordinator's process. Stated, with the executed count named as what makes the claim true and the table as what makes it checkable. --- docs/plans/M5-technical.md | 91 +++++++++++++++++++++++++++++--------- docs/plans/M5.md | 10 ++--- 2 files changed, 74 insertions(+), 27 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 6ca03c812..50ef5262c 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -294,8 +294,8 @@ reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop as the sum of the eight phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 525 s**, being 5 s for closing admissions, 300 s for - settling what was already admitted, 90 s for abort + **`budget_ms` + 585 s**, being 5 s for closing admissions, 300 s for + settling what was already admitted, 150 s for abort admission, `budget_ms` for cancellation, 5 s for coordinator termination, 90 s for the fence, 5 s for daemon teardown and 30 s for the Store — together with the sentence that keeps the number from being read as a @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a ready coordinator's in-flight callback spends three store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `the cleanup callback commits at most twice on either branch`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -390,7 +390,7 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | --- | --- | --- | --- | --- | | Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | | The two history-paged kinds, at **fixed** sizes, so the claim that they have no constant is itself checked | `session.attach` over an empty session asserting **1**, and over an eight-event session asserting **2**; `session.resume` of a **twelve-record, eight-event** session asserting **11**, in the traced order, including **two** `transact` calls — the staged owner attempt and the advance | `apps/loopex/test/runtime_quiesce_test.exs` | `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls` | fast | -| Phase 2, three calls | A drained abort admitted behind the deepest callback a **ready** coordinator can be running, constructed rather than waited for: that coordinator is made to run a commit which answers `commit_unknown` once — two calls — and the drained abort is admitted behind it. Asserts **three**, and asserts that the two of them belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it** | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a ready coordinator's in-flight callback spends three store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead` | fast | +| Phase 2, five calls | A drained abort admitted behind **the real deepest callback**, not a synthetic one: a run is driven to `complete_cleanup/3` so that the coordinator commits the executor fact and then the run terminal in **one** callback, each commit made to answer `commit_unknown` once — four calls — and the drained abort is admitted behind it. Asserts **five**, and asserts the four belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. A third pins the ceiling itself: the same cleanup callback driven down its `:unconfirmed` branch is asserted to commit **twice, not three times**, the executor fact and the unproved tool result being mutually exclusive | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the cleanup callback commits at most twice on either branch` | fast | | Phase 5, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | All three are **core** witnesses, because all three paths are core's: the @@ -2243,15 +2243,15 @@ that already exists somewhere, and the operator maximum is the sum: | --- | --- | --- | --- | | 1a | **Close admissions** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement of a **state change**, not of any work: the relay sets a flag, refuses everything after it, and answers. It has nothing to finish, so this bound measures the relay's own responsiveness and nothing else; a relay that does not answer inside it is a relay the daemon has lost, and the stop becomes the `relay_lost` fail-stop | | 1b | **Settle the admitted** | **300 s** — **ten** Store calls deep, the deepest ticket kind, counted from a traced run rather than from the code; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | -| 2 | **Abort admission** | **90 s** — **three** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** a **ready** coordinator is already running, which is at most two calls, and then makes its own, which is one | +| 2 | **Abort admission** | **150 s** — **five** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** a **ready** coordinator is already running, which is at most two commits and so four calls, and then makes its own, which is one | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across **every** enumerated coordinator | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | | 5 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | | 6 | **Daemon teardown** | **5 s** | One of this plan's two chosen numbers, covering the notice, the closes, the lease owners, the relay, **the runtime tree** and the edges. The runtime stop is attempted with what remains and killed at the bound; its trapping descendants unwind afterwards on their own clock, which the daemon does not wait for | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 5 s + 300 s + 90 s + `budget_ms` + 5 s + 90 s + -> 5 s + 30 s = `budget_ms` + 525 s**, and `budget_ms` is the one term an +> **Maximum graceful stop = 5 s + 300 s + 150 s + `budget_ms` + 5 s + 90 s + +> 5 s + 30 s = `budget_ms` + 585 s**, and `budget_ms` is the one term an > operator cannot compute in advance. **That is a worst case nobody approaches, and saying so is part of stating @@ -2357,25 +2357,72 @@ are these: **The ready coordinator's callbacks, traced.** Every adapter call this module makes is at one of nine sites, and they divide cleanly: + **The enumeration below is over the calls this module makes; the bound needs + the calls made in the coordinator's *process*.** Those differ if a + coordinator callback calls out to something that reaches the Store itself. + The table is what makes the claim checkable by reading; what makes it true + is the **executed count**, and the phase-2 witness below is where it is + measured rather than argued. + | Site | Callback | On the ready path? | | --- | --- | --- | | `transaction_status` `:1214`, `OwnerLane.transact` `:1242`, `runtime_command` `:1265`, `transaction_status` `:1325`, `ownership_head` `:1338`, `OwnerLane.transact` `:1363` | acquisition only | **no** | | `load_records` `:7077`, `load_events` `:7088` | reached only from `discover_prior_tx_id/1` (`:1303`) and `recover_committed_owner/1` (`:1399-1400`) | **no** | | `OwnerLane.transact` `:1761-1762`, inside `resolve_transaction/2` | every ready commit, through `apply_transaction/3` (`:1702`) or `commit_internal_result/2` (`:6423`) | **yes** | - So a ready callback makes **one commit and nothing else**, and that commit - is **one adapter call, or two** where `resolve_transaction/2` re-presents on - `commit_unknown` (`:1752-1768`). **No ready callback pages**, the two paging - helpers having no caller outside acquisition. And **no ready callback - commits twice**: each of the thirteen commit sites sits in its own function - and each callback reaches one of them, because a committing callback ends by - *sending itself* `:advance_work` (`:1720`) rather than continuing — so - scheduling and any further commit happen in a **later** callback, which the - admission is no longer behind. - - **Maximum over the ready callbacks: two.** Plus the drain's own admission, - which is **one** because it does not retry — see the non-retrying commit - below. **Three, in sequence.** + So **no ready callback pages**, the two paging helpers having no caller + outside acquisition, and every ready commit is **one adapter call, or two** + where `resolve_transaction/2` re-presents on `commit_unknown` + (`:1752-1768`). + + **A ready callback commits twice, and an earlier revision said once.** That + revision argued that a committing callback ends by sending itself + `:advance_work` and so cannot continue — which is true of + `apply_transaction/3`, where that send sits (`:1720`), and of nothing else: + the module has **thirteen** such sends (`:465`, `:627`, `:1425`, `:1720`, + `:1996`, `:2237`, `:2249`, `:4013`, `:4051`, `:4078`, `:5894`, `:6304`, + `:6775`), and reaching one is not the same as reaching it *before* the + callback's second commit. There are **fifteen** paths into + `commit_internal_result/2`: the thirteen `commit_internal/2` call sites and + the two into `retain_terminal_operation_fact/2` (`:4062`, `:6381`). + + The traced double is the **cleanup-completion** callback, + `complete_cleanup/3` (`:5045-5068`): + + 1. `settle_executor_work/2` (`:5235`) → `put_executor_fact/3` (`:6379-6384`) + → `retain_terminal_operation_fact/2` → `commit_internal_result/2` — + **the executor fact**; + 2. `finish_settled_cleanup/4` (`:5070-5078`) → `finish_cleanup/4` + (`:5080-5090`) → `commit_terminal/4` (`:2558-2563`) → + `commit_internal/2` → `commit_internal_result/2` — **the run terminal**. + + Both inside one callback, with no return in between. + + **And never three, which is the part that needs an argument rather than a + count.** The only candidate third is `settle_owned_operation/3`'s + `:unconfirmed` clause (`:5399-5400`), which commits a tool result through + `commit_owned_operation_unknown/2` (`:5426-5444`, the commit at `:5437`) + between the two above. It cannot co-occur with the first, and the code says + why in its own comment at `:5396-5398`: *"a run whose executor answered and + whose fact committed has already left `effect_dispatched`, so this is a + no-op there, and a `:cleaned` cleanup has nothing unproved to record."* The + two are mutually exclusive by the stage the run is in — either the executor + answered and step 1 committed the fact, or it did not and + `commit_owned_operation_unknown/2` records the unproved result instead — so + the callback commits the run terminal plus **exactly one** of them. Every + other ready path reaches `commit_internal_result/2` once, each of the + fifteen sites sitting in its own function. + + **Maximum over the ready callbacks: two commits, so four adapter calls.** + Plus the drain's own admission, which is **one** because it does not + retry — see the non-retrying commit below. **Five, in sequence.** + + **This bound rests on two claims and not on one**, and both are stated so a + later change fails against them rather than around them: the rule that + quiesce admits only into `:active`, which keeps the acquisition callback out + of the wait; and this enumeration, that no ready callback reaches + `commit_internal_result/2` more than twice. The executed-count witness below + is what holds the second to a number. - **Phase 5 is three at worst.** A head read, then the `advance_owner`, then, only where that answers `commit_unknown`, **one** `transaction_status` query. - **And the drain retries nothing, which is a change to the coordinator rather @@ -4492,14 +4539,14 @@ line; M5 introduces none of its own. | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | | Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | -| Phase 2, abort admission | a fixed **90 s** — three sequential Store calls at the adapter's own 30 s `@call_timeout`: the two of the deepest callback a **ready** coordinator may be running, which is one commit re-presented once, and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. Quiesce admits only into an `:active` entry, so the acquisition callback — which pages and may re-enter itself up to 1,024 times — is never what an admission waits behind | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `control.ex:575-591` | +| Phase 2, abort admission | a fixed **150 s** — five sequential Store calls at the adapter's own 30 s `@call_timeout`: the four of the deepest callback a **ready** coordinator may be running, which is **two** commits each re-presented once, and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. It rests on two claims — quiesce admits only into an `:active` entry, so the acquisition callback is never what an admission waits behind, and no ready callback reaches `commit_internal_result/2` more than twice | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `:5045-5068`, `:5396-5400`, `control.ex:575-591` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | | Phase 4, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`), concurrent across **every** enumerated coordinator; it runs **before** the fence so that fence races no live writer | Core's existing child specification | | Phase 5, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Maximum fail-stop exit | **35 s** — 5 s for the executor stop and the Store's own fixed 30 s, the only two steps of that path that wait; 5 s on the two store classes, where the Store is already gone | This plan, as the sum of its parts | -| Maximum graceful stop | `budget_ms` + **525 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **585 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 4a0a5b71f..f310bef9e 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -435,19 +435,19 @@ service manager needs one, and it is the **sum of eight bounded phases** rather than one clock that has to cover everything: five seconds for the admission cut — which is two phases, because closing admissions is instant and waiting for what was already admitted is not: five seconds for the close and three -hundred for the settle, after which the stop proceeds. Then ninety for -admitting every session's abort, the drain budget **core +hundred for the settle, after which the stop proceeds. Then a hundred and +fifty for admitting every session's abort, the drain budget **core derives and reports** for the cancellation, five for terminating every coordinator it enumerated, ninety for fencing every one of those sessions afterwards, five for every non-Store action after the drain — the stop records, the closes, the lease owners, the runtime tree and the edges, the runtime being attempted with what remains and killed at the bound — and thirty for the Store stop that releases the marker. Seven of -the eight are fixed, so the maximum is **`budget_ms` plus 525 seconds** — a +the eight are fixed, so the maximum is **`budget_ms` plus 585 seconds** — a worst case assembled from the store adapter's ceiling for a wedged filesystem, not the cost of an ordinary stop, which finishes in milliseconds. **Five** of the seven are counts of the adapter's own thirty-second call timeout, or the coordinator's own shutdown -value: a phase that makes three Store calls in sequence is bounded at ninety -and one that makes ten at three hundred, and the drain retries nothing, which +value: a phase that makes five Store calls in sequence is bounded at a hundred +and fifty and one that makes ten at three hundred, and the drain retries nothing, which is what keeps those counts finite. The other two — the five seconds for closing admissions and the five for the teardown — are **this plan's own numbers**, chosen rather than derived, and the technical companion says so From 4168f5aaba0feadd5ae9de23b5069b501661c3a4 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:36:57 -0700 Subject: [PATCH 154/585] plan(M5): settled means the terminal is committed, and it has a surface H4. `settled` was defined as "whether its cancellation finished inside the budget" with no observation point named -- the most consequential of the three lists resting on a word. It also let phase 4 kill a coordinator between its cleanup and its terminal commit and still report the session settled, with no terminal in the journal. A session is `settled` exactly when the run the drain aborted has its **terminal fact committed**, and the surface is one core already serves: the coordinator's `{:session_status, owner}` reply (`session_coordinator.ex:414-442`), carrying `active_run_id` (`:421`) and `pending_work_ids` (`:425-426`) at its committed cursor. A run whose terminal is committed appears in neither, so the two answers that must differ are the aborted run present and the aborted run absent. The owner that call requires is the one quiesce read from `Control`'s enumeration, which is why the enumeration carries it. No core change is needed, which is worth saying after several rounds of adding things. A cancellation that finished without its terminal committed is therefore `unsettled`, never `settled`: terminated, fenced, reconciled. Phase 4 kills no owed write of a session it called settled, because a session is called settled only once the write it owed is in the journal. M1. The disposition for `:acquiring` was right and its reason was false. `owner_ready` is a **cast** (`session_coordinator.ex:1424`) sent after `phase: :ready` (`:1407`) and before `send(self(), :advance_work)` (`:1425`), so a fully ready coordinator -- a resumed one with a recovered active run already advancing -- sits behind an `:acquiring` entry until `Control` consumes it. The rule rests on the implication that holds, `:active` implies ready (`control.ex:575-591`), and the cost is stated: such a run is ended crash-equivalent by termination rather than cancelled under its grace, which is the unsettled disposition reached without guessing at a cast. M2/L1. "The fence races nothing" overstated it. Phase 4 removes every live **writer**; what the fence still races is at most one delivered transaction, the one the serial `OwnerLane` may have handed the Store before its coordinator died, which the stale handling covers. Bounded at one is the claim the no-second-attempt rule needs, and it is what both places now say. M4. Outcome 1 said `quiesce/1` runs "stop phases 2 and 3"; it runs 2 to 5. --- docs/plans/M5-technical.md | 91 +++++++++++++++++++++++++++++++------- 1 file changed, 75 insertions(+), 16 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 50ef5262c..78303a27e 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 and 3 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only for an entry that never had a coordinator — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 to 5 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only for an entry that never had a coordinator — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `the cleanup callback commits at most twice on either branch`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `the cleanup callback commits at most twice on either branch`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -3136,9 +3136,15 @@ carried: it described three outcomes and returned none of them. required and now actually gets. Terminating a settled session's coordinator costs nothing it was still - doing: it settled. What it buys is that after phase 4 no enumerated session - has a process that could start a transaction at all, so phase 5's fence - races nothing. + doing, and "settled" is what makes that true: its terminal is already + committed, which is what the word is defined to mean below. What phase 4 + buys is that no enumerated session still has a **process** that could start + a transaction, so phase 5's fence **races at most one delivered + transaction** — the one the serial `OwnerLane` may have handed the Store + before its coordinator died — which the fence's stale handling already + covers. It does not race nothing, and an earlier revision said it did; what + it races is bounded at one, which is the claim the no-second-attempt rule + needs. **The drain's guarantee rests on that termination and not on how a coordinator handles a refusal**, which is worth saying because the @@ -3401,7 +3407,7 @@ carried: it described three outcomes and returned none of them. | What `Control` holds | Why it can be there | Which list | Fenced? | | --- | --- | --- | --- | - | `:active` with a live coordinator | The ordinary case | `settled` or `unsettled`, by whether its cancellation finished inside the budget | **Yes, either way** — see below | + | `:active` with a live coordinator | The ordinary case | `settled` or `unsettled`, by whether the aborted run's **terminal fact is committed** — see the surface below | **Yes, either way** — see below | | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes**, for the same reason: there is no coordinator, and there may be a transaction | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | @@ -3410,15 +3416,57 @@ carried: it described three outcomes and returned none of them. | **A phase-5 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | | **A phase-5 task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | - **Quiesce admits no abort into an `:acquiring` entry, and that is a rule - rather than an accident of timing.** ADR 0023 admits a cancellation only - for a run, and a session still acquiring has no ready coordinator and no - active run, so there is nothing to abort; `Control` marks an entry - `:active` only when the owner is ready (`control.ex:575-591`). Phase 2 - therefore touches `:active` entries alone — which is also what keeps its - bound honest, the acquisition callback being far deeper than any ready one. - An `:acquiring` session skips phases 2 and 3 entirely and meets phases 4 - and 5 like any other: terminated, then fenced. + **What `settled` means, and where it is read.** An earlier revision defined + it as "whether its cancellation finished inside the budget" and named no + observation point, which left the most consequential of the three lists + with no surface at all — and made phase 4 able to kill a coordinator + between its cleanup and its terminal commit and still report the session + settled, with no terminal in the journal. + + **A session is `settled` exactly when the run the drain aborted has its + terminal fact committed**, and that is read on a surface core already + serves: the coordinator's own `{:session_status, owner}` call + (`session_coordinator.ex:414-442`), whose reply carries `active_run_id` + (`:421`) and `pending_work_ids` (`:425-426`) at the coordinator's committed + cursor. A run whose terminal is committed appears in neither. **The two + answers that must differ are therefore the aborted run present and the + aborted run absent**, and the owner the call requires is the one quiesce + read from `Control`'s enumeration, which is why that enumeration carries + it. + + No core change is needed for this, which is worth saying plainly after + several rounds of adding things: the read exists, quiesce is outside + `Control` and can make it, and a coordinator that refuses it — + `:session_unavailable` for a superseded or not-ready owner — is not a + settled session anyway. + + **So a cancellation that finished without its terminal committed is + `unsettled`, never `settled`**: terminated in phase 4, fenced in phase 5, + and reconciled at the next activation like any other. Phase 4 therefore + kills no owed write of a session it called settled, because a session is + called settled only once the write it owed is already in the journal. + + **Quiesce admits no abort into an `:acquiring` entry, and the disposition + is right even though an earlier revision's reason for it was not.** That + revision said an `:acquiring` session "has no ready coordinator". It may + have one: the coordinator sets `phase: :ready` (`session_coordinator.ex:1407`) + and then **casts** `{:owner_ready, …}` to `Control` (`:1424`) before + sending itself `:advance_work` (`:1425`), so a fully ready coordinator — a + resumed one, with a recovered active run already advancing — sits behind an + `:acquiring` entry until `Control` consumes that cast. + + The rule rests on the implication that actually holds: **`:active` ⇒ + ready**, because `Control` writes that status only in the `owner_ready` + handler (`control.ex:575-591`). Quiesce admits only into `:active`, which + is sound — every entry it admits into has a ready coordinator — and is what + keeps phase 2's bound honest, the acquisition callback being far deeper + than any ready one. What it costs is stated rather than hidden: an + `:acquiring` entry whose cast is merely in flight is a session whose run is + **ended crash-equivalent** by phase 4's termination rather than cancelled + through its own grace. Its journal claims no terminal, its ambiguous + mutation is `commit_unknown`, and the next activation reconciles it — + which is exactly the unsettled disposition, reached without the drain + having to guess at a cast it cannot see. **`:acquiring` is reachable, and an earlier revision called it unreachable.** That revision's argument was the cut: only `session.create` and @@ -3986,6 +4034,17 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. cancelled — and that the `daemon.stopping` record is written **after** the drain rather than before it. + **And it asserts what `settled` was read from**, which is the half an + earlier revision left unstated: the coordinator's + `{:session_status, owner}` reply, with the aborted run in neither + `active_run_id` nor `pending_work_ids` at the moment the drain classified + it. A **third** case is the one that separates the definition from the + timing: a session whose cancellation completes but whose **terminal commit + is held** past the budget is asserted **`unsettled`**, terminated and + fenced, with the journal carrying no terminal for that run — where the old + definition, "whether its cancellation finished", would have called it + settled and left phase 4 free to kill the write it still owed. + *It does not.* A daemon with an effect held past the drain budget and an unresolved mutation receives `SIGTERM`. The case asserts the session is in the `unsettled` list; that its coordinator is **gone before `quiesce/1` @@ -4541,7 +4600,7 @@ line; M5 introduces none of its own. | Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | | Phase 2, abort admission | a fixed **150 s** — five sequential Store calls at the adapter's own 30 s `@call_timeout`: the four of the deepest callback a **ready** coordinator may be running, which is **two** commits each re-presented once, and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. It rests on two claims — quiesce admits only into an `:active` entry, so the acquisition callback is never what an admission waits behind, and no ready callback reaches `commit_internal_result/2` more than twice | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `:5045-5068`, `:5396-5400`, `control.ex:575-591` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | -| Phase 4, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`), concurrent across **every** enumerated coordinator; it runs **before** the fence so that fence races no live writer | Core's existing child specification | +| Phase 4, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`), concurrent across **every** enumerated coordinator; it runs **before** the fence, so the fence races no live **writer** — at most the one transaction the serial lane may already have delivered, which its stale handling covers | Core's existing child specification | | Phase 5, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | From fbe1defb917adde99a50437d32e17091c0882282 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:37:56 -0700 Subject: [PATCH 155/585] plan(M5): adversarial pass over the sixth round MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Class 10, process safety, and it is this round's own doing. Moving `quiesce/1` into the caller's process (H1) put its per-session tasks in the **daemon owner's** process, and `Task.async` links. A linked task is an `{:EXIT, …}` at that owner, whose EXIT clause classifies any exit it did not ask for as a fatal class -- so one crashing drain task would have taken the daemon down mid-stop with a class naming nothing real. The tasks are `async_nolink` under the runtime's own worker `Task.Supervisor`, which `RuntimeSupervisor.children/1` already resolves as `workers` (`runtime/supervisor.ex:73`, `:104`, `:113`): no new process, no new option, and a task that dies arrives as a `DOWN` the drain handles like any other non-answer -- the session is fenced. Witness added. `Task.yield/2` per task becomes one `Task.yield_many/2` for the phase, which is what "concurrent, bounded by the phase" actually needs; yielding on each in turn would have serialised the bound it was meant to share. Checked and clean: no residue of `525`, of phase 2 at three calls, or of `quiesce/1` living in `Control`; the "inside core" phrasings elsewhere remain true, since what moved is which process runs the code, not whose code it is. --- docs/plans/M5-technical.md | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 78303a27e..44cd9e905 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `the cleanup callback commits at most twice on either branch`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `the cleanup callback commits at most twice on either branch`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -2463,10 +2463,21 @@ the call that does the work: a coordinator's `command/3` waits `:infinity` by de (`session_coordinator.ex:146-149`), and must, because a timeout there is not evidence of anything. So quiesce runs **each session's admission (phase 2) and each session's fence (phase 5) in its own task**, and bounds the task rather than -the call: -`Task.async/1` per session, one `Task.yield/2` against what remains of the -phase's absolute deadline, then `Task.shutdown/2` for whatever has not -answered. That is the ordinary bounded-task idiom, it needs no new mechanism, +the call: one task per session, a single `Task.yield_many/2` against what +remains of the phase's absolute deadline, then `Task.shutdown/2` for whatever +has not answered. + +**Those tasks are started `async_nolink` under the runtime's own worker +`Task.Supervisor`**, not linked to whoever called `quiesce/1`, and that +matters now that the caller is the **daemon's owner**. A linked task is an +`{:EXIT, …}` at that owner, and the owner's EXIT clause classifies any exit it +did not ask for as a **fatal class** — so one crashing drain task would take +the daemon down mid-stop with a class naming nothing real. Unlinked, a task +that dies arrives as a `DOWN` the drain handles like any other +non-answer: the session is fenced. The supervisor is the runtime root's third +child, already resolved by `RuntimeSupervisor.children/1` as `workers` +(`runtime/supervisor.ex:73`, `:104`, `:113`), so this needs no new process and +no new option — it is what that supervisor is for. That is the ordinary bounded-task idiom, it needs no new mechanism, and it is what makes "concurrent across sessions" and "bounded per phase" the same sentence rather than two hopes. From 820b7787dc3bbe03330ad9e3fbfeb5e9d3867702 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 15:58:14 -0700 Subject: [PATCH 156/585] plan(M5): the reserve-completion callback commits three times MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P0-1. The previous revision named the wrong callback and cited an edge that does not exist. `settle_executor_work/2` (`:5235-5256`) makes **no Store call**: it reads `in_flight_of/3` and local durable state and answers `{:settled, …}` or `{:reserved, …}`. `put_executor_fact/3` is not reached from it. The two real callers of `retain_executor_fact/3` are `:5354` and `:6302`. The deepest ready callback is the execute-result reserve's completion, `close_execute_result_reserve/3` (`:5336-5351`), and it commits **three** times: `retain_execute_result/3` (`:5353-5364`) → `retain_executor_fact/3` (`:6349`) for the executor fact; then, where that commit was refused or ambiguous -- `:5356-5358` answer `:unconfirmed` and leave the run at `effect_dispatched` -- `settle_owned_operation/3`'s `:unconfirmed` clause (`:5399-5400`) → `commit_owned_operation_unknown/2` (`:5437`) for the unproved tool result; then `finish_cleanup/4` → `commit_terminal/4` (`:2558-2563`) for the run terminal. The mutual-exclusion comment at `:5396-5398` says "whose fact **committed**", and the previous revision read it as bounding commits when it bounds only successful ones. A phase bound counts calls, not successes. **Phase 2 is seven calls, 210 s**, and the sum is **`budget_ms` + 645 s**. The ceiling is three, argued over the fifteen paths: twelve are reached by callbacks that commit once and return; the three that compose do so only in this callback and only in this order, the second requiring the first to have failed; and there is no fourth because `finish_cleanup/4` ends the run and every clause of it commits the terminal and returns. Both witnesses are re-pointed at that callback, with the injection that makes the three-commit branch reachable -- `refuse_next_record(store, "executor_receipt_committed")` -- and the ceiling case asserts the same callback commits twice when the fact commits. --- docs/plans/M5-technical.md | 93 ++++++++++++++++++++++---------------- docs/plans/M5.md | 10 ++-- 2 files changed, 60 insertions(+), 43 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 44cd9e905..7dfc4b058 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -294,8 +294,8 @@ reviewer can check against this sentence at closure. - **`docs/operator/daemon.md` must state the maximum graceful stop as the sum of the eight phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 585 s**, being 5 s for closing admissions, 300 s for - settling what was already admitted, 150 s for abort + **`budget_ms` + 645 s**, being 5 s for closing admissions, 300 s for + settling what was already admitted, 210 s for abort admission, `budget_ms` for cancellation, 5 s for coordinator termination, 90 s for the fence, 5 s for daemon teardown and 30 s for the Store — together with the sentence that keeps the number from being read as a @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `the cleanup callback commits at most twice on either branch`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -390,7 +390,7 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | --- | --- | --- | --- | --- | | Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | | The two history-paged kinds, at **fixed** sizes, so the claim that they have no constant is itself checked | `session.attach` over an empty session asserting **1**, and over an eight-event session asserting **2**; `session.resume` of a **twelve-record, eight-event** session asserting **11**, in the traced order, including **two** `transact` calls — the staged owner attempt and the advance | `apps/loopex/test/runtime_quiesce_test.exs` | `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls` | fast | -| Phase 2, five calls | A drained abort admitted behind **the real deepest callback**, not a synthetic one: a run is driven to `complete_cleanup/3` so that the coordinator commits the executor fact and then the run terminal in **one** callback, each commit made to answer `commit_unknown` once — four calls — and the drained abort is admitted behind it. Asserts **five**, and asserts the four belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. A third pins the ceiling itself: the same cleanup callback driven down its `:unconfirmed` branch is asserted to commit **twice, not three times**, the executor fact and the unproved tool result being mutually exclusive | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind the cleanup callback spends five store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the cleanup callback commits at most twice on either branch` | fast | +| Phase 2, seven calls | A drained abort admitted behind **the real deepest callback**: a run is driven to an execute-result reserve and that reserve closed, so `close_execute_result_reserve/3` commits the executor fact, the unproved tool result and the run terminal in **one** callback. The fact's commit is **refused** — the controllable store's `refuse_next_record(store, "executor_receipt_committed")` — which is what keeps the run at `effect_dispatched` and makes the second commit run at all; each commit is made to answer `commit_unknown` once, for six calls, and the drained abort is admitted behind them. Asserts **seven**, and asserts the six belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. A third pins the ceiling: the same callback with the fact's commit **succeeding** is asserted to commit **twice**, and no ready callback anywhere to commit four times | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one` | fast | | Phase 5, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | All three are **core** witnesses, because all three paths are core's: the @@ -2243,15 +2243,15 @@ that already exists somewhere, and the operator maximum is the sum: | --- | --- | --- | --- | | 1a | **Close admissions** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement of a **state change**, not of any work: the relay sets a flag, refuses everything after it, and answers. It has nothing to finish, so this bound measures the relay's own responsiveness and nothing else; a relay that does not answer inside it is a relay the daemon has lost, and the stop becomes the `relay_lost` fail-stop | | 1b | **Settle the admitted** | **300 s** — **ten** Store calls deep, the deepest ticket kind, counted from a traced run rather than from the code; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | -| 2 | **Abort admission** | **150 s** — **five** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** a **ready** coordinator is already running, which is at most two commits and so four calls, and then makes its own, which is one | +| 2 | **Abort admission** | **210 s** — **seven** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** a **ready** coordinator is already running, which is at most three commits and so six calls, and then makes its own, which is one | | 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | | 4 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across **every** enumerated coordinator | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | | 5 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | | 6 | **Daemon teardown** | **5 s** | One of this plan's two chosen numbers, covering the notice, the closes, the lease owners, the relay, **the runtime tree** and the edges. The runtime stop is attempted with what remains and killed at the bound; its trapping descendants unwind afterwards on their own clock, which the daemon does not wait for | | 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | -> **Maximum graceful stop = 5 s + 300 s + 150 s + `budget_ms` + 5 s + 90 s + -> 5 s + 30 s = `budget_ms` + 585 s**, and `budget_ms` is the one term an +> **Maximum graceful stop = 5 s + 300 s + 210 s + `budget_ms` + 5 s + 90 s + +> 5 s + 30 s = `budget_ms` + 645 s**, and `budget_ms` is the one term an > operator cannot compute in advance. **That is a worst case nobody approaches, and saying so is part of stating @@ -2386,36 +2386,53 @@ are these: `commit_internal_result/2`: the thirteen `commit_internal/2` call sites and the two into `retain_terminal_operation_fact/2` (`:4062`, `:6381`). - The traced double is the **cleanup-completion** callback, - `complete_cleanup/3` (`:5045-5068`): - - 1. `settle_executor_work/2` (`:5235`) → `put_executor_fact/3` (`:6379-6384`) - → `retain_terminal_operation_fact/2` → `commit_internal_result/2` — - **the executor fact**; - 2. `finish_settled_cleanup/4` (`:5070-5078`) → `finish_cleanup/4` - (`:5080-5090`) → `commit_terminal/4` (`:2558-2563`) → - `commit_internal/2` → `commit_internal_result/2` — **the run terminal**. - - Both inside one callback, with no return in between. - - **And never three, which is the part that needs an argument rather than a - count.** The only candidate third is `settle_owned_operation/3`'s - `:unconfirmed` clause (`:5399-5400`), which commits a tool result through - `commit_owned_operation_unknown/2` (`:5426-5444`, the commit at `:5437`) - between the two above. It cannot co-occur with the first, and the code says - why in its own comment at `:5396-5398`: *"a run whose executor answered and - whose fact committed has already left `effect_dispatched`, so this is a - no-op there, and a `:cleaned` cleanup has nothing unproved to record."* The - two are mutually exclusive by the stage the run is in — either the executor - answered and step 1 committed the fact, or it did not and - `commit_owned_operation_unknown/2` records the unproved result instead — so - the callback commits the run terminal plus **exactly one** of them. Every - other ready path reaches `commit_internal_result/2` once, each of the - fifteen sites sitting in its own function. - - **Maximum over the ready callbacks: two commits, so four adapter calls.** + **The deepest ready callback is the executor-reserve completion**, and an + earlier revision named the wrong one. That revision routed the executor + fact through `settle_executor_work/2` (`:5235-5256`) — which makes **no + Store call at all**: it reads `in_flight_of/3` and local durable state and + answers `{:settled, …}` or `{:reserved, …}`. `put_executor_fact/3` is not + reached from it. The two real callers of `retain_executor_fact/3` are + `:5354` and `:6302`. + + The callback is the one that closes an execute-result reserve — + `close_execute_result_reserve/3` (`:5336-5351`) — and it can commit + **three** times: + + 1. `retain_execute_result/3` (`:5353-5364`) → `retain_executor_fact/3` + (`:6349`) → `put_executor_fact/3` → `retain_terminal_operation_fact/2` → + `commit_internal_result/2` — **the executor fact**; + 2. then `finish_settled_cleanup/4` (`:5070-5078`) → + `settle_owned_operation/3`'s `:unconfirmed` clause (`:5399-5400`) → + `commit_owned_operation_unknown/2` (`:5426-5444`, the commit at `:5437`) + — **the unproved tool result**; + 3. then `finish_cleanup/4` (`:5080-5090`) → `commit_terminal/4` + (`:2558-2563`) → `commit_internal/2` → `commit_internal_result/2` — + **the run terminal**. + + All three inside one callback, with no return in between. + + **Steps 1 and 2 are not mutually exclusive, and the comment that says they + are means something narrower.** `:5396-5398` reads: *"a run whose executor + answered and whose fact **committed** has already left `effect_dispatched`, + so this is a no-op there."* That is exclusivity for a fact that + **committed**. A fact whose commit is **refused or ambiguous** takes + `retain_execute_result/3`'s other arms (`:5356-5358`), which answer + `:unconfirmed` and leave the run at `effect_dispatched` — so step 2 runs + after step 1 has already spent its calls. The previous revision read that + comment as bounding commits when it bounds only successful ones, and a + phase bound counts **calls**, not successes. + + **Three is the ceiling, argued over the fifteen paths.** Of the fifteen, + twelve are reached by callbacks that commit once and return. The three that + can compose are exactly the ones above, and they compose only in this + callback, in this order: a fact commit, an unproved-result commit that + requires the fact commit to have *failed*, and one terminal commit that ends + the run. There is no fourth, because `finish_cleanup/4` is where the run + ends and every one of its clauses commits the terminal and returns. + + **Maximum over the ready callbacks: three commits, so six adapter calls.** Plus the drain's own admission, which is **one** because it does not - retry — see the non-retrying commit below. **Five, in sequence.** + retry — see the non-retrying commit below. **Seven, in sequence.** **This bound rests on two claims and not on one**, and both are stated so a later change fails against them rather than around them: the rule that @@ -4609,14 +4626,14 @@ line; M5 introduces none of its own. | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | | Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | -| Phase 2, abort admission | a fixed **150 s** — five sequential Store calls at the adapter's own 30 s `@call_timeout`: the four of the deepest callback a **ready** coordinator may be running, which is **two** commits each re-presented once, and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. It rests on two claims — quiesce admits only into an `:active` entry, so the acquisition callback is never what an admission waits behind, and no ready callback reaches `commit_internal_result/2` more than twice | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `:5045-5068`, `:5396-5400`, `control.ex:575-591` | +| Phase 2, abort admission | a fixed **210 s** — seven sequential Store calls at the adapter's own 30 s `@call_timeout`: the six of the deepest callback a **ready** coordinator may be running — `close_execute_result_reserve/3`, which commits the executor fact, then an unproved tool result where that fact's commit was refused, then the run terminal, each re-presented once — and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. It rests on two claims — quiesce admits only into an `:active` entry, so the acquisition callback is never what an admission waits behind, and no ready callback reaches `commit_internal_result/2` more than three times | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `:5336-5351`, `:5353-5364`, `:5396-5400`, `control.ex:575-591` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | | Phase 4, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`), concurrent across **every** enumerated coordinator; it runs **before** the fence, so the fence races no live **writer** — at most the one transaction the serial lane may already have delivered, which its stale handling covers | Core's existing child specification | | Phase 5, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | | Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | | Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Maximum fail-stop exit | **35 s** — 5 s for the executor stop and the Store's own fixed 30 s, the only two steps of that path that wait; 5 s on the two store classes, where the Store is already gone | This plan, as the sum of its parts | -| Maximum graceful stop | `budget_ms` + **585 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | +| Maximum graceful stop | `budget_ms` + **645 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index f310bef9e..bf5ab5fab 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -435,19 +435,19 @@ service manager needs one, and it is the **sum of eight bounded phases** rather than one clock that has to cover everything: five seconds for the admission cut — which is two phases, because closing admissions is instant and waiting for what was already admitted is not: five seconds for the close and three -hundred for the settle, after which the stop proceeds. Then a hundred and -fifty for admitting every session's abort, the drain budget **core +hundred for the settle, after which the stop proceeds. Then two hundred and +ten for admitting every session's abort, the drain budget **core derives and reports** for the cancellation, five for terminating every coordinator it enumerated, ninety for fencing every one of those sessions afterwards, five for every non-Store action after the drain — the stop records, the closes, the lease owners, the runtime tree and the edges, the runtime being attempted with what remains and killed at the bound — and thirty for the Store stop that releases the marker. Seven of -the eight are fixed, so the maximum is **`budget_ms` plus 585 seconds** — a +the eight are fixed, so the maximum is **`budget_ms` plus 645 seconds** — a worst case assembled from the store adapter's ceiling for a wedged filesystem, not the cost of an ordinary stop, which finishes in milliseconds. **Five** of the seven are counts of the adapter's own thirty-second call timeout, or the coordinator's own shutdown -value: a phase that makes five Store calls in sequence is bounded at a hundred -and fifty and one that makes ten at three hundred, and the drain retries nothing, which +value: a phase that makes seven Store calls in sequence is bounded at two +hundred and ten and one that makes ten at three hundred, and the drain retries nothing, which is what keeps those counts finite. The other two — the five seconds for closing admissions and the five for the teardown — are **this plan's own numbers**, chosen rather than derived, and the technical companion says so From c26798bc1cfc719f4d6c1cb1a449ca3a73504547 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 16:00:14 -0700 Subject: [PATCH 157/585] plan(M5): a fourth Control status, one cut, a fresh enumeration P0-2. `Control` has four statuses, not three. `:awaiting_owner_barrier` (`control.ex:835`, `:1040`, `:1046-1053`, consumed in the owner-group `DOWN` handler at `:833-857`) is a dead coordinator with a live owner group and a caller still waiting -- reachable exactly when phase 1b proceeds with a resume in flight. It gets its row: `unsettled`, no abort admitted, terminated, and fenced, its outliving owner group ended by the runtime kill in phase 6. P0-3. Two cut semantics stood in one file. The relay bullet still said the cut "answers only when every ticket it holds has settled", which is the design phases 1a and 1b replaced and which the phase table and every witness contradict. One stands: 1a closes and answers, 1b waits and proceeds. What the cut buys is restated as the true, narrower thing -- after 1a no new work enters core, so the set quiesce reads can shrink but not grow, **except** by a ticket still settling. That exception is why phases 4 and 5 now take a **fresh** enumeration at phase 4's start rather than reusing phase 2's snapshot: `Control` keeps serving while the drain runs, so an entry that appeared during phases 2 and 3 is terminated and fenced like any other, and the `:not_needed` no-entry row is read from that list. One residual survives and is stated rather than closed. `create_session/2` makes up to three Store calls -- `runtime_command` at `control.ex:959-965` and the genesis commit at `:896-897`, re-presented once -- before `start_owner/4` reaches `await_owner/9` (`:1176-1195`), which is where the `state.sessions` entry is written. A create inside those calls is invisible to any enumeration and may commit after quiesce returns while phase 7 holds the Store open. It is bounded by the create's remaining depth, and what it leaves is the crash cut ADR 0032's recovery procedure already answers: a durable session the daemon never indexed, reached by replaying the create under its `command_id`. P1-4. `:unavailable` was both "fenced" and the `:not_needed` case, on the reading that such an entry never had a coordinator. It can have had one: `unavailable_owner/3` (`:1149-1158`) writes no coordinator key, and a caller reaches it at `:1134` after terminating a coordinator already started at `:1132`. Every `:unavailable` entry is fenced; `:not_needed` is the no-entry case alone. P1-7. The commonest drained session was unclassified: an abort on an idle session answers `"rejected_no_active_run"` (`session_state.ex:1750-1761`), so there is nothing to cancel and nothing owed. It is `settled` at once, and still terminated and fenced with the rest. --- docs/plans/M5-technical.md | 112 +++++++++++++++++++++++++++---------- 1 file changed, 81 insertions(+), 31 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 7dfc4b058..4e94a9620 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 to 5 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with a `:unavailable` `Control` entry asserted to land in `absent` and be fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only for an entry that never had a coordinator — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 to 5 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fresh phase-4 enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only for an entry that never had a coordinator`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the phase-4 enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during phases 2 and 3`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -1746,19 +1746,26 @@ as though it does: and the second grants nothing that could be overtaken. - **The admission cut is the relay's, because the relay is the only process that can answer for all ten.** The owner calls it once at the start of an - orderly stop; it stops admitting, and it answers only when **every ticket it - holds has settled** — not "settled or recorded", which an earlier revision - wrote and which gives away the whole property. A ticket merely *recorded* is - a call still running inside core, so quiesce would begin enumerating - `Control` while an admission, a create or an attach was still changing it. - Settling is the only acknowledgement worth having and it is reachable: every - ticketed call is bounded by core's own work rather than by a client, and a - ticket that cannot settle is the `relay_lost` case this section already - defines. That answer is what makes "after this instant nothing enters core - through the daemon **that could change what quiesce is about to read**" a - fact rather than a policy, and it is why every call that mutates `Control` - or the journal goes through this one process. The narrower claim is the true - one; the transfer methods above are the reason it has to be narrow. + orderly stop and the relay **stops admitting and answers at once** — that is + phase 1a, and it promises nothing about work already inside core. The wait + for that work is **phase 1b**, which is bounded and then **proceeds**. + + An earlier revision said here that the cut "answers only when every ticket + it holds has settled". That was the design phase 1a and 1b replaced, and + leaving the sentence standing gave this file two cut semantics — one that + waits unconditionally and one that proceeds at a bound — with the witnesses + and the phase table written against the second. One stands: **1a closes, 1b + waits, 1b proceeds.** + + What the cut buys is therefore narrower than that sentence claimed, and it + is the true thing: after 1a **no new work enters core through the daemon**, + so the set quiesce is about to read can only shrink from admitted work + finishing, never grow from new work arriving — except by a ticket still + settling, which is why phases 4 and 5 re-read the enumeration and why the + create residual below is stated. That is why every call that mutates + `Control` or the journal goes through this one process. The narrower claim + is the true one; the transfer methods above are the reason it has to be + narrow. That is the ordering claim ADR 0033's owner-loss section now rests on: a successor's first call cannot be issued while an older call for the same @@ -2549,9 +2556,8 @@ and "the session is reported `fence: :not_needed` if the head already moved and `:unknown` otherwise" — but deciding whether the head moved *is* a Store read, which is the very thing the rule has just refused. There is no way to take that branch. `:not_needed` now means one thing only, decided from the -`Control` entry without reading the Store: **a session for which no -coordinator ever existed in this runtime**, where there is nothing that could -write. Every other enumerated session is fenced — settled, unsettled and +fresh phase-4 enumeration without reading the Store: **a session it holds no +entry for**. Every enumerated session is fenced — settled, unsettled and absent alike, for the reason phase 5 gives — and its entry is `:committed`, `:superseded` or `{:unknown, …}`. @@ -3002,7 +3008,7 @@ can hold. `budget_ms` is the drain budget core derived and used. `drain_id` is the label this drain reports, and `fences` is what the fence below actually did for each session it touched — `:committed` where the epoch moved, `:superseded` where the one transaction that could still linearize won the -race first, `:not_needed` where no coordinator ever existed for the session so nothing could write for it, and +race first, `:not_needed` where the phase-4 enumeration holds no entry for the session at all, and `{:unknown, head}` where the Store could not say, **carrying the head the fence was built from**, because that head is the only thing a successor can discriminate on. **Without `fences` a fence's failure is @@ -3356,7 +3362,16 @@ carried: it described three outcomes and returned none of them. | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | `{:unknown, head}` | Resolved by **one** `Store.transaction_status/4` query under the same derived `tx_id`; an answer that is still unknown after it leaves the session `unsettled` with `{:unknown, head}` carrying the head the fence read, and the domain fenced | | **No fence is attempted** | No coordinator ever existed for this session in this runtime, so nothing can write for it | `:not_needed` | As the entry left it | - **Phase 5 fences every session quiesce enumerated — settled, unsettled and + **Phases 4 and 5 run over a *fresh* enumeration, not the one phase 2 + used.** `Control` keeps serving while the drain runs — which is the whole + point of quiesce being outside it — so entries can appear during phases 2 + and 3, and a create admitted just before the cut is exactly what appears. + Phase 4 therefore takes the enumeration again at its own start, and phases + 4 and 5 both work from that list. An entry that arrived during the + cancellation is terminated and fenced like any other; the `:not_needed` + no-entry row is read from **this** list rather than the earlier one. + + **Phase 5 fences every session in that enumeration — settled, unsettled and absent alike, every one of them with its coordinator already terminated in phase 4 — and an earlier revision fenced only the ones that had not settled.** That was a hole, and phase 7 is where it opened. The stop kills @@ -3376,11 +3391,33 @@ carried: it described three outcomes and returned none of them. epoch has moved and the adapter refuses it `:stale_owner_epoch` (`state.ex:548-551`). - `:not_needed` therefore survives for one case only, and it is decidable - from the entry rather than from the outcome: a session for which **no - coordinator ever existed in this runtime** — an entry that reached - `:unavailable` without one — where there is nothing that could write and - nothing to fence. + `:not_needed` therefore survives for one case only: a session the **fresh + phase-4 enumeration holds no entry for**. Not an `:unavailable` entry, + which an earlier revision used and which proves nothing about whether a + coordinator once existed; no entry at all. + + **One residual survives the fresh enumeration, and it is stated rather than + closed.** A `session.create` whose ticket was still outstanding when phase + 1b proceeded may not have an entry even at phase 4's enumeration: + `Control.create_session/2` makes up to **three** Store calls — the + `runtime_command` at `control.ex:959-965` and the genesis commit at + `:896-897`, re-presented once — before `start_owner/4` reaches + `await_owner/9` (`:1176-1195`), which is where the `state.sessions` entry + is written. A create inside those calls is invisible to any enumeration, + so it is neither terminated nor fenced, and its coordinator may start and + commit after `quiesce/1` has returned, while phase 7 still holds the Store + open. + + What that leaves is bounded and already covered. Bounded: the create's own + remaining depth, the rest of the ten calls phase 1b counts. Covered: + whatever it commits is an ordinary genesis and owner advance for a session + the daemon never indexed and never told a client about — which is exactly + the crash cut ADR 0032's *recovery procedure for the crash cut* answers, + where a client that never received the session ID replays its + `session.create` under the same `command_id` and the daemon repairs the + directory entry and index row. The next daemon meets a durable session it + can reach by command identity, not a lost one, and no false terminal is + claimed for it. The cost is stated: a settled session's next activation spends one ordinary epoch step, exactly as an unsettled one's does, and the journal a drained @@ -3430,16 +3467,21 @@ carried: it described three outcomes and returned none of them. **The classification quiesce returns has three lists, not two, and it is total over what `Control` actually holds.** An earlier revision wrote it as - though every entry were `:active`. `Control` has **three** statuses, and a - session may have no entry at all, so the drain says what it does with each: + though every entry were `:active`, and a later one found three statuses + where there are **four**. `Control` writes `:acquiring`, `:active`, + `:unavailable` and **`:awaiting_owner_barrier`** (`control.ex:835`, + `:1040`, `:1046-1053`, consumed in the owner-group `DOWN` handler at + `:833-857`), and a session may have no entry at all, so the drain says what + it does with each: | What `Control` holds | Why it can be there | Which list | Fenced? | | --- | --- | --- | --- | | `:active` with a live coordinator | The ordinary case | `settled` or `unsettled`, by whether the aborted run's **terminal fact is committed** — see the surface below | **Yes, either way** — see below | | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | - | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes**, for the same reason: there is no coordinator, and there may be a transaction | + | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes, always.** An earlier revision let this be the `:not_needed` case on the reading that such an entry never had a coordinator. It can have had one: `unavailable_owner/3` (`:1149-1158`) writes `%{status: :unavailable, durable: nil}` with **no coordinator key**, and one of its callers reaches it at `:1134` *after* terminating a coordinator that had already been started (`:1132`). The absent key proves nothing about the past, so every `:unavailable` entry is fenced | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | - | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No | + | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when phase 1b proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes**. Its coordinator is already gone, and the owner group that outlived it ends with the runtime kill in phase 6 | + | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No — the **only** `:not_needed` case, and it is read from the fresh enumeration phase 4 takes, never from the phase-2 snapshot | | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | | **A phase-5 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | | **A phase-5 task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | @@ -3451,8 +3493,16 @@ carried: it described three outcomes and returned none of them. between its cleanup and its terminal commit and still report the session settled, with no terminal in the journal. - **A session is `settled` exactly when the run the drain aborted has its - terminal fact committed**, and that is read on a surface core already + **A session with no run to abort is `settled` at once**, and it is the + commonest drained session there is. `propose_new/3` answers an abort on an + idle session `"admission" => "rejected_no_active_run"` + (`session_state.ex:1750-1761`); there was nothing to cancel, nothing is + owed, and the session is reported `settled` without waiting for a terminal + that no run will produce. It is still terminated and fenced in phases 4 + and 5 like every other enumerated session. + + **Otherwise a session is `settled` exactly when the run the drain aborted + has its terminal fact committed**, and that is read on a surface core already serves: the coordinator's own `{:session_status, owner}` call (`session_coordinator.ex:414-442`), whose reply carries `active_run_id` (`:421`) and `pending_work_ids` (`:425-426`) at the coordinator's committed From 54e23af7f95364224f6ae11166d74275e14a7e14 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 16:02:32 -0700 Subject: [PATCH 158/585] plan(M5): the enumeration is a new Control read, and five repairs P1-6. Quiesce's `Control` read was described as "exactly two bounded reads" followed by one read and a negation, and -- more to the point -- **`Control` cannot answer it today**. Its only session read takes a single id (`control.ex:473-481`) and nothing projects `state.sessions` at all. So the enumeration is a **new `Control` call**, a plain-data projection of every entry's session ID, status, coordinator pid and owner, taken in one `handle_call` and returning at once. It is named inside core change 4 in the concept pair's change list, the ownership table and the minimalism budget, because a change nobody listed is a change nobody reviews. It is made twice: once at the start of the drain, once at the start of phase 4. P1-5. `quiesce/1` has four parts, which are stop phases 2 to 5, not three parts and phases 2 to 4. P2-8. The provider modules are **thirteen** serial and **eleven** referencing the credential variable, counted rather than carried forward. `test/support/provider_entry_test.exs` is in scope like any other: the application's `test_ignore_filters` name three fixture and diagnostic files and no `*_test.exs` (`apps/loopex_llm_reqllm/mix.exs:16-22`). Four places. P2-9. The huge-grace witness was vacuous: the grace reaches a wait only through `budget_ms`, which is `0` on a daemon with nothing active -- the one value that cannot exercise slicing. The case now activates a session, leaves an effect in flight, and asserts the derived budget actually exceeds 2^32-1 before asserting the stop completes. And the slicing obligation is assigned to `quiesce/1`'s own waits: phase 3 is the only bound unbounded by construction, core is where it is enforced, and every other phase is a fixed number far inside the domain. P2-10. The fatal-class map is one row per linked process **except the Store's**, which has two -- the capacity refusal distinguished from every other reason, as the table itself says four rows above. --- docs/plans/M5-technical.md | 79 +++++++++++++++++++++++++++----------- docs/plans/M5.md | 26 ++++++++----- 2 files changed, 73 insertions(+), 32 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 4e94a9620..81b80dd65 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not, together with the one coordinator change it needs in two halves — a drained abort pauses where cleanup would have begun, and its commit is presented once rather than retried on an ambiguous answer**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -148,7 +148,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The twelve modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -2703,12 +2703,15 @@ today, so the rule is stated here: subtracting one timeout from another, so no arithmetic can produce a negative `after` — which is the other way `after` fails, as the 1 ms stop probe showed. -- **Every wait is taken in slices of at most `@wait_slice_ms`, 60_000**, a - minute being long enough that slicing costs nothing measurable and short - enough to be far inside the domain. After each slice the owner compares the - clock with the deadline and either waits again or gives up. A budget of any - admitted size is therefore reachable, and no `after` argument is ever larger - than the slice. +- **Every wait is taken in slices of at most `@wait_slice_ms`, 60_000** — the + obligation falling on **`quiesce/1`'s own waits**, phase 3 being the only + bound that is unbounded by construction and core being where it is + enforced; every other phase is a fixed number far inside the domain. A + minute is long enough that slicing costs nothing measurable and short + enough to be far inside that domain. After each slice the waiter compares + the clock with the deadline and either waits again or gives up. A budget of + any admitted size is therefore reachable, and no `after` argument is ever + larger than the slice. - **The composition-input table says what a huge value does**: it is accepted, not refused, because core accepts it; the daemon simply never passes it to `after` unsliced. An operator who composes a grace of a year gets a daemon @@ -3600,15 +3603,25 @@ Not a race — a certainty, on the first session with work to drain. So `quiesce/1` is a function of **`Loopex.Runtime`** that executes in the **caller's** process — the daemon's owner, which sits on no commit path — and `Control` keeps serving `post_commit` and `current_owner` throughout. -What it asks `Control` for is exactly two bounded reads: - -- **the enumeration**, once: every session entry with its status, its - coordinator pid and its **owner**, which is what the per-session calls need - to identify themselves as the current owner; -- **nothing else.** The drain's work — admitting, cancelling, terminating, - fencing and reading status — is per-session calls the caller's own tasks - make **directly to coordinators and to the Store**, never through - `Control`. +What it asks `Control` for is **one** bounded read, made **twice**: the +enumeration — every session entry with its status, its coordinator pid and +its **owner**, the owner being what the per-session calls need to identify +themselves as current. Once at the start of the drain, and again at the start +of phase 4, for the reason that phase gives. Everything else the drain does — +admitting, cancelling, terminating, fencing and reading status — is +per-session calls the caller's own tasks make **directly to coordinators and +to the Store**, never through `Control`. (An earlier revision said "exactly +two bounded reads" and then listed one and a negation.) + +**That enumeration does not exist today, and adding it is part of core +change 4.** `Control` answers `{:session_status, token, session_id}` for **one** +session (`control.ex:473-481`) and has no call that projects `state.sessions` +at all. So quiesce's read is a new `Control` call — a plain-data projection of +every entry's session ID, status, coordinator pid and owner, taken in one +`handle_call` and returning immediately, which is what keeps it from blocking +the process it reads. It is named in the concept pair's core-change list and +in the ownership table beside `quiesce/1` itself, because a change nobody +listed is a change nobody reviews. Neither read blocks `Control` for longer than a map projection, so a coordinator committing in the middle of phase 2 is served as usual. That is @@ -3877,7 +3890,9 @@ set; a lease owner produces no daemon exit class at all. The rows are named rather than numbered, because a number is a fact about the start order and this table is a fact about which pid died; the two drifted apart in an earlier revision and the numbers are gone for that reason. There -is one row per linked process, and the transfers row exists only in a daemon +is one row per linked process **except the Store's, which has two** — the +capacity refusal being distinguished from every other reason, as the table +above says — and the transfers row exists only in a daemon that has one. **`registry_lost`, `custody_lost` and `capability_lost` are fail-stop like @@ -4350,7 +4365,23 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. `18_446_744_073_709_551_615` — and asserts the daemon starts, stops and releases the marker normally: the value reaches no `receive … after` unsliced, which is what the wait rule promises and what a direct `after` - would have turned into an immediate `:timeout_value` exit. All of them run + would have turned into an immediate `:timeout_value` exit. + + **That case requires an active session with work in flight, and without one + it proves nothing.** The huge grace only ever reaches a wait through + `budget_ms`, which is the maximum over the **drained** sessions of + `cancellation_bounds(g_i).cli_backstop_ms` and is therefore **`0`** on a + daemon with nothing active — the very value that cannot exercise slicing. + So the case activates a session, leaves a dispatched effect in flight, and + asserts the derived `budget_ms` actually exceeds 2^32-1 before asserting the + stop completes. + + **And the slicing obligation is `quiesce/1`'s, not the daemon owner's.** + Phase 3 is the one phase whose bound is unbounded by construction, and it is + enforced inside core; every other phase is a fixed number far below the + domain. The wait rule therefore binds core's own waits in the drain, and the + daemon's owner — whose longest wait is phase 1b's 300 s — inherits it as a + rule it cannot violate rather than one it must remember. All of them run at both toolchain pairs, because both timeout results were observed at both. - **A replayed create repairs, a fresh create charges.** Two cases on the @@ -4603,10 +4634,14 @@ what `Loopex.create_session/3` forwards to a released embedded caller (`loopex.ex:87-95`), which is a compatibility break bought for a daemon's bookkeeping. Direct code cannot supply them, because the only alternative is inferring the answer from side effects, -which is a race. **One bounded `quiesce/1`, and the one coordinator change it needs** — the +which is a race. **One bounded `quiesce/1`, the one coordinator change it needs and the one +`Control` read it enumerates from** — the admit-and-pause split and the non-retrying drained commit, which are two -halves of one clause rather than two changes, and neither of which is -reachable from outside a drain. It unifies nothing today and says so: +halves of one clause rather than two changes and neither of which is +reachable from outside a drain, and a plain-data projection of `Control`'s +session entries, which is the smallest thing that can answer "what is there +to drain" and which `Control` cannot answer today at all, its only session +read taking one id. It unifies nothing today and says so: its only caller is the daemon's orderly stop, and the app-server host does not drain by hand, because `LoopexComposition.with_runtime/2` brackets a runtime that lives and dies with one client's stdin and has nothing to drain diff --git a/docs/plans/M5.md b/docs/plans/M5.md index bf5ab5fab..38036d30a 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -31,10 +31,14 @@ closure authorizes. M5 also settles one debt M4's verification work left explicitly open. The provider adapter resolves its credential by reading a process-wide environment variable inside each call, which is both a weaker property than the rest of -its credential plane and the reason the twelve heavy provider test modules -declare `async: false` — **ten of the twelve** reference the credential -variable directly, and the other two are serial beside them for their own -reasons. M5 moves that handoff onto the private per-invocation +its credential plane and the reason the **thirteen** heavy provider test +modules declare `async: false` — **eleven of the thirteen** reference the +credential variable directly, and the other two are serial beside them for +their own reasons. Thirteen counts +`apps/loopex_llm_reqllm/test/support/provider_entry_test.exs`, which is in +scope like any other: the application's `test_ignore_filters` name only three +fixture and diagnostic files and no `*_test.exs` +(`apps/loopex_llm_reqllm/mix.exs:16-22`). M5 moves that handoff onto the private per-invocation channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's @@ -53,7 +57,9 @@ list's values under their own keys, which is what keeps the credential token out of an entry on its way to the adapter; `quiesce/1`, the bounded settle an orderly stop drains through — which carries one coordinator change in two halves, an admission that pauses where cleanup would have begun and a commit that does -not re-present itself on an ambiguous answer, both in the same clause; and two plain fields on **two new runtime-side functions beside** create and +not re-present itself on an ambiguous answer, both in the same clause, and +one new `Control` read, a plain-data projection of every session entry that +quiesce enumerates from and that `Control` has no equivalent of today; and two plain fields on **two new runtime-side functions beside** create and resume — `create_session_detailed/3` and `resume_session_detailed/3`, so the existing pair keeps its exact return and the embedded facade forwards what it forwards today — `disposition`, saying whether the call was fresh or a replay, @@ -74,7 +80,7 @@ second loop and no new durable command. | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | -| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the credential is named by an opaque token bound at composition, whose **resolution** is what happens per invocation, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The twelve provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, ADR 0034's host-owned-process cases at `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/`, the security review recorded in `docs/evidence/M5-closure-runs.md` | +| 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the credential is named by an opaque token bound at composition, whose **resolution** is what happens per invocation, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The eleven provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, ADR 0034's host-owned-process cases at `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/`, the security review recorded in `docs/evidence/M5-closure-runs.md` | Technical depth: [Evidence obligations and mapping](M5-technical.md#technical-plan-evidence). @@ -302,7 +308,7 @@ behaves, what bounds it, and what every failure does. The maintainer set this as reasons. A credential that must sit in the parent VM's environment for the duration of every call is a weaker property than one that exists only on a private channel to the child that needs it; and that shared slot is what makes -ten of the twelve heavy provider test modules serial, which leaves the provider suite +eleven of the thirteen heavy provider test modules serial, which leaves the provider suite as the fast check's critical path. The change stays inside the credential plane: what a child may receive, from whom and when does not widen, and every negative proof M0 to M2 established is carried to the new mechanism rather @@ -390,8 +396,8 @@ did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. **The drain has a mechanism, and it is core's.** M5 adds `quiesce/1` to -`Loopex.Runtime`, and it has three parts — which are stop **phases 2, 3 and -4**, the numbering the bound uses, rather than a second scheme of its own. +`Loopex.Runtime`, and it has four parts — which are stop **phases 2 to 5**, +the numbering the bound uses, rather than a second scheme of its own. **Phase 2** durably admits the existing abort command for every active session and stops there, because ADR 0023 fixes that only a durable `session.abort` cancels and nothing may infer @@ -926,7 +932,7 @@ that adds the tests it names. | 3 | Open | No controller lease, writer epoch or takeover exists above core | | 4 | Open | Core replaces an existing same-session attachment today; no independent concurrent attachments, resident window, socket output buffer or eviction exists | | 5 | Open | No two-process workflow, daemon operator guide or `0.2.0` source archive exists | -| 6 | Open | The adapter resolves the credential from the parent VM's environment inside each call; ten of the twelve heavy provider modules reference that variable and all twelve declare `async: false` | +| 6 | Open | The adapter resolves the credential from the parent VM's environment inside each call; eleven of the thirteen heavy provider modules reference that variable and all thirteen declare `async: false` | **Revision of 2026-09-14 (first).** On the independent review of `dc81212360327caa7e8b0ed371cb5ed531b960d9`, the maintainer narrowed this plan From 673a37b50815112f62cc37331acb52a739a7adbf Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 16:03:30 -0700 Subject: [PATCH 159/585] plan(M5): adversarial pass over the seventh round Class 7, stale vocabulary, two places the new counts did not reach. The ready-callback section still headed itself "a ready callback commits twice", correcting the revision before it while describing the one this round replaced; and the two-claim sentence still capped the ceiling at twice. Three, in both, with the history kept as history: that ceiling has now been wrong twice by reading and right once by execution, which is the whole argument for requiring the executed-count witness rather than the enumeration. Class 30, result totality: `control_entry` was still "three values over three statuses plus no-entry" after P0-2 found the fourth. `:awaiting_owner_barrier` maps to `:dormant` with `:unavailable` and no-entry -- there is no live coordinator in any of the three, the barrier status meaning the coordinator has already died -- and the status list beside it carries `control.ex:835`. Grepped clean: no residue of `585`, of phase 2 at five calls, or of the `settle_executor_work/2` chain except where it is named as the edge that does not exist. --- docs/plans/M5-technical.md | 24 +++++++++++++++--------- 1 file changed, 15 insertions(+), 9 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 81b80dd65..dd39e9a21 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -991,13 +991,16 @@ carries two plain fields beside the session ID:** | `disposition` | `:fresh` \| `:historical` | Charge an activation for `:fresh`; charge nothing for `:historical` | | `control_entry` | `:active` \| `:acquiring` \| `:dormant` | Repair the directory entry and index row without activating when `:dormant`; leave both alone when `:active`, since an activated session already recorded them | -**`control_entry` is three values over three statuses plus no-entry, and an +**`control_entry` is three values over four statuses plus no-entry, and an earlier revision argued one of them away.** `Control` holds `:active`, -`:acquiring` and `:unavailable`, and a session may have no entry at all -(`control.ex:569`, `:620`, `:818`, `:862`, `:1030`, `:1150`, `:1189`). The +`:acquiring`, `:unavailable` and `:awaiting_owner_barrier`, and a session may +have no entry at all +(`control.ex:569`, `:620`, `:818`, `:835`, `:862`, `:1030`, `:1150`, `:1189`). +The mapping is `:active` → **`:active`**; `:acquiring` → **`:acquiring`**; -`:unavailable` and no-entry → **`:dormant`**, there being no coordinator -either way. +`:unavailable`, `:awaiting_owner_barrier` and no-entry → **`:dormant`**, +there being no live coordinator in any of the three — the barrier status +meaning the coordinator has already died. That revision said `:acquiring` "is never observed by the caller of a completed create or resume", reasoning that the status exists only while that @@ -2382,8 +2385,9 @@ are these: where `resolve_transaction/2` re-presents on `commit_unknown` (`:1752-1768`). - **A ready callback commits twice, and an earlier revision said once.** That - revision argued that a committing callback ends by sending itself + **A ready callback commits three times, and two earlier revisions said + once and then twice.** The first + argued that a committing callback ends by sending itself `:advance_work` and so cannot continue — which is true of `apply_transaction/3`, where that send sits (`:1720`), and of nothing else: the module has **thirteen** such sends (`:465`, `:627`, `:1425`, `:1720`, @@ -2445,8 +2449,10 @@ are these: later change fails against them rather than around them: the rule that quiesce admits only into `:active`, which keeps the acquisition callback out of the wait; and this enumeration, that no ready callback reaches - `commit_internal_result/2` more than twice. The executed-count witness below - is what holds the second to a number. + `commit_internal_result/2` more than three times. The executed-count witness + below is what holds the second to a number — and it has now been wrong twice + by reading and right once by execution, which is the whole argument for + requiring the witness. - **Phase 5 is three at worst.** A head read, then the `advance_owner`, then, only where that answers `commit_unknown`, **one** `transaction_status` query. - **And the drain retries nothing, which is a change to the coordinator rather From eb3878a638766aa1223c6358c3a7338b0c09efd3 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 16:18:51 -0700 Subject: [PATCH 160/585] plan(M5): bound both commit routes and both late activations MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A1. The ceiling argued only over `commit_internal_result/2` and its fifteen paths, while the site table beside it names a second route -- `apply_transaction/3`, the command admission. A callback takes both: the admission commits, and its reply path runs `begin_admitted_cleanup/1` (`:4806-4817`) into `begin_cleanup/3`'s `"model_attempt_open"` branch (`:4841`) → `begin_model_termination/3` (`:4861`) → `settle_model_attempt/3` (`:4876`, `:4038-4056`) → `commit_model_settlement/3` (`:4048`) → `retain_terminal_operation_fact/2` (`:4062`), a second commit in the same callback. The ceiling now covers both routes. **It stops at two, and the bound does not move.** Every branch of `commit_model_settlement/3` (`:4078-4104`) ends the callback, and the other cleanup branch reaches no synchronous commit at all -- `dispatch_host_cancel/3` either sends itself a message (`:5010-5011`) or spawns `async_nolink` (`:5028-5031`). So the admission route is two commits and the reserve route three; phase 2 stays at seven calls and the sum at `budget_ms` + 645 s. That is a deviation from the decision, argued from the lines above, and the new witness asserts the admission route commits **twice and stops** so a trace that disagrees fails there rather than in prose. A2. The late-entry residual was written for creates and leaned on replay by `command_id`, which is a create's recovery. `Control.resume_session` has the same window: its `Store.runtime_command` at `control.ex:310` precedes the `:acquiring` entry written at `:1030` and `:1189`. Both calls are restated with the disposition that actually holds for either -- the phase-6 kill ends a non-trapping coordinator at once, at most one already-delivered transaction linearizes, and it lands as an ordinary durable fact with no terminal claimed, read as history by the next activation's head read (`:1186-1203`). Replay by `command_id` is named as an **additional** recovery for one of the two. A late attach is excluded with its reason: `begin_attach/3` requires `:active` (`control.ex:1237`). A3. The provider module count is settled by evidence, not by a glob. That application sets no `test_paths`, no `test_pattern` and no `elixirc_paths`, so the default pattern matches recursively under `test/`, and its `test_ignore_filters` name three non-`_test` files (`mix.exs:16-22`). Measured: `mix test --only ` reports **179 excluded**; the twelve `test/*_test.exs` files alone report **164**; the difference of **15** is exactly what `mix test test/support/provider_entry_test.exs` runs. Thirteen serial modules, eleven referencing the variable, with the method cited in all four places. B1. "Every count is taken from a traced run" was not true of one. Four are traced -- create's nine, attach's one and two, resume's eleven, the fence's three -- and phase 2's seven is derived by reading and waits on its witness. B2. The `:awaiting_owner_barrier` row credited phase 6's kill with its safety. That kill ends the root only; a trapping `OwnerGroup` unwinds afterwards into a Store phase 7 keeps open. Phase 5's moved epoch is what refuses its commits. --- docs/plans/M5-technical.md | 112 ++++++++++++++++++++++++++----------- docs/plans/M5.md | 31 +++++++--- 2 files changed, 102 insertions(+), 41 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index dd39e9a21..bd6857780 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -148,7 +148,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -349,7 +349,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the phase-4 enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during phases 2 and 3`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the phase-4 enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during phases 2 and 3`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -390,7 +390,7 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | --- | --- | --- | --- | --- | | Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | | The two history-paged kinds, at **fixed** sizes, so the claim that they have no constant is itself checked | `session.attach` over an empty session asserting **1**, and over an eight-event session asserting **2**; `session.resume` of a **twelve-record, eight-event** session asserting **11**, in the traced order, including **two** `transact` calls — the staged owner attempt and the advance | `apps/loopex/test/runtime_quiesce_test.exs` | `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls` | fast | -| Phase 2, seven calls | A drained abort admitted behind **the real deepest callback**: a run is driven to an execute-result reserve and that reserve closed, so `close_execute_result_reserve/3` commits the executor fact, the unproved tool result and the run terminal in **one** callback. The fact's commit is **refused** — the controllable store's `refuse_next_record(store, "executor_receipt_committed")` — which is what keeps the run at `effect_dispatched` and makes the second commit run at all; each commit is made to answer `commit_unknown` once, for six calls, and the drained abort is admitted behind them. Asserts **seven**, and asserts the six belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. A third pins the ceiling: the same callback with the fact's commit **succeeding** is asserted to commit **twice**, and no ready callback anywhere to commit four times | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one` | fast | +| Phase 2, seven calls | A drained abort admitted behind **the real deepest callback**: a run is driven to an execute-result reserve and that reserve closed, so `close_execute_result_reserve/3` commits the executor fact, the unproved tool result and the run terminal in **one** callback. The fact's commit is **refused** — the controllable store's `refuse_next_record(store, "executor_receipt_committed")` — which is what keeps the run at `effect_dispatched` and makes the second commit run at all; each commit is made to answer `commit_unknown` once, for six calls, and the drained abort is admitted behind them. Asserts **seven**, and asserts the six belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. Two more pin the ceiling over **both** commit routes: the same reserve callback with the fact's commit **succeeding** asserted to commit **twice**; and an **abort admitted against a run with an open model attempt**, whose reply path runs `begin_admitted_cleanup/1` into the model settlement, asserted to commit **twice and stop there** — four adapter calls, fewer than the reserve route's six, which is what makes the reserve route the bound | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops` | fast | | Phase 5, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | All three are **core** witnesses, because all three paths are core's: the @@ -2433,13 +2433,37 @@ are these: comment as bounding commits when it bounds only successful ones, and a phase bound counts **calls**, not successes. - **Three is the ceiling, argued over the fifteen paths.** Of the fifteen, - twelve are reached by callbacks that commit once and return. The three that - can compose are exactly the ones above, and they compose only in this - callback, in this order: a fact commit, an unproved-result commit that - requires the fact commit to have *failed*, and one terminal commit that ends - the run. There is no fourth, because `finish_cleanup/4` is where the run - ends and every one of its clauses commits the terminal and returns. + **There are two routes into a commit, and the ceiling has to bound both.** + An earlier revision argued only over `commit_internal_result/2` and its + fifteen paths, while the site table above names a second route — + `apply_transaction/3` (`:1702`), the **command admission** itself. A + callback can take both, and one does: + + - **The admission route reaches two.** `commit_command_proposal/2` + (`:1672-1699`) commits the admission through `apply_transaction/3` and + then, on the commit reply path, runs `begin_admitted_cleanup/1` + (`:4806-4817`). For a run with an **open model attempt** that continues + synchronously — `begin_cleanup/3`'s `"model_attempt_open"` branch + (`:4841`) → `begin_model_termination/3` (`:4861`) → + `settle_model_attempt/3` (`:4038-4056`, at `:4876`) → + `commit_model_settlement/3` (`:4048`, `:4059`) → + `retain_terminal_operation_fact/2` (`:4062`) — a **second** commit in the + same callback. It stops there: every branch of + `commit_model_settlement/3` (`:4078-4104`) ends the callback, and the + other cleanup branch reaches no synchronous commit at all, since + `dispatch_host_cancel/3` either sends itself a message (`:5010-5011`) or + spawns `async_nolink` (`:5028-5031`). + - **The reserve route reaches three**, as traced above. + + **Three is therefore the ceiling, over both routes.** Of the fifteen + `commit_internal_result/2` paths, twelve are reached by callbacks that + commit once and return. The three that can compose do so only in the + reserve-completion callback, in that order: a fact commit, an + unproved-result commit that requires the fact commit to have *failed*, and + one terminal commit that ends the run. There is no fourth, because + `finish_cleanup/4` is where the run ends and every one of its clauses + commits the terminal and returns; and the admission route adds a second + commit to a callback that then stops, never a fourth to this one. **Maximum over the ready callbacks: three commits, so six adapter calls.** Plus the drain's own admission, which is **one** because it does not @@ -3405,28 +3429,50 @@ carried: it described three outcomes and returned none of them. which an earlier revision used and which proves nothing about whether a coordinator once existed; no entry at all. - **One residual survives the fresh enumeration, and it is stated rather than - closed.** A `session.create` whose ticket was still outstanding when phase - 1b proceeded may not have an entry even at phase 4's enumeration: - `Control.create_session/2` makes up to **three** Store calls — the - `runtime_command` at `control.ex:959-965` and the genesis commit at - `:896-897`, re-presented once — before `start_owner/4` reaches - `await_owner/9` (`:1176-1195`), which is where the `state.sessions` entry - is written. A create inside those calls is invisible to any enumeration, - so it is neither terminated nor fenced, and its coordinator may start and - commit after `quiesce/1` has returned, while phase 7 still holds the Store - open. - - What that leaves is bounded and already covered. Bounded: the create's own - remaining depth, the rest of the ten calls phase 1b counts. Covered: - whatever it commits is an ordinary genesis and owner advance for a session - the daemon never indexed and never told a client about — which is exactly - the crash cut ADR 0032's *recovery procedure for the crash cut* answers, - where a client that never received the session ID replays its - `session.create` under the same `command_id` and the daemon repairs the - directory entry and index row. The next daemon meets a durable session it - can reach by command identity, not a lost one, and no false terminal is - claimed for it. + **One residual survives the fresh enumeration, it covers *both* + activation-capable calls, and it is stated rather than closed.** An earlier + revision wrote it for `session.create` alone and leaned the whole + disposition on replay by `command_id`, which is a create's recovery and not + a resume's. Both calls have the same window, for the same reason: the entry + that makes a session enumerable is written late. + + - **`session.create`** makes up to **three** Store calls — the + `runtime_command` at `control.ex:959-965` and the genesis commit at + `:896-897`, re-presented once — before `start_owner/4` reaches + `await_owner/9` (`:1176-1195`), where the `state.sessions` entry is + written. + - **`session.resume`** makes its `Store.runtime_command` at `control.ex:310` + before `start_resume_owner` reaches the same `do_start_owner` path, whose + `:acquiring` entry is written at `:1030` and `:1189`. + + A call inside those Store calls is invisible to any enumeration, so it is + neither terminated by phase 4 nor fenced by phase 5, and its coordinator + may start after phase 4's read. + + **What actually holds for it is crash-equivalence, not replay**, and that + is the disposition stated: the runtime kill in phase 6 ends such a + coordinator **at once**, it being non-trapping; at most **one** transaction + it had already delivered can linearize afterwards, the owner lane being + serial; and that transaction lands as an ordinary durable fact — a genesis, + an owner advance or a command admission — with **no terminal claimed**. The + next activation reads it as history, `discover_and_advance_owner/1` reading + the head it finds (`session_coordinator.ex:1186-1203`). Nothing false is + recorded and nothing is lost. + + For a **create whose client never learned the session ID**, ADR 0032's + *recovery procedure for the crash cut* applies **in addition**: the client + replays its `session.create` under the same `command_id`, and the daemon + repairs the directory entry and index row. That is a second recovery for + one of the two calls, not the reason either is safe. + + Bounded, in both cases, by the call's own remaining depth — the rest of the + ten calls phase 1b counts for a create, and a resume's own sequence. + + **A late `session.attach` is not in this class**, and the reason is worth + one line: `begin_attach/3` requires the entry to be `:active` already + (`control.ex:1237`), so an attach cannot bring a session into existence + behind the enumeration. It either finds an entry the enumeration also found + or is refused. The cost is stated: a settled session's next activation spends one ordinary epoch step, exactly as an unsettled one's does, and the journal a drained @@ -3489,7 +3535,7 @@ carried: it described three outcomes and returned none of them. | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes, always.** An earlier revision let this be the `:not_needed` case on the reading that such an entry never had a coordinator. It can have had one: `unavailable_owner/3` (`:1149-1158`) writes `%{status: :unavailable, durable: nil}` with **no coordinator key**, and one of its callers reaches it at `:1134` *after* terminating a coordinator that had already been started (`:1132`). The absent key proves nothing about the past, so every `:unavailable` entry is fenced | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | - | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when phase 1b proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes**. Its coordinator is already gone, and the owner group that outlived it ends with the runtime kill in phase 6 | + | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when phase 1b proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes, and the fence is what makes it safe.** Its coordinator is already gone, so phase 4 has nothing to terminate; what could still write is the **owner group that outlived it**, and phase 6's kill does not answer that — `Process.exit(sup, :kill)` ends the root only, and a trapping `OwnerGroup` unwinds on its own clock afterwards, into a Store phase 7 keeps open. Phase 5's moved epoch is what refuses those commits `:stale_owner_epoch`. An earlier revision credited the kill | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No — the **only** `:not_needed` case, and it is read from the fresh enumeration phase 4 takes, never from the phase-2 snapshot | | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | | **A phase-5 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 38036d30a..e189b5601 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -34,11 +34,21 @@ variable inside each call, which is both a weaker property than the rest of its credential plane and the reason the **thirteen** heavy provider test modules declare `async: false` — **eleven of the thirteen** reference the credential variable directly, and the other two are serial beside them for -their own reasons. Thirteen counts -`apps/loopex_llm_reqllm/test/support/provider_entry_test.exs`, which is in -scope like any other: the application's `test_ignore_filters` name only three -fixture and diagnostic files and no `*_test.exs` -(`apps/loopex_llm_reqllm/mix.exs:16-22`). M5 moves that handoff onto the private per-invocation +their own reasons. + +Thirteen rather than twelve, and the difference is one file whose membership +was settled by running it rather than by reading a glob: +`apps/loopex_llm_reqllm/test/support/provider_entry_test.exs`. It sits under +`test/support/`, which invites the assumption that it is a helper. It is not. +That application sets no `test_paths`, no `test_pattern` and no +`elixirc_paths`, so Mix's defaults apply and the default pattern is matched +**recursively** under `test/`; its `test_ignore_filters` name three +non-`_test` fixture and diagnostic files and nothing else +(`apps/loopex_llm_reqllm/mix.exs:16-22`). Measured: in that application +`mix test --only ` reports **179 excluded**, the twelve +`test/*_test.exs` files alone report **164**, and the difference of **15** is +exactly what `mix test test/support/provider_entry_test.exs` runs. An +ordinary `mix test` loads it. M5 moves that handoff onto the private per-invocation channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's @@ -457,9 +467,14 @@ hundred and ten and one that makes ten at three hundred, and the drain retries n is what keeps those counts finite. The other two — the five seconds for closing admissions and the five for the teardown — are **this plan's own numbers**, chosen rather than derived, and the technical companion says so -where it names them. Every count is taken from a traced run of the path -rather than from reading it, because reading it is how an earlier revision -missed four calls. The drain term is core's because each session drains under the grace it +where it names them. **Four of those counts are taken from a traced run** — a fresh create's nine, +an attach's one and two, a resume's eleven and a fence's three. **Phase 2's +seven is not**: it is derived by reading which commits one coordinator +callback can compose, and it waits on its witness like the others. The +distinction is drawn rather than glossed, because reading is exactly how that +count was wrong twice before a trace settled it, and a plan that called every +number traced when one was not would be repeating the error it is warning +about. The drain term is core's because each session drains under the grace it committed, which a daemon reading its own flag would not know for a session composed earlier. A service manager that kills the daemon sooner turns the stop into a forced From 9182ffe9b39391461b3f72e25ad3c15e484f08c3 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 16:19:34 -0700 Subject: [PATCH 161/585] plan(M5): adversarial pass over the eighth round Class 7, and it is the same class this round's A1 found: extending the ceiling to a second commit route left two statements of it describing only the first. The two-claim paragraph and the phase-2 limits row both said "no ready callback reaches `commit_internal_result/2` more than three times", which is the narrower claim the admission route was added to widen. Both now say no ready callback **commits** more than three times, counting both routes. And the tally beside it is corrected: that ceiling has been wrong three times by reading -- once, twice, and once more by bounding only one route -- and right once by execution. It is stated as an argument for the witness rather than for the enumeration, which is what the record now supports. --- docs/plans/M5-technical.md | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index bd6857780..e9ec18946 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -2472,11 +2472,11 @@ are these: **This bound rests on two claims and not on one**, and both are stated so a later change fails against them rather than around them: the rule that quiesce admits only into `:active`, which keeps the acquisition callback out - of the wait; and this enumeration, that no ready callback reaches - `commit_internal_result/2` more than three times. The executed-count witness - below is what holds the second to a number — and it has now been wrong twice - by reading and right once by execution, which is the whole argument for - requiring the witness. + of the wait; and this enumeration over **both** commit routes, that no ready + callback commits more than three times. The executed-count witness + below is what holds the second to a number — and it has now been wrong three + times by reading and right once by execution, which is the whole argument + for requiring the witness rather than the enumeration. - **Phase 5 is three at worst.** A head read, then the `advance_owner`, then, only where that answers `commit_unknown`, **one** `transaction_status` query. - **And the drain retries nothing, which is a change to the coordinator rather @@ -4763,7 +4763,7 @@ line; M5 introduces none of its own. | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | | Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | | Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | -| Phase 2, abort admission | a fixed **210 s** — seven sequential Store calls at the adapter's own 30 s `@call_timeout`: the six of the deepest callback a **ready** coordinator may be running — `close_execute_result_reserve/3`, which commits the executor fact, then an unproved tool result where that fact's commit was refused, then the run terminal, each re-presented once — and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. It rests on two claims — quiesce admits only into an `:active` entry, so the acquisition callback is never what an admission waits behind, and no ready callback reaches `commit_internal_result/2` more than three times | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `:5336-5351`, `:5353-5364`, `:5396-5400`, `control.ex:575-591` | +| Phase 2, abort admission | a fixed **210 s** — seven sequential Store calls at the adapter's own 30 s `@call_timeout`: the six of the deepest callback a **ready** coordinator may be running — `close_execute_result_reserve/3`, which commits the executor fact, then an unproved tool result where that fact's commit was refused, then the run terminal, each re-presented once — and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. It rests on two claims — quiesce admits only into an `:active` entry, so the acquisition callback is never what an admission waits behind, and no ready callback commits more than three times, counting **both** the `commit_internal_result/2` route and the `apply_transaction/3` admission route | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `:5336-5351`, `:5353-5364`, `:5396-5400`, `control.ex:575-591` | | Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | | Phase 4, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`), concurrent across **every** enumerated coordinator; it runs **before** the fence, so the fence races no live **writer** — at most the one transaction the serial lane may already have delivered, which its stale handling covers | Core's existing child specification | | Phase 5, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | From 41d0bdeef4d11331b5a68ecc42198f2056d23ef7 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 16:28:27 -0700 Subject: [PATCH 162/585] plan(M5): say the three-commit shape is derived until its witness runs The phase-2 witness row read as though the reserve-completion callback committing three times had been traced. It has not: a review traced every coordinator callback across the cancellation and agent-loop suites and saw at most two commits in one callback, because no existing case refuses the executor fact's commit. The row now says the witness is what first constructs that state, and that the count stays derived until it runs. --- docs/plans/M5-technical.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index e9ec18946..bd9e18a80 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -390,7 +390,7 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | --- | --- | --- | --- | --- | | Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | | The two history-paged kinds, at **fixed** sizes, so the claim that they have no constant is itself checked | `session.attach` over an empty session asserting **1**, and over an eight-event session asserting **2**; `session.resume` of a **twelve-record, eight-event** session asserting **11**, in the traced order, including **two** `transact` calls — the staged owner attempt and the advance | `apps/loopex/test/runtime_quiesce_test.exs` | `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls` | fast | -| Phase 2, seven calls | A drained abort admitted behind **the real deepest callback**: a run is driven to an execute-result reserve and that reserve closed, so `close_execute_result_reserve/3` commits the executor fact, the unproved tool result and the run terminal in **one** callback. The fact's commit is **refused** — the controllable store's `refuse_next_record(store, "executor_receipt_committed")` — which is what keeps the run at `effect_dispatched` and makes the second commit run at all; each commit is made to answer `commit_unknown` once, for six calls, and the drained abort is admitted behind them. Asserts **seven**, and asserts the six belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. Two more pin the ceiling over **both** commit routes: the same reserve callback with the fact's commit **succeeding** asserted to commit **twice**; and an **abort admitted against a run with an open model attempt**, whose reply path runs `begin_admitted_cleanup/1` into the model settlement, asserted to commit **twice and stop there** — four adapter calls, fewer than the reserve route's six, which is what makes the reserve route the bound | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops` | fast | +| Phase 2, seven calls | A drained abort admitted behind **the real deepest callback**: a run is driven to an execute-result reserve and that reserve closed, so `close_execute_result_reserve/3` commits the executor fact, the unproved tool result and the run terminal in **one** callback. The fact's commit is **refused** — the controllable store's `refuse_next_record(store, "executor_receipt_committed")` — which is what keeps the run at `effect_dispatched` and makes the second commit run at all; each commit is made to answer `commit_unknown` once, for six calls, and the drained abort is admitted behind them. No existing case reaches this state — a review traced every callback across the cancellation and agent-loop suites and saw at most two commits in one callback — so this witness is what first constructs the three-commit shape, and the count is derived until it runs. Asserts **seven**, and asserts the six belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. Two more pin the ceiling over **both** commit routes: the same reserve callback with the fact's commit **succeeding** asserted to commit **twice**; and an **abort admitted against a run with an open model attempt**, whose reply path runs `begin_admitted_cleanup/1` into the model settlement, asserted to commit **twice and stop there** — four adapter calls, fewer than the reserve route's six, which is what makes the reserve route the bound | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops` | fast | | Phase 5, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | All three are **core** witnesses, because all three paths are core's: the From a36232b512ab8337957da135760a726d22151816 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 16:38:25 -0700 Subject: [PATCH 163/585] plan(M5): bound the status read, name the fence's one writer Three sentences from the tenth review pass. The settled surface is read through the coordinator's own session_status call, which carries a 5 s bound the drain does not set; any answer that is not ok now reads as not settled, which fails closed, and a witness holds one commit past that bound. The awaiting-owner-barrier row named the owner group as what could still write; no owner group or worker can commit, and the one writer the fence refuses is the dead coordinator's at-most-one delivered transaction. The census-purity claim is scoped to an idle stop, since a crashed drain task's termination report also reaches stderr and names no fatal class. --- docs/plans/M5-technical.md | 25 ++++++++++++++++++++----- 1 file changed, 20 insertions(+), 5 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index bd9e18a80..a21247349 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -3535,7 +3535,7 @@ carried: it described three outcomes and returned none of them. | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes, always.** An earlier revision let this be the `:not_needed` case on the reading that such an entry never had a coordinator. It can have had one: `unavailable_owner/3` (`:1149-1158`) writes `%{status: :unavailable, durable: nil}` with **no coordinator key**, and one of its callers reaches it at `:1134` *after* terminating a coordinator that had already been started (`:1132`). The absent key proves nothing about the past, so every `:unavailable` entry is fenced | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | - | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when phase 1b proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes, and the fence is what makes it safe.** Its coordinator is already gone, so phase 4 has nothing to terminate; what could still write is the **owner group that outlived it**, and phase 6's kill does not answer that — `Process.exit(sup, :kill)` ends the root only, and a trapping `OwnerGroup` unwinds on its own clock afterwards, into a Store phase 7 keeps open. Phase 5's moved epoch is what refuses those commits `:stale_owner_epoch`. An earlier revision credited the kill | + | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when phase 1b proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes, and the fence is what makes it safe.** Its coordinator is already gone, so phase 4 has nothing to terminate; what could still write is **the dead coordinator's at-most-one already-delivered transaction** — the same case every other fenced row rests on — and nothing else, because no owner group or worker can commit: `Store.transact` has one caller in core (`store/owner_lane.ex:121`), and `OwnerLane.transact` is called only from the coordinator (`session_coordinator.ex:1242`, `:1363`, `:1761-1762`) and `Control` (`control.ex:1680-1681`). The owner group that outlived the coordinator unwinds on its own clock past phase 6's kill, which ends the root only, but it writes nothing. Phase 5's moved epoch is what refuses that one transaction `:stale_owner_epoch`. An earlier revision credited the kill, and the one before it named the owner group as a writer | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No — the **only** `:not_needed` case, and it is read from the fresh enumeration phase 4 takes, never from the phase-2 snapshot | | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | | **A phase-5 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | @@ -3565,7 +3565,18 @@ carried: it described three outcomes and returned none of them. answers that must differ are therefore the aborted run present and the aborted run absent**, and the owner the call requires is the one quiesce read from `Control`'s enumeration, which is why that enumeration carries - it. + it. That read carries the coordinator's own bound, not the drain's: + `session_status/2` is `safe_call(coordinator, …, @session_status_timeout_ms)` + at 5,000 ms (`session_coordinator.ex:164`, `:181-182`), and quiesce reads + it at budget expiry, when a coordinator that has just cancelled may be + inside the cleanup callback whose commits are each bounded at 30 s. Any + answer that is not `{:ok, …}` — a `:session_unavailable` refusal or the + timeout — is read as **not settled**, which fails closed: the session is + `unsettled`, terminated and fenced, and nothing false is journaled. The "it + settles" witness therefore holds the Store fast enough for the read to + answer, and a witness beside it holds one commit past 5 s and asserts the + session lands in `unsettled` with its terminal still committed by the + coordinator before phase 4 ends it. No core change is needed for this, which is worth saying plainly after several rounds of adding things: the read exists, quiesce is outside @@ -3984,9 +3995,13 @@ one line and no class: a census naming `drain_id`, `budget_ms`, the three counts quiesce returned and, for every session it left `{:unknown, head}`, that session's id with the `owner_epoch` and `journal_version` its fence read — the values a successor compares against, and the only part of the census -that is recovery data rather than a count. That line is the only thing an ordinary stop writes -to `stderr`, and it names no fatal class, which is what a reader checks it -for. +that is recovery data rather than a count. That line is the only thing an +idle stop writes to `stderr`, and it names no fatal class, which is what a +reader checks it for. A stop with work in flight may add one more thing: a +drain task that crashes is an `async_nolink` child of the runtime's worker +supervisor, and its termination report goes through Logger to `stderr`. That +report accompanies the census line, names no fatal class, and changes no exit +status; the daemon's log rule bounds it as it bounds every other line. **Reverse cleanup.** Startup happens inside the owner, so a failure at any step unwinds what that step and its predecessors did, in reverse — and From aa78dc60bcca7f88d4f5d041d33fd091331a6b4a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:21:50 -0700 Subject: [PATCH 164/585] plan(M5): the drain is a contract, not an arithmetic Maintainer decision of 2026-09-20 (D1). Three revisions of this pair derived the graceful-stop bound by counting sequential Store calls per phase and summing them. That derivation was corrected in four consecutive reviews -- once for a missed paging call, once for a missed commit, once for taking a callback the drain never waits behind, once for bounding one of two commit routes -- and every correction moved a number the plan had already published. The approach is withdrawn. The lifecycle and quiesce sections now state the **order** of the stop and the **guarantee** at each step, and state no per-step seconds and no total. The eight-phase table, the sums, the per-kind depth tables, the ceiling arguments and the phase-numbered prose are deleted; the steps keep their names and their order. Two numeric bounds survive because neither is derived from a drain: the fail-stop's 35 s, and the Store stop's fixed 30 s, which is the adapter's own `@call_timeout`. What the contract now says: the cut closes admissions with one acknowledged state change, after which **every** request -- reads and transfers included -- is refused `daemon_stopping` by a synchronous admission-state check the connection layer performs before dispatch; the ten state-changing calls carry tickets; already-admitted tickets are awaited for a bound the implementation measures, after which the stop proceeds. Cleanup is released only when every admission is durably decided, and if any is ambiguous no cleanup is released for any session. Settled means the aborted run's terminal fact is committed. Termination reaches every enumerated coordinator before any fence, over a fresh enumeration, both bounded by one deadline the implementation measures -- and "concurrent" means issued together, not served together, since `DynamicSupervisor.terminate_child/2` serialises through the one supervisor. The operator-page obligation becomes a closure item carrying the **measured** figure, and the executed-count rule stays as the implementation's obligation rather than as a planning claim. --- docs/plans/M5-technical.md | 672 +++++++++++-------------------------- docs/plans/M5.md | 56 ++-- 2 files changed, 223 insertions(+), 505 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index a21247349..1e62106dc 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as **phase 1a**, one synchronous call in which the relay closes admissions and answers at once, followed by **phase 1b**, the owner's bounded wait for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* 1a is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past 1b's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the 1a acknowledgement returns while a prompt commit is still in flight, which a five-second cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running stop phases 2 to 5 — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fresh phase-4 enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during phase 7 while the Store is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its four parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fresh phase-4 enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -292,23 +292,15 @@ provider configuration. because both are facts an operator cannot derive from the software and a reviewer can check against this sentence at closure. -- **`docs/operator/daemon.md` must state the maximum graceful stop as the sum - of the eight phase bounds**, in the form the lifecycle section fixes: - **`budget_ms` + 645 s**, being 5 s for closing admissions, 300 s for - settling what was already admitted, 210 s for abort - admission, `budget_ms` for cancellation, 5 s for coordinator termination, - 90 s for the fence, 5 s for daemon teardown and 30 s for the Store — - together with the sentence that keeps the number from being read as a - duration: **four** of the seven fixed terms — 1b, 2, 5 and 7 — count the - Store's thirty-second ceiling for a wedged filesystem, **one** — phase 4 — - is the coordinator's own shutdown value, and the remaining **two**, the five - seconds for closing admissions and the five for the teardown, are this - plan's own chosen numbers, which the page says rather than implying every - term is derived — and an ordinary stop finishes in milliseconds — - with the seven constants written out beside the one derived term, so an - operator setting a `TimeoutStopSec` adds up numbers rather than trusting a - total. It must say that seven of the eight are fixed and - that the drain term alone is **not** read off the daemon's own +- **`docs/operator/daemon.md` must state the maximum graceful stop, and the + figure it states is the one the implementation *measures*** — not one this + plan derives. The maintainer withdrew the derived sum on 2026-09-20 for the + reason the lifecycle section gives, so this row carries the obligation + instead of the number: at closure the page names the measured maximum, the + conditions it was measured under, and the two bounds this pair does fix + beside it — the **fail-stop** exit at **5 s + 30 s = 35 s** and the **Store + stop's** fixed **30 s**. It must also say that the measured figure is + **not** read off the daemon's own `--cleanup-grace-ms`, because each session drains under the grace it committed and a root may carry sessions composed earlier, so the page must point an operator at the figure the daemon **reports in its stop line** @@ -349,7 +341,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during phase 2 is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the phase-4 enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during phases 2 and 3`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `a phase-2 task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the phase-4 enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during phases 2 and 3`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -388,10 +380,6 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and | Bound | What the case executes and counts | File | Case | Lane | | --- | --- | --- | --- | --- | -| Phase 1b, ten calls | A fresh `session.create` driven to its reply, asserting **nine** adapter calls in the traced order and **ten** when the genesis commit is made to answer `commit_unknown` once | `apps/loopex/test/runtime_quiesce_test.exs` | `a fresh create executes nine store calls, ten with the retry` | fast | -| The two history-paged kinds, at **fixed** sizes, so the claim that they have no constant is itself checked | `session.attach` over an empty session asserting **1**, and over an eight-event session asserting **2**; `session.resume` of a **twelve-record, eight-event** session asserting **11**, in the traced order, including **two** `transact` calls — the staged owner attempt and the advance | `apps/loopex/test/runtime_quiesce_test.exs` | `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls` | fast | -| Phase 2, seven calls | A drained abort admitted behind **the real deepest callback**: a run is driven to an execute-result reserve and that reserve closed, so `close_execute_result_reserve/3` commits the executor fact, the unproved tool result and the run terminal in **one** callback. The fact's commit is **refused** — the controllable store's `refuse_next_record(store, "executor_receipt_committed")` — which is what keeps the run at `effect_dispatched` and makes the second commit run at all; each commit is made to answer `commit_unknown` once, for six calls, and the drained abort is admitted behind them. No existing case reaches this state — a review traced every callback across the cancellation and agent-loop suites and saw at most two commits in one callback — so this witness is what first constructs the three-commit shape, and the count is derived until it runs. Asserts **seven**, and asserts the six belonged to **one** callback, which is what makes the unit the callback rather than the call. A second case asserts the acquisition callback is never what an admission waits behind, by driving a session that is still `:acquiring` and asserting **no abort is admitted for it**. Two more pin the ceiling over **both** commit routes: the same reserve callback with the fact's commit **succeeding** asserted to commit **twice**; and an **abort admitted against a run with an open model attempt**, whose reply path runs `begin_admitted_cleanup/1` into the model settlement, asserted to commit **twice and stop there** — four adapter calls, fewer than the reserve route's six, which is what makes the reserve route the bound | `apps/loopex/test/runtime_quiesce_test.exs` | `a drained abort admitted behind a refused executor fact spends seven store calls in phase 2`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops` | fast | -| Phase 5, three calls | A fence run to `commit_unknown` and resolved, asserting **three** — head, advance, status | `apps/loopex/test/runtime_quiesce_test.exs` | `a fence executes three store calls at worst` | fast | All three are **core** witnesses, because all three paths are core's: the daemon contributes no Store call of its own to any of them. A case that @@ -1633,7 +1621,7 @@ as though it does: whatever its method** — transfers included, and reads included, the refusal being about the daemon's state and not about what the request would have done. A transfer already in flight when the cut answers either completes on - its own or ends in phase 6 with its connection: the connection process ends, + its own or ends in the teardown with its connection: the connection process ends, core change 1's monitor drops its attachment, and the transfer state goes with the attachment it was hanging from. Nothing about it is durable and nothing about it can disturb the drain. @@ -1750,14 +1738,14 @@ as though it does: - **The admission cut is the relay's, because the relay is the only process that can answer for all ten.** The owner calls it once at the start of an orderly stop and the relay **stops admitting and answers at once** — that is - phase 1a, and it promises nothing about work already inside core. The wait - for that work is **phase 1b**, which is bounded and then **proceeds**. + the **cut**, and it promises nothing about work already inside core. The + wait for that work is separate, bounded, and then **proceeds**. An earlier revision said here that the cut "answers only when every ticket - it holds has settled". That was the design phase 1a and 1b replaced, and + it holds has settled". That was the design the bounded wait replaced, and leaving the sentence standing gave this file two cut semantics — one that - waits unconditionally and one that proceeds at a bound — with the witnesses - and the phase table written against the second. One stands: **1a closes, 1b + waits unconditionally and one that proceeds at a bound — with every witness + written against the second. One stands: **the cut closes, the wait waits, 1b proceeds.** What the cut buys is therefore narrower than that sentence claimed, and it @@ -1822,12 +1810,12 @@ the registry — and then **the Store, last of all**, out of reverse order. The lease owners go before the relay because the relay is what holds their tickets, and stopping it first would discard a ticket an owner could still be waiting on. They are stopped -as **one collective sweep, not one at a time**, against phase 6's deadline: +as **one collective sweep, not one at a time**, against the teardown deadline: up to 512 of them exist, and 512 sequential stops inside a five-second phase is arithmetic that does not work. The sweep — every stop sent at once, one wait for all of the exits, a kill for whatever is left at the phase's end — and the disposition of a lease owner killed that way are written out with -phase 6 below. The +the teardown below. The Store is moved to the end because its `terminate/2` releases the writer marker, and the marker must outlive every operation the owner can end; custody and registry hold nothing durable, so stopping them before it costs @@ -1868,7 +1856,7 @@ step 3's clean return as `runtime_lost` — a daemon that could never exit `0`, idle-shutdown witness that could never pass. So the owner carries a `stopping` field naming **the component it is -currently stopping** — one pid at every step but phase 6's lease-owner sweep, +currently stopping** — one pid at every step but the teardown's lease-owner sweep, where it names that step's set of pids — set immediately before each stop call. The EXIT clause reads: @@ -1990,7 +1978,7 @@ waiting for is the one that made it dead, already queued. It is a wait for a signal that exists, not a second bound. **Other messages wait their turn.** Both receives are selective on the pid -this step is stopping — on the set of them, in phase 6's lease-owner sweep, by +this step is stopping — on the set of them, in the teardown's lease-owner sweep, by the same discipline read over a set — so an exit from another component, a client's frame, or anything else stays in the mailbox and is read when the owner returns to its loop. Nothing is @@ -2238,360 +2226,117 @@ between the owner's death and the monitor's `DOWN` being handled. In both routes the class is `owner_lost` on `stderr`, and it is the one class no linked component produces. -**Eight phases, each with a named bound, and the stop is their sum.** Earlier -revisions called this "three clocks" and then let two of them overlap: the -drain budget was the largest cancellation backstop — at the smallest admitted -grace that is already **22,001 ms** (`cancellation_bounds/1`, -`apps/loopex/lib/loopex/executor.ex:456-474`) — fencing began *after* it, and -the five-second teardown was expected to absorb a sequential stop of up to 512 -lease owners and a Store call that can itself block 30 s -(`apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111`). None of that -adds up. The contract is now one phase at a time, each bounded by a number -that already exists somewhere, and the operator maximum is the sum: - -| # | Phase | Bound | Where the number comes from | -| --- | --- | --- | --- | -| 1a | **Close admissions** | **5 s**, this plan's teardown number reused | A synchronous acknowledgement of a **state change**, not of any work: the relay sets a flag, refuses everything after it, and answers. It has nothing to finish, so this bound measures the relay's own responsiveness and nothing else; a relay that does not answer inside it is a relay the daemon has lost, and the stop becomes the `relay_lost` fail-stop | -| 1b | **Settle the admitted** | **300 s** — **ten** Store calls deep, the deepest ticket kind, counted from a traced run rather than from the code; **per phase, not per ticket**, the tickets settling concurrently | The tickets already inside core when 1a answered. The per-kind derivation is below, and at this bound the stop **proceeds** rather than waiting further | -| 2 | **Abort admission** | **210 s** — **seven** Store calls deep, at 30 s each; **per phase, not per session**, because the sessions are admitted **concurrently** | The admission waits behind the **callback** a **ready** coordinator is already running, which is at most three commits and so six calls, and then makes its own, which is one | -| 3 | **Cancellation** | The derived backstop: `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms` | Core's own number for how long a cancellation may take | -| 4 | **Coordinator termination** | **5 s**, the coordinator's own `shutdown` (`session_coordinator.ex:134-142`); **per phase, concurrent** across **every** enumerated coordinator | The value core already gives a coordinator to stop in — and a ceiling nothing approaches, because a coordinator does **not** trap exits (`init/1` sets no flag, `session_coordinator.ex:260-292`, and the module's only `Process.flag(:trap_exit, true)` is at `:3108-3109`, inside the per-invocation provider guard it spawns), so it has no `terminate/2` to run and dies at once | -| 5 | **Fence** | **90 s** — **three** Store calls deep at worst, again **concurrent** across sessions | A head read, then the `advance_owner`, and on `commit_unknown` one `transaction_status` query. Three sequential calls, no retries | -| 6 | **Daemon teardown** | **5 s** | One of this plan's two chosen numbers, covering the notice, the closes, the lease owners, the relay, **the runtime tree** and the edges. The runtime stop is attempted with what remains and killed at the bound; its trapping descendants unwind afterwards on their own clock, which the daemon does not wait for | -| 7 | **Store** | **30 s**, its own `@call_timeout` | The stop that releases the marker | - -> **Maximum graceful stop = 5 s + 300 s + 210 s + `budget_ms` + 5 s + 90 s + -> 5 s + 30 s = `budget_ms` + 645 s**, and `budget_ms` is the one term an -> operator cannot compute in advance. - -**That is a worst case nobody approaches, and saying so is part of stating -it.** Every term but `budget_ms` is a count of the local adapter's 30 s -`@call_timeout`, and that timeout is a ceiling for a wedged filesystem, not a -cost: the calls it bounds are a `File.read`, an append and a directory sync, -microseconds apiece on a working disk. An ordinary stop of an idle daemon -finishes in milliseconds. The sum is what a `TimeoutStopSec` must not be -shorter than if a stop is never to be cut off, not what a stop takes. - -**Every phase bound is a Store-call count, and an earlier revision counted -one where the sequence is two or three.** *Every* call into the local adapter -is the same 30 s: `transact/2` at `local.ex:111-113`, `ownership_head/3` at -`:130-132` and `transaction_status/4` at `:116-122` all pass `@call_timeout` -(`:65`). So a phase's bound is not "30 s because it is a Store call"; it is -**(the worst sequential count of Store calls in it) × 30 s**, and the counts -are these: - -- **Phase 1b is ten, and the derivation is per ticket kind.** A ticket settles - when its core call answers, and what that call does before answering is not - the same for all ten. Counted from the code, in sequence: - - | Ticket kind | Sequential Store calls before the ticket settles | Where | - | --- | --- | --- | - | The seven non-resume lease-authorized mutations — `prompt`, `steer`, `follow_up`, `abort`, `respond_interaction`, `admit_resources`, `activate_skill` | **2** | One `OwnerLane.transact/2`, retried once on `commit_unknown` (`session_coordinator.ex:1752-1768`). The wait-behind does **not** apply: this call *is* the session's one in-flight transaction, and the coordinator's `command/3` waits `:infinity` for it (`:146-149`) | - | `session.create`, fresh | **9**, or **10** with the one retry | Traced, not counted by eye — see below | - | `session.attach` | **1 + ⌈events ÷ 1,024⌉** — traced at 1 over an empty session and 2 over eight events | The dispatcher's snapshot scan pages the session's events (`event_dispatcher.ex:169-199`, `:926`) | - | `session.resume` | **no constant**, and traced at **11** over a twelve-record, eight-event session | `Store.runtime_command` (`control.ex:310`), then `load_records` ×2, `transaction_status` (`:1324-1335`), `ownership_head`, **`transact` ×2** — the staged owner attempt `owner_stage_tx` (`:1162-1167`) and then the advance (`:1363`) — then `load_records` ×2 and `load_events` ×2 | - - **A fresh create executes nine adapter calls, and the earlier figure of six - was a reading of the code rather than a run of it.** Two errors, both of - them the kind only execution finds: - - 1. **`load_pages/4` always makes a terminating empty-page call.** It recurses - while a page comes back non-empty and returns on `{:ok, []}` - (`session_coordinator.ex:7090-7114`), so `load_all_records` over a session - that holds its genesis record is **two** calls, not one — a page with the - row, then a page without. An earlier revision counted one, having assumed - a fresh session reads empty; it does not, because the genesis record is - already there. - 2. **The genesis commit was never counted at all.** - `create_session/2` calls `create_command_absent?/2` — one - `Store.runtime_command` (`control.ex:959-965`) — and *then* - `Store.create_session/3` with `resolve_transaction/2` - (`:896-897`, `:1679-1684`), which is a second adapter call and which - retries once on `commit_unknown` at `:1681`. Two calls inside `Control` - before the coordinator is started at all. - - The executed sequence, in order: `runtime_command`, `transact` (both - `Control`); then `load_records` ×2, `ownership_head`, `transact`, - `load_records` ×2, `load_events` (the coordinator reaching `:ready` — - `:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`; `load_events` is one - because a fresh session has no events yet). **Nine, or ten with the retry.** - - **The maximum over the kinds whose depth is a constant is ten**, which is a - fresh create — constant because a fresh session holds exactly its genesis - record and no events, so its two `load_records` and one `load_events` are - fixed. So 1b is bounded at ten calls — **300 s**. - - **Two kinds have no constant depth**, attach and resume, both paging over - the root's history at 1,024 rows a call. And the resume trace is worth - reading rather than filing: a **twelve-record, eight-event** session — a - small one by any measure — already executes **eleven**, one more than the - bound. That is not an argument for raising the bound to cover it, because no - number covers a session whose history is unbounded; it is the plainest - possible demonstration that **1b is a bounded wait that then proceeds**, and - that the `:acquiring` row in the classification table is an ordinary - outcome rather than a remote one. An operator whose daemon is stopping with - resumes in flight should expect the stop to reach 1b's bound and go on. -- **Phase 2 is three, and the unit that blocks is the callback rather than the - call — of a coordinator that is *ready*.** The abort admission goes to a - coordinator through `SessionCoordinator.command/3`, a `GenServer` call - (`session_coordinator.ex:146-149`): what it waits behind is not one Store - transaction but **whatever callback that coordinator is currently running**, - to completion. A callback can make more than one adapter call, so the - question is which callbacks the admission can actually meet. - - **It can only meet a ready coordinator's, and that is a rule rather than an - observation.** Quiesce admits an abort **only into a session whose `Control` - entry is `:active`**, which `Control` writes at the instant the owner is - ready and not before (`control.ex:575-591`: the entry is `:acquiring` until - `owner_ready` replaces it with `status: :active` at `:579` and replies to the - waiting caller at `:590`). A session still acquiring has no ready - coordinator, no active run and therefore **nothing to abort**: quiesce - admits nothing for it, and it is terminated and fenced exactly as an - unsettled session is. That is the ordinary outcome of phase 1b proceeding at - its bound, not an exception to anything — the `:acquiring` row in the - classification table is where it lands. - - **That matters because the acquisition callback is enormous and the ready - ones are not.** `handle_continue(:acquire_owner, …)` (`:378`) runs - `advance_acquisition/1` (`:1142-1145`) into `discover_and_advance_owner/1` - (`:1186-1203`), `transact_owner/1` (`:1362-1395`) and - `recover_committed_owner/1` (`:1397-1426`) **without returning**: three - paging loops (`:1303`, `:1399`, `:1400`, each `load_pages/4` at - `:7090-7114`, `@page_size 1_024` at `:49`), a `transaction_status`, an - `ownership_head` and a commit, and it may re-enter itself up to - `@max_historical_attempts` — **1,024** (`:83`). An earlier revision took - *that* callback as phase 2's wait-behind and called it three calls, which - under-counted it by an unbounded factor while over-counting what phase 2 - actually waits for. Both errors are fixed by admitting only into `:active`. - - **The ready coordinator's callbacks, traced.** Every adapter call this - module makes is at one of nine sites, and they divide cleanly: - - **The enumeration below is over the calls this module makes; the bound needs - the calls made in the coordinator's *process*.** Those differ if a - coordinator callback calls out to something that reaches the Store itself. - The table is what makes the claim checkable by reading; what makes it true - is the **executed count**, and the phase-2 witness below is where it is - measured rather than argued. - - | Site | Callback | On the ready path? | - | --- | --- | --- | - | `transaction_status` `:1214`, `OwnerLane.transact` `:1242`, `runtime_command` `:1265`, `transaction_status` `:1325`, `ownership_head` `:1338`, `OwnerLane.transact` `:1363` | acquisition only | **no** | - | `load_records` `:7077`, `load_events` `:7088` | reached only from `discover_prior_tx_id/1` (`:1303`) and `recover_committed_owner/1` (`:1399-1400`) | **no** | - | `OwnerLane.transact` `:1761-1762`, inside `resolve_transaction/2` | every ready commit, through `apply_transaction/3` (`:1702`) or `commit_internal_result/2` (`:6423`) | **yes** | - - So **no ready callback pages**, the two paging helpers having no caller - outside acquisition, and every ready commit is **one adapter call, or two** - where `resolve_transaction/2` re-presents on `commit_unknown` - (`:1752-1768`). - - **A ready callback commits three times, and two earlier revisions said - once and then twice.** The first - argued that a committing callback ends by sending itself - `:advance_work` and so cannot continue — which is true of - `apply_transaction/3`, where that send sits (`:1720`), and of nothing else: - the module has **thirteen** such sends (`:465`, `:627`, `:1425`, `:1720`, - `:1996`, `:2237`, `:2249`, `:4013`, `:4051`, `:4078`, `:5894`, `:6304`, - `:6775`), and reaching one is not the same as reaching it *before* the - callback's second commit. There are **fifteen** paths into - `commit_internal_result/2`: the thirteen `commit_internal/2` call sites and - the two into `retain_terminal_operation_fact/2` (`:4062`, `:6381`). - - **The deepest ready callback is the executor-reserve completion**, and an - earlier revision named the wrong one. That revision routed the executor - fact through `settle_executor_work/2` (`:5235-5256`) — which makes **no - Store call at all**: it reads `in_flight_of/3` and local durable state and - answers `{:settled, …}` or `{:reserved, …}`. `put_executor_fact/3` is not - reached from it. The two real callers of `retain_executor_fact/3` are - `:5354` and `:6302`. - - The callback is the one that closes an execute-result reserve — - `close_execute_result_reserve/3` (`:5336-5351`) — and it can commit - **three** times: - - 1. `retain_execute_result/3` (`:5353-5364`) → `retain_executor_fact/3` - (`:6349`) → `put_executor_fact/3` → `retain_terminal_operation_fact/2` → - `commit_internal_result/2` — **the executor fact**; - 2. then `finish_settled_cleanup/4` (`:5070-5078`) → - `settle_owned_operation/3`'s `:unconfirmed` clause (`:5399-5400`) → - `commit_owned_operation_unknown/2` (`:5426-5444`, the commit at `:5437`) - — **the unproved tool result**; - 3. then `finish_cleanup/4` (`:5080-5090`) → `commit_terminal/4` - (`:2558-2563`) → `commit_internal/2` → `commit_internal_result/2` — - **the run terminal**. - - All three inside one callback, with no return in between. - - **Steps 1 and 2 are not mutually exclusive, and the comment that says they - are means something narrower.** `:5396-5398` reads: *"a run whose executor - answered and whose fact **committed** has already left `effect_dispatched`, - so this is a no-op there."* That is exclusivity for a fact that - **committed**. A fact whose commit is **refused or ambiguous** takes - `retain_execute_result/3`'s other arms (`:5356-5358`), which answer - `:unconfirmed` and leave the run at `effect_dispatched` — so step 2 runs - after step 1 has already spent its calls. The previous revision read that - comment as bounding commits when it bounds only successful ones, and a - phase bound counts **calls**, not successes. - - **There are two routes into a commit, and the ceiling has to bound both.** - An earlier revision argued only over `commit_internal_result/2` and its - fifteen paths, while the site table above names a second route — - `apply_transaction/3` (`:1702`), the **command admission** itself. A - callback can take both, and one does: - - - **The admission route reaches two.** `commit_command_proposal/2` - (`:1672-1699`) commits the admission through `apply_transaction/3` and - then, on the commit reply path, runs `begin_admitted_cleanup/1` - (`:4806-4817`). For a run with an **open model attempt** that continues - synchronously — `begin_cleanup/3`'s `"model_attempt_open"` branch - (`:4841`) → `begin_model_termination/3` (`:4861`) → - `settle_model_attempt/3` (`:4038-4056`, at `:4876`) → - `commit_model_settlement/3` (`:4048`, `:4059`) → - `retain_terminal_operation_fact/2` (`:4062`) — a **second** commit in the - same callback. It stops there: every branch of - `commit_model_settlement/3` (`:4078-4104`) ends the callback, and the - other cleanup branch reaches no synchronous commit at all, since - `dispatch_host_cancel/3` either sends itself a message (`:5010-5011`) or - spawns `async_nolink` (`:5028-5031`). - - **The reserve route reaches three**, as traced above. - - **Three is therefore the ceiling, over both routes.** Of the fifteen - `commit_internal_result/2` paths, twelve are reached by callbacks that - commit once and return. The three that can compose do so only in the - reserve-completion callback, in that order: a fact commit, an - unproved-result commit that requires the fact commit to have *failed*, and - one terminal commit that ends the run. There is no fourth, because - `finish_cleanup/4` is where the run ends and every one of its clauses - commits the terminal and returns; and the admission route adds a second - commit to a callback that then stops, never a fourth to this one. - - **Maximum over the ready callbacks: three commits, so six adapter calls.** - Plus the drain's own admission, which is **one** because it does not - retry — see the non-retrying commit below. **Seven, in sequence.** - - **This bound rests on two claims and not on one**, and both are stated so a - later change fails against them rather than around them: the rule that - quiesce admits only into `:active`, which keeps the acquisition callback out - of the wait; and this enumeration over **both** commit routes, that no ready - callback commits more than three times. The executed-count witness - below is what holds the second to a number — and it has now been wrong three - times by reading and right once by execution, which is the whole argument - for requiring the witness rather than the enumeration. -- **Phase 5 is three at worst.** A head read, then the `advance_owner`, then, - only where that answers `commit_unknown`, **one** `transaction_status` query. -- **And the drain retries nothing, which is a change to the coordinator rather - than a statement about it.** Core's ordinary commit path retries a - `commit_unknown` once — `resolve_transaction/2` re-presents the transaction - on the second line of its own case (`session_coordinator.ex:1752-1768`) — - and an earlier revision said the drain's abort "is not retried" while also - saying the admission path was "otherwise untouched". Those cannot both hold: - a drained abort that took the ordinary path **would** retry. So the drain's - abort admission commits through a **non-retrying** path, and that is the - **second half of core change 4's coordinator change**, beside the - admit-and-pause split — one change with two halves, both in the same clause - of the same function, and both named in the concept pair's core-change list - and in the ownership table. A `commit_unknown` on a drained abort is - therefore ambiguous immediately: the session is fenced, by the rule this - section already states. An ambiguous **fence** is resolved by the one status - query, not re-proposed. A **stale** - fence is not reattempted at all, for the reason the fence table gives. - -**The eight phases and the six steps are two cuts through the same stop, and -the mapping is stated rather than left to be inferred.** The numbered sequence -below is what the daemon's owner *does*; the phases are what each part of it -is *bounded by*. Phases 1a and 1b are step 1: 1a is the owner's call to the -relay, 1b is the owner's wait afterwards. **Phases 2 to 5 are -inside `quiesce/1`** — they are core's to enforce, because core owns the -admission, the cancellation, the coordinator's termination and the fence, and -the daemon -passes no deadline in — and together they are step 2. Of the four, only -phase 3's actual value is returned, as `budget_ms`; the other three are fixed -numbers an operator adds to it. Phase 6 begins the instant `quiesce/1` returns -and covers steps 3, 4, 5 and the non-Store part of step 6. Phase 7 is the -Store stop at the end of step 6. Nothing is bounded twice and nothing is -bounded by nobody. - -**Who enforces a phase, since a bound with no enforcer is a wish.** Phases 2, -3, 4 and 5 are core's, and the admission and the fence cannot be bounded by -the call that does the work: a coordinator's `command/3` waits `:infinity` by design -(`session_coordinator.ex:146-149`), and must, because a timeout there is not -evidence of anything. So quiesce runs **each session's admission (phase 2) and each -session's fence (phase 5) in its own task**, and bounds the task rather than -the call: one task per session, a single `Task.yield_many/2` against what -remains of the phase's absolute deadline, then `Task.shutdown/2` for whatever -has not answered. - -**Those tasks are started `async_nolink` under the runtime's own worker -`Task.Supervisor`**, not linked to whoever called `quiesce/1`, and that -matters now that the caller is the **daemon's owner**. A linked task is an -`{:EXIT, …}` at that owner, and the owner's EXIT clause classifies any exit it -did not ask for as a **fatal class** — so one crashing drain task would take -the daemon down mid-stop with a class naming nothing real. Unlinked, a task -that dies arrives as a `DOWN` the drain handles like any other -non-answer: the session is fenced. The supervisor is the runtime root's third -child, already resolved by `RuntimeSupervisor.children/1` as `workers` -(`runtime/supervisor.ex:73`, `:104`, `:113`), so this needs no new process and -no new option — it is what that supervisor is for. That is the ordinary bounded-task idiom, it needs no new mechanism, -and it is what makes "concurrent across sessions" and "bounded per phase" -the same sentence rather than two hopes. - -What a shutdown means is decided, not left open, and the classification table -below carries both rows: - -- **a phase-2 admission that does not answer** leaves the session's abort - neither known-committed nor known-refused, which is the ambiguous case this - section already handles: **no cleanup is released for it and it is fenced**; -- **a phase-5 fence that does not answer** is exactly a fence whose outcome - the drain cannot read, so it is reported **`{:unknown, head}`** and the - domain stays fenced — the same disposition a `commit_unknown` gets, reached - by a different route; -- **phase 4 needs no task**, being `Supervisor`-shaped already: terminating a - coordinator is bounded by the `shutdown: 5_000` its own child specification - carries (`session_coordinator.ex:134-142`), which is the enforcer. - -**Shutting down a task does not cancel the call it made**, and the phase-2 -row's consequence is worth writing out rather than leaving as an -implication. `Task.shutdown/2` ends the task; the `GenServer` call that task -already delivered runs to completion in the coordinator regardless, which is -the same property that makes a dead caller's transaction commit and a dead -relay task's mutation reach core. So a phase-2 admission the drain gave up on -still **lands**: the coordinator admits the abort, writes the same -`command_admitted` record, and **pauses at the split** with no cancellation -released, because the drained path is what it is running. The drain simply -does not know which of those happened, which is why the session is fenced -rather than cancelled. - -That is the right outcome and not a regrettable one: the journal ends up with -an admitted abort and no cleanup, which is exactly what an unsettled session's -journal holds on every other route to it. What the drain must not do — release -a cancellation for a command it cannot confirm — it does not do. - -**One rule keeps a phase from starting work it cannot finish, and with the -counts above it can always be honoured.** *No Store -operation begins without at least its own 30 s remaining in its phase.* Because -each phase's bound **is** its worst sequential call count times 30 s, a phase -that has reached its *k*th call still has at least 30 s left **provided the -count is right**. That proviso is the whole of the invariant now, and it is -stated as a proviso rather than as a guarantee: an earlier revision said the -rule "never fires", which was true of a count that had missed four calls and -would have been false in practice. The rule is what catches a miscount — a -sequence deeper than the one this plan counted reaches its bound and stops -there rather than running past it — which is exactly the service it has to -perform, and the executed-count witnesses below are what keep it from being -needed. - -**The escape an earlier revision gave it is deleted, because it was -circular.** That revision said a fence with four seconds left is not attempted -and "the session is reported `fence: :not_needed` if the head already moved -and `:unknown` otherwise" — but deciding whether the head moved *is* a Store -read, which is the very thing the rule has just refused. There is no way to -take that branch. `:not_needed` now means one thing only, decided from the -fresh phase-4 enumeration without reading the Store: **a session it holds no -entry for**. Every enumerated session is fenced — settled, unsettled and -absent alike, for the reason phase 5 gives — and its entry is `:committed`, -`:superseded` or `{:unknown, …}`. - -**Phase 6 stops the lease owners as a collective sweep, not one at a time.** +**The stop is a contract, not an arithmetic.** Earlier revisions of this +section built an eight-phase table, derived each phase's seconds from a count +of sequential Store calls, and summed them into an operator bound. That +derivation was wrong four times in four reviews — once by missing a paging +call, once by missing a commit, once by taking a callback the drain never +waits behind, and once by bounding one of two commit routes — and each +correction moved a number the plan had already published. The maintainer +withdrew the approach on 2026-09-20: **the plan states what the drain +guarantees and how each guarantee is proved; the implementation measures what +it costs.** + +So this section fixes the **order** of the stop and the **guarantees** at each +step, and states no per-step seconds and no total. What replaces the published +sum is a closure obligation: the operator page carries the **measured** +maximum graceful stop, taken from the implementation, and the implementation +states every bound it uses as an **executed count** under the rule the +verification section keeps. Two numeric bounds survive here because neither is +derived from a drain: the **fail-stop** exit at **5 s + 30 s = 35 s**, and the +**Store phase's fixed 30 s**, which is the adapter's own `@call_timeout` +(`apps/loopex_store_local/lib/loopex/store/local.ex:65`) and the one stop whose +`terminate/2` releases a durable exclusion. + +**What the cut guarantees.** The owner calls the relay, which closes +admissions and acknowledges that **state change** — one synchronous +acknowledgement, not a wait for work. After the acknowledgement **every +request on an open connection is refused `daemon_stopping`, whatever its +method**: the ten state-changing calls, the queries, and ADR 0023's three +artifact-transfer methods alike. That refusal is a **synchronous +admission-state check the connection layer performs before it dispatches +anything**, not a property of the relay's ticket set — an earlier revision +gated only the ticketed methods and left reads and transfers entering core +after a cut that claimed to have closed it. + +The ten state-changing calls carry tickets, and the tickets already inside +core when the cut answered are **awaited for a bound the implementation +measures**, after which **the stop proceeds**. It does not wait for them to +settle: an earlier revision said the cut "answers only when every ticket it +holds has settled", which a resume paging a long history can defeat, and which +contradicted every witness written against the bounded wait. What proceeding +costs is stated where the classification is: a ticket still running leaves its +session `:active` or `:acquiring`, and both are classified and fenced. + +**What the abort admission guarantees.** Quiesce admits the existing abort +command — a fresh core-minted command ID, and a commit that is **presented +once** rather than re-presented on an ambiguous answer, the two halves of core +change 4's coordinator change — and it admits **only into an `:active` +entry**, `Control` writing that status at the instant an owner is ready +(`control.ex:575-591`). A session that is not `:active` has no ready +coordinator and no run to abort. + +**The invariant is global, and it is the one the Concept promises.** +Cancellation is released **only when every admission is durably decided**. If +any admission is ambiguous or unanswered, **no cleanup is released for any +session**: the census is terminated and fenced instead. An earlier revision +released cleanup per session once that session's own admission resolved, which +makes "every abort durable before any cancellation begins" true one session at +a time and false across the daemon — the thing the split exists to prevent. + +**What settlement means.** A session is `settled` exactly when the run the +drain aborted has its **terminal fact committed**, read on the coordinator's +`{:session_status, owner}` reply (`session_coordinator.ex:414-442`), where a +committed terminal means the run appears in neither `active_run_id` (`:421`) +nor `pending_work_ids` (`:425-426`). That read carries its own five-second +bound and **any answer but `{:ok, status}` means not settled** — a coordinator +that refuses, times out or is gone is not a settled session. An abort answered +`rejected_no_active_run` (`session_state.ex:1750-1761`) is `settled`: there +was nothing to cancel and nothing is owed. + +**Then termination, then the fence, over a fresh enumeration.** Every +enumerated coordinator is terminated and every `DOWN` awaited **before** any +fence commits, so no fence races a live writer; the enumeration is taken again +at that point rather than reused from the admission step, because `Control` +keeps serving while the drain runs and an entry can appear during it. Both are +bounded by **one absolute deadline the implementation measures**, and +"concurrent" means **issued together, not served together**: +`DynamicSupervisor.terminate_child/2` is a call into the **one** session +supervisor, so terminations queue behind each other there — two children that +take half a second each cost about a second, not half of one. The plan says so +rather than implying a parallel stop the supervisor cannot give. + +**What the fence guarantees.** One `advance_owner` per enumerated session, +its identity derived from `(session_id, expected_owner_epoch, +expected_journal_version)` so a successor can recompute it, and after it no +transaction for that session can commit — the epoch has moved and the adapter +refuses it `:stale_owner_epoch` (`state.ex:548-551`). A **committed** fence +**preserves the classification the session already had**: a settled session +stays `settled`, an unsettled one stays `unsettled`. An earlier revision's +table reported every committed fence as `unsettled`, which contradicted the +settled-and-fenced case two paragraphs above it. A fence refused stale is +**not reattempted and not reconciled from the journal**: the session is +reported `unsettled` with `fence: :superseded`, which is the conservative +answer and costs no further Store call. A fence answering `commit_unknown` is +resolved by one `transaction_status` query under the same derived identity, +and if still unknown is reported `{:unknown, head}` with the head it read. + +**One residual is stated rather than closed**, and it covers both +activation-capable calls: `session.create` and `session.resume` each make +Store calls before the entry that makes a session enumerable is written +(`control.ex:959-965` and `:896-897` before `await_owner/9` at `:1176-1195`; +`:310` before `:1030` and `:1189`). A call inside them is invisible to any +enumeration, so it is neither terminated nor fenced. What holds for it is +crash-equivalence: the runtime kill ends a non-trapping coordinator at once, +at most one already-delivered transaction linearizes, and it lands as an +ordinary durable fact — a genesis, an owner advance or a command admission — +with **no terminal claimed**, read as history by the next activation +(`session_coordinator.ex:1186-1203`). For a create whose client never learned +the session ID, ADR 0032's recovery by `command_id` applies in addition. A +late `session.attach` is not in this class: `begin_attach/3` requires the +entry to be `:active` already (`control.ex:1237`). + +**The teardown stops the lease owners as a collective sweep, not one at a time.** Up to 512 of them exist, and stopping them in sequence inside five seconds was arithmetic nobody did: the owner spawns one stop helper **per lease owner, all at once**, then waits in **one** loop until every one of those pids has @@ -2654,8 +2399,9 @@ is a ceiling that matters only when the filesystem is wedged, which is exactly when killing the Store mid-release is worst. The same fixed phase applies in the failed-start reverse cleanup, for the same reason. -**`teardown_ms` is phase 6's bound, `5_000`, and it is a number rather than a -formula.** An +**The teardown has one deadline covering every non-Store action after the +drain, and the implementation measures it rather than this plan naming a +number.** An earlier revision named the clock and never gave it a value, which left the operator bound unstatable and every "what remains" reference undefined. Five seconds is **chosen, not derived**: the notification writes are one @@ -2666,26 +2412,25 @@ closes the descriptors it holds — each of them milliseconds. **One process under this deadline is not like the others, and an earlier revision's justification was false for it.** That revision said "of the processes stopped here only the transfers owner runs a `terminate/2` at all", -which forgets that **step 5, the runtime stop, is inside phase 6**: +which forgets that **the runtime stop is inside the teardown**: `Supervisor.stop(runtime_supervisor, :normal, remaining)` brings down a tree whose `OwnerGroup` children trap exits, carry `shutdown: :infinity` and have a `terminate/2` that stops their own worker supervisor with `:infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`). Nothing bounds that from inside. So the rule is the one this file already argues for the kill path, applied -honestly here: **the runtime stop is attempted with what remains of phase 6 -and killed at the bound.** A tree killed that way is crash-equivalent in the +honestly here: **the runtime stop is attempted with what remains of the +teardown deadline and killed at it.** A tree killed that way is crash-equivalent in the only sense this plan ever claims — about the journal, not about processes — and its trapping descendants go on unwinding on their own clock afterwards, which the daemon does not wait for and the halt at the end of the sequence -ends. Five seconds is therefore a ceiling for the work phase 6 *performs*, not +ends. Five seconds is therefore a ceiling for the work the teardown *performs*, not a promise about what the runtime's subtree has finished, and the drain is why that is affordable: by the time step 5 runs, every coordinator quiesce could not settle has already been fenced and terminated inside core. It is recorded in the limits table with that rationale. -**Phase 6's deadline starts when phase 5 ends**, which is when `quiesce/1` -returns, and it covers every +**The teardown deadline starts when `quiesce/1` returns**, and it covers every remaining non-Store action: the stop records, the connection closes, the listener close, and every stop from the lease owners through the registry. Every helper under it is given `remaining(teardown_deadline)` and nothing @@ -2734,7 +2479,7 @@ today, so the rule is stated here: negative `after` — which is the other way `after` fails, as the 1 ms stop probe showed. - **Every wait is taken in slices of at most `@wait_slice_ms`, 60_000** — the - obligation falling on **`quiesce/1`'s own waits**, phase 3 being the only + obligation falling on **`quiesce/1`'s own waits**, the cancellation being the only bound that is unbounded by construction and core being where it is enforced; every other phase is a fixed number far inside the domain. A minute is long enough that slicing costs nothing measurable and short @@ -2821,7 +2566,7 @@ the owner fixes. microseconds — one non-blocking `send` into a buffer the daemon already holds, and one `close` — so the work is trivial; what is not trivial is doing 512 of them in sequence and then waiting for 512 process exits one - after another inside phase 6. So the owner writes and closes **all of + after another inside the teardown. So the owner writes and closes **all of them at once**, then waits **once** for every connection process to exit, killing whatever is left at the phase's end. The processes must actually end, not merely stop being written to: core change 1's monitor is what @@ -2832,7 +2577,7 @@ the owner fixes. or any other: the next daemon to prove it holds the marker removes it before binding, which is the only safe moment there is. 4. **Every lease owner stops as one sweep, then the admission relay**, inside - phase 6's deadline. Every lease vanishes with the + the teardown deadline. Every lease vanishes with the owners; the relay goes after them because it is what holds their admission tickets, and stopping it first would discard a ticket a lease owner could still be waiting on. Nothing durable is involved, and no client is left @@ -2931,10 +2676,10 @@ the owner fixes. of components. An earlier revision gave each component its own grace, which made the worst-case stop a sum nobody had written down. - **The Store's phase is separate and fixed** — phase 7, and the reason it is + **The Store's stop is separate and fixed**, and the reason it is its own phase is that it is the one stop whose `terminate/2` releases a durable exclusion, and its length has nothing to do with any session's - cancellation grace. It begins when phase 6's deadline is done with, runs + cancellation grace. It begins when the teardown deadline is done with, runs for at most 30 s, and usually finishes in milliseconds. **The residual is stated.** A Store that has not released within its 30 s @@ -2977,21 +2722,21 @@ the owner fixes. end**, which is the honest form of a claim an earlier draft overstated. On the ordinary path that is every operation. On the timeout path it is not: an orphaned owner-group worker may still be unwinding when the runtime is - killed at phase 6's bound, and it goes on unwinding **while the Store is - still alive**, because phase 7 gives that stop its own thirty seconds. + killed at the teardown deadline, and it goes on unwinding **while the Store is + still alive**, because the Store stop has its own fixed thirty seconds. **What refuses its commit is the fence, not a dead Store**, and an earlier revision had this exactly backwards. It said such a call "reaches a stopped Store and fails as it would after a VM death… a refusal, never a write", - which is false for the whole of phase 7: the Store is not stopped yet, and + which is false for the whole of the Store stop: the Store is not stopped yet, and a straggler's `session_commit` in that window would be an ordinary, - acceptable transaction. It is refused because **phase 5 has already moved + acceptable transaction. It is refused because **the fence has already moved that session's owner epoch** — every enumerated session's, settled ones included, for exactly this reason — so the adapter answers `:stale_owner_epoch` (`state.ex:548-551`). The claim survives with a different mechanism under it, and it is a stronger mechanism: it holds whether the Store is alive or not, where "the Store is gone" only ever held - after phase 7 had finished. + after the Store stop had finished. One dependency this step relies on is worth naming rather than assuming: `Loopex.Store.Local` **traps exits**, so even an owner that crashes rather @@ -3050,7 +2795,7 @@ carried: it described three outcomes and returned none of them. **Three parts, in order, and the first two are one thing split in half.** -1. **Phase 2 of the stop, the abort admission: every live coordinator admits +1. **The abort admission: every live coordinator admits the abort, and then stops.** ADR 0023 fixes that *only* the durable `session.abort` command cancels, and that cancellation is "never inferred from EOF or death" @@ -3078,8 +2823,7 @@ carried: it described three outcomes and returned none of them. retried. Both cannot hold: an abort taking the ordinary path goes through `resolve_transaction/2`, which re-presents once on `commit_unknown` (`session_coordinator.ex:1752-1768`). Under a drain it presents **once** - and an unknown answer is an unknown answer, which is what makes phase 2's - third call the last one it can make and what lets the session be fenced + and an unknown answer is an unknown answer, which is what lets the session be fenced rather than waited on. Two halves, one clause, one change. **What is genuinely untouched is the record**: `propose_new/3` for @@ -3092,8 +2836,8 @@ carried: it described three outcomes and returned none of them. whether the commit is presented a second time and whether cleanup begins on the reply. -2. **Phase 3 of the stop, the cancellation: it is released, concurrently, - only once every admission has resolved.** Core waits for phase 2 to finish for every +2. **The cancellation: it is released, concurrently, + only once every admission has resolved.** Core waits for the admission to finish for every session — committed, refused as having no active run, or failed — and then releases the paused cleanups together. That is what makes the Concept's ordering true globally rather than per session, and it is also why the two @@ -3185,11 +2929,11 @@ carried: it described three outcomes and returned none of them. 3. **Terminate every coordinator, then fence every session — two phases, in that order, over the same set.** When the budget is spent, core terminates **every enumerated coordinator** — settled, unsettled and acquiring alike — - and waits for every `DOWN`; that is **phase 4**, bounded at the 5 s the - coordinator's own child specification carries and concurrent across them, - which is a ceiling nothing approaches because a coordinator does not trap - exits. Only then does it fence **every session it enumerated**, which is - **phase 5**. + and waits for every `DOWN`; that is the **termination**, bounded by the deadline the implementation + measures and issued concurrently across them — a coordinator does not trap + exits, so each dies at once, though `DynamicSupervisor.terminate_child/2` + serialises them through the one session supervisor. Only then does it fence + **every session it enumerated**. **The order is the whole of it, and an earlier revision had the sets different.** That revision terminated only the *unsettled* coordinators @@ -3204,9 +2948,9 @@ carried: it described three outcomes and returned none of them. Terminating a settled session's coordinator costs nothing it was still doing, and "settled" is what makes that true: its terminal is already - committed, which is what the word is defined to mean below. What phase 4 + committed, which is what the word is defined to mean below. What the termination buys is that no enumerated session still has a **process** that could start - a transaction, so phase 5's fence **races at most one delivered + a transaction, so the fence **races at most one delivered transaction** — the one the serial `OwnerLane` may have handed the Store before its coordinator died — which the fence's stale handling already covers. It does not race nothing, and an earlier revision said it did; what @@ -3395,31 +3139,29 @@ carried: it described three outcomes and returned none of them. | The fence answers **`commit_unknown`** | The Store cannot say whether it linearized | `{:unknown, head}` | Resolved by **one** `Store.transaction_status/4` query under the same derived `tx_id`; an answer that is still unknown after it leaves the session `unsettled` with `{:unknown, head}` carrying the head the fence read, and the domain fenced | | **No fence is attempted** | No coordinator ever existed for this session in this runtime, so nothing can write for it | `:not_needed` | As the entry left it | - **Phases 4 and 5 run over a *fresh* enumeration, not the one phase 2 - used.** `Control` keeps serving while the drain runs — which is the whole - point of quiesce being outside it — so entries can appear during phases 2 - and 3, and a create admitted just before the cut is exactly what appears. - Phase 4 therefore takes the enumeration again at its own start, and phases - 4 and 5 both work from that list. An entry that arrived during the + **Termination and the fence run over a *fresh* enumeration, not the one the + admission used.** `Control` keeps serving while the drain runs — which is the whole + point of quiesce being outside it — so entries can appear during the admission and the cancellation, and a create admitted just before the cut is exactly what appears. + Termination therefore takes the enumeration again at its own start, and it + and the fence both work from that list. An entry that arrived during the cancellation is terminated and fenced like any other; the `:not_needed` no-entry row is read from **this** list rather than the earlier one. - **Phase 5 fences every session in that enumeration — settled, unsettled and + **The fence covers every session in that enumeration — settled, unsettled and absent alike, every one of them with its coordinator already terminated in - phase 4 — and an earlier revision fenced only the ones that had not - settled.** That was a hole, and phase 7 is where it opened. The stop kills - the runtime supervisor at phase 6's bound; `OwnerGroup` traps exits and + the termination — and an earlier revision fenced only the ones that had not + settled.** That was a hole, and the Store stop is where it opened. The stop kills + the runtime supervisor at the teardown deadline; `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so a trapping descendant of a **settled** session's coordinator can still be - unwinding afterwards — and phase 7 then keeps the Store **alive** for up to + unwinding afterwards — and the Store stop then keeps it **alive** for up to thirty seconds more. A straggler's `session_commit` in that window would land on a session the drain had already reported `settled`, after the census was taken and with no fence to refuse it. So the fence is not a remedy for sessions that failed to settle; it is what makes the census true for **all** of them. One `advance_owner` per - enumerated session, concurrent, inside phase 5's 90 s — the phase is three - sequential calls whatever the session count is — and after `quiesce/1` + enumerated session, issued concurrently — and after `quiesce/1` returns, **no transaction for any enumerated session can commit**: the epoch has moved and the adapter refuses it `:stale_owner_epoch` (`state.ex:548-551`). @@ -3446,11 +3188,11 @@ carried: it described three outcomes and returned none of them. `:acquiring` entry is written at `:1030` and `:1189`. A call inside those Store calls is invisible to any enumeration, so it is - neither terminated by phase 4 nor fenced by phase 5, and its coordinator - may start after phase 4's read. + neither terminated nor fenced, and its coordinator + may start after that read. **What actually holds for it is crash-equivalence, not replay**, and that - is the disposition stated: the runtime kill in phase 6 ends such a + is the disposition stated: the runtime kill in the teardown ends such a coordinator **at once**, it being non-trapping; at most **one** transaction it had already delivered can linearize afterwards, the owner lane being serial; and that transaction lands as an ordinary durable fact — a genesis, @@ -3466,7 +3208,7 @@ carried: it described three outcomes and returned none of them. one of the two calls, not the reason either is safe. Bounded, in both cases, by the call's own remaining depth — the rest of the - ten calls phase 1b counts for a create, and a resume's own sequence. + rest of the create's own sequence, and a resume's. **A late `session.attach` is not in this class**, and the reason is worth one line: `begin_attach/3` requires the entry to be `:active` already @@ -3484,8 +3226,8 @@ carried: it described three outcomes and returned none of them. reason is the serial lane.** An earlier revision rereads the head and makes one new attempt — which would be right if more transactions could keep arriving, and none can. By the time a fence is attempted the coordinator is - **dead**, and that holds for **every** session phase 5 fences because - **phase 4 terminates every enumerated coordinator first** and waits for + **dead**, and that holds for **every** session the fence covers because + **termination reaches every enumerated coordinator first** and waits for every `DOWN` — which is the change this premise needed, an earlier revision having terminated only the unsettled ones while fencing them all. While a coordinator was alive it held **at most one** Store transaction in flight @@ -3510,8 +3252,8 @@ carried: it described three outcomes and returned none of them. precisely the case where the daemon says so rather than pretending, and it says so in a key a caller can read. - **Phase 3 never releases a session whose admission it cannot account - for.** A session whose phase-2 abort admission **failed or is ambiguous** + **The cancellation never releases a session whose admission it cannot account + for.** A session whose abort admission **failed or is ambiguous** — a refusal that is not `rejected_no_active_run`, or a `commit_unknown` on the admission itself — has no cleanup released for it at all. It is fenced like an unsettled session, or, where the fence too is unknown, left fenced @@ -3535,16 +3277,16 @@ carried: it described three outcomes and returned none of them. | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes, always.** An earlier revision let this be the `:not_needed` case on the reading that such an entry never had a coordinator. It can have had one: `unavailable_owner/3` (`:1149-1158`) writes `%{status: :unavailable, durable: nil}` with **no coordinator key**, and one of its callers reaches it at `:1134` *after* terminating a coordinator that had already been started (`:1132`). The absent key proves nothing about the past, so every `:unavailable` entry is fenced | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | - | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when phase 1b proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes, and the fence is what makes it safe.** Its coordinator is already gone, so phase 4 has nothing to terminate; what could still write is **the dead coordinator's at-most-one already-delivered transaction** — the same case every other fenced row rests on — and nothing else, because no owner group or worker can commit: `Store.transact` has one caller in core (`store/owner_lane.ex:121`), and `OwnerLane.transact` is called only from the coordinator (`session_coordinator.ex:1242`, `:1363`, `:1761-1762`) and `Control` (`control.ex:1680-1681`). The owner group that outlived the coordinator unwinds on its own clock past phase 6's kill, which ends the root only, but it writes nothing. Phase 5's moved epoch is what refuses that one transaction `:stale_owner_epoch`. An earlier revision credited the kill, and the one before it named the owner group as a writer | - | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No — the **only** `:not_needed` case, and it is read from the fresh enumeration phase 4 takes, never from the phase-2 snapshot | - | **A phase-2 admission that did not answer** inside the phase, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | - | **A phase-5 fence that did not answer** inside the phase, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | - | **A phase-5 task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | + | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when the bounded wait proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes, and the fence is what makes it safe.** Its coordinator is already gone, so termination has nothing to reach; what could still write is **the dead coordinator's at-most-one already-delivered transaction** — the same case every other fenced row rests on — and nothing else, because no owner group or worker can commit: `Store.transact` has one caller in core (`store/owner_lane.ex:121`), and `OwnerLane.transact` is called only from the coordinator (`session_coordinator.ex:1242`, `:1363`, `:1761-1762`) and `Control` (`control.ex:1680-1681`). The owner group that outlived the coordinator unwinds on its own clock past the runtime kill, which ends the root only, but it writes nothing. The fence's moved epoch is what refuses that one transaction `:stale_owner_epoch`. An earlier revision credited the kill, and the one before it named the owner group as a writer | + | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No — the **only** `:not_needed` case, and it is read from the fresh enumeration termination takes, never from the admission's snapshot | + | **An admission that did not answer** inside its bound, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | + | **A fence that did not answer** inside its bound, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | + | **A fence task shut down before its head read answered** | There is no head, so there is no identity a successor could recompute and nothing was proposed | `unsettled`, `{:unknown, :no_head}` | No fence was attempted. A successor reads the head itself and proceeds; nothing is outstanding at any version | **What `settled` means, and where it is read.** An earlier revision defined it as "whether its cancellation finished inside the budget" and named no observation point, which left the most consequential of the three lists - with no surface at all — and made phase 4 able to kill a coordinator + with no surface at all — and made termination able to kill a coordinator between its cleanup and its terminal commit and still report the session settled, with no terminal in the journal. @@ -3576,7 +3318,7 @@ carried: it described three outcomes and returned none of them. settles" witness therefore holds the Store fast enough for the read to answer, and a witness beside it holds one commit past 5 s and asserts the session lands in `unsettled` with its terminal still committed by the - coordinator before phase 4 ends it. + coordinator before termination ends it. No core change is needed for this, which is worth saying plainly after several rounds of adding things: the read exists, quiesce is outside @@ -3585,8 +3327,8 @@ carried: it described three outcomes and returned none of them. settled session anyway. **So a cancellation that finished without its terminal committed is - `unsettled`, never `settled`**: terminated in phase 4, fenced in phase 5, - and reconciled at the next activation like any other. Phase 4 therefore + `unsettled`, never `settled`**: terminated, fenced, + and reconciled at the next activation like any other. Termination therefore kills no owed write of a session it called settled, because a session is called settled only once the write it owed is already in the journal. @@ -3603,10 +3345,10 @@ carried: it described three outcomes and returned none of them. ready**, because `Control` writes that status only in the `owner_ready` handler (`control.ex:575-591`). Quiesce admits only into `:active`, which is sound — every entry it admits into has a ready coordinator — and is what - keeps phase 2's bound honest, the acquisition callback being far deeper + keeps the admission off the acquisition callback, which is far deeper than any ready one. What it costs is stated rather than hidden: an `:acquiring` entry whose cast is merely in flight is a session whose run is - **ended crash-equivalent** by phase 4's termination rather than cancelled + **ended crash-equivalent** by termination rather than cancelled through its own grace. Its journal claims no terminal, its ambiguous mutation is `commit_unknown`, and the next activation reconciles it — which is exactly the unsettled disposition, reached without the drain @@ -3616,8 +3358,8 @@ carried: it described three outcomes and returned none of them. That revision's argument was the cut: only `session.create` and `session.resume` write that status, both start a coordinator inside the call, both are ticketed, and the cut waited for every ticket to settle — so - none could be in flight. The argument died with the phase split. Phase 1b - waits for the admitted tickets and then **proceeds at its bound**, and a + none could be in flight. The argument died with the bounded wait, which + waits for the admitted tickets and then **proceeds**, and a resume whose replay is paging a long history is exactly the ticket most likely to still be running when it does. So an `:acquiring` entry is an ordinary outcome of a stop that fell back on its bound, not a defect. @@ -3670,7 +3412,7 @@ What it asks `Control` for is **one** bounded read, made **twice**: the enumeration — every session entry with its status, its coordinator pid and its **owner**, the owner being what the per-session calls need to identify themselves as current. Once at the start of the drain, and again at the start -of phase 4, for the reason that phase gives. Everything else the drain does — +at termination, for the reason given there. Everything else the drain does — admitting, cancelling, terminating, fencing and reading status — is per-session calls the caller's own tasks make **directly to coordinators and to the Store**, never through `Control`. (An earlier revision said "exactly @@ -3687,8 +3429,8 @@ in the ownership table beside `quiesce/1` itself, because a change nobody listed is a change nobody reviews. Neither read blocks `Control` for longer than a map projection, so a -coordinator committing in the middle of phase 2 is served as usual. That is -the witness: **a commit made by a coordinator during phase 2 completes** — its +coordinator committing in the middle of the admission is served as usual. That is +the witness: **a commit made by a coordinator during the abort admission completes** — its `post_commit` answered while the drain is running — **and its session settles**. Under the design this replaces, that case hangs. @@ -3860,7 +3602,7 @@ to write. **A fail-stop has an operator bound too, and it is much smaller than an orderly stop's.** Only two of its steps can wait: the executor stop, under - the same five seconds phase 6 uses, and the Store stop, in its own fixed + the same teardown deadline, and the Store stop, in its own fixed thirty. Nothing else waits on anything — there is no drain, no admission, no fence, no coordinator to terminate and no runtime tree to bring down. So **the maximum for any fatal class is 5 s + 30 s = 35 s**, with no @@ -4203,7 +3945,7 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. is held** past the budget is asserted **`unsettled`**, terminated and fenced, with the journal carrying no terminal for that run — where the old definition, "whether its cancellation finished", would have called it - settled and left phase 4 free to kill the write it still owed. + settled and left termination free to kill the write it still owed. *It does not.* A daemon with an effect held past the drain budget and an unresolved mutation receives `SIGTERM`. The case asserts the session is in @@ -4228,7 +3970,7 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. **A settled session's straggler is the case this fence exists for**, and it has its own assertion here: a transaction for a session the drain reported - `settled` is held inside the Store and released during **phase 7**, while + `settled` is held inside the Store and released during the **Store stop**, while the Store is still alive and the runtime has already been killed. It is asserted refused `:stale_owner_epoch` and absent from the journal. Before every enumerated session was fenced, that commit would have landed after the @@ -4444,10 +4186,10 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. stop completes. **And the slicing obligation is `quiesce/1`'s, not the daemon owner's.** - Phase 3 is the one phase whose bound is unbounded by construction, and it is + The cancellation is the one part whose bound is unbounded by construction, and it is enforced inside core; every other phase is a fixed number far below the domain. The wait rule therefore binds core's own waits in the drain, and the - daemon's owner — whose longest wait is phase 1b's 300 s — inherits it as a + daemon's owner inherits it as a rule it cannot violate rather than one it must remember. All of them run at both toolchain pairs, because both timeout results were observed at both. @@ -4588,7 +4330,7 @@ links rather than one of them, and an earlier revision headed eleven rows | --- | --- | --- | --- | | **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | | **Connections**, one per accepted client | The listener | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | -| **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time, except phase 6's lease-owner sweep, which spawns one per lease owner at once and so is bounded by the 512 above | Nothing: monitored, never linked | +| **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time, except the teardown's lease-owner sweep, which spawns one per lease owner at once and so is bounded by the 512 above | Nothing: monitored, never linked | | **Relay tasks**, one per ticketed call — the eight lease-authorized mutations, `session.create` and `session.attach`; **not** the three artifact-transfer methods, which mutate neither `Control` nor the journal | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | **Core's processes, as groups with their owner.** The runtime root supervises @@ -4776,16 +4518,8 @@ line; M5 introduces none of its own. | Socket path bound, over `/daemon/daemon.sock` | the platform's usable `sun_path`, one byte less than the structure because of the terminator: at most 103 bytes on Darwin and 107 on Linux, derived and tested per platform rather than assumed, refused at start as `socket_path_too_long` | ADR 0032 | | Protocol frame ceiling on the wire | unchanged from ADR 0023 | ADR 0032 | | Cleanup grace | an integer of 1 or more, refusing `0` with `cleanup_grace_invalid`, because core's `cancellation_bounds/1` admits `grace_ms >= 1` (`apps/loopex/lib/loopex/executor.ex:456`) | This plan, against core's existing validation | -| Phase 1a, closing admissions | **5_000 ms**, the teardown number reused; it bounds the relay's answer to a state change, not any work, and an unanswered close becomes the `relay_lost` fail-stop | This plan | -| Phase 1b, settling the admitted | **300 s** — ten sequential Store calls, a fresh `session.create` being the deepest ticket kind whose depth is a constant; the stop **proceeds** at this bound rather than waiting further | This plan, counted from a **traced run** of that path: `control.ex:959-965`, `:896-897`, `:1679-1684` and `session_coordinator.ex:1302-1309`, `:1338`, `:1363`, `:1397-1400`, `:1407`, `:7090-7114` | -| Phase 2, abort admission | a fixed **210 s** — seven sequential Store calls at the adapter's own 30 s `@call_timeout`: the six of the deepest callback a **ready** coordinator may be running — `close_execute_result_reserve/3`, which commits the executor fact, then an unproved tool result where that fact's commit was refused, then the run terminal, each re-presented once — and then the drain's own admission, which does not retry; one phase for every session, because they are admitted concurrently. It rests on two claims — quiesce admits only into an `:active` entry, so the acquisition callback is never what an admission waits behind, and no ready callback commits more than three times, counting **both** the `commit_internal_result/2` route and the `apply_transaction/3` admission route | Core, against `apps/loopex_store_local/lib/loopex/store/local.ex:65`, `:111-113` and `session_coordinator.ex:146-149`, `:1752-1768`, `:5336-5351`, `:5353-5364`, `:5396-5400`, `control.ex:575-591` | -| Phase 3, the drain budget | `max` over drained sessions of `cancellation_bounds(g_i).cli_backstop_ms`, returned as `budget_ms` | Derived from `apps/loopex/lib/loopex/executor.ex:456-474`; no number chosen | -| Phase 4, coordinator termination | **5_000 ms**, the coordinator's own `shutdown` value (`apps/loopex/lib/loopex/runtime/session_coordinator.ex:134-142`), concurrent across **every** enumerated coordinator; it runs **before** the fence, so the fence races no live **writer** — at most the one transaction the serial lane may already have delivered, which its stale handling covers | Core's existing child specification | -| Phase 5, the fence | a fixed **90 s** — three sequential Store calls at 30 s: the head read, the `advance_owner`, and at most one `transaction_status` query; concurrent across sessions, and no retries | Core, against `local.ex:65`, `:111-113`, `:116-122`, `:130-132` | -| Phase 6, non-Store teardown | **5_000 ms**, one absolute deadline from the instant `quiesce/1` returns, covering the stop records, the connection and listener closes, the collective lease-owner sweep, **the runtime tree's stop** and every other non-Store stop | This plan. Chosen, not derived. A ceiling for the work the phase performs rather than a promise about the runtime's subtree: an `OwnerGroup` traps exits and carries `shutdown: :infinity` (`owner_group.ex:14-19`, `:50`, `:86-90`), so the runtime stop is attempted with what remains and killed at the bound | -| Phase 7, the Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | +| Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Maximum fail-stop exit | **35 s** — 5 s for the executor stop and the Store's own fixed 30 s, the only two steps of that path that wait; 5 s on the two store classes, where the Store is already gone | This plan, as the sum of its parts | -| Maximum graceful stop | `budget_ms` + **645 s**, the sum of the seven fixed phases above — eight phases, of which only the drain budget is derived; a worst case built from the adapter's wedged-filesystem ceiling, not the cost of an ordinary stop | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index e189b5601..2ddf555f6 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -406,12 +406,11 @@ did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. **The drain has a mechanism, and it is core's.** M5 adds `quiesce/1` to -`Loopex.Runtime`, and it has four parts — which are stop **phases 2 to 5**, -the numbering the bound uses, rather than a second scheme of its own. -**Phase 2** durably admits the +`Loopex.Runtime`, and it has four parts, in this order. +**The abort admission** durably admits the existing abort command for every active session and stops there, because ADR 0023 fixes that only a durable `session.abort` cancels and nothing may infer -cancellation from a signal. **Phase 3** releases every session's +cancellation from a signal. **The cancellation** is then released for every session's cancellation, concurrently, only once every admission has resolved — which is what makes "every abort durable before any cancellation" true across the daemon rather than one session at a time. The record it writes is the one a client's own abort writes, under a @@ -427,7 +426,7 @@ that settled as well as the ones that did not — and only then commits a Store-linearized owner-epoch fence for every one of those sessions**, in that order, so no fence races a live writer; because the runtime is killed at the teardown bound while the Store stays -alive for its own phase, so a settled session's straggler could otherwise +alive for its own stop, so a settled session's straggler could otherwise commit after the census that called it settled; so an older transaction still in flight either wins before the fence and is observed or loses after it and is refused as stale. **That fence's identity is derived @@ -446,37 +445,22 @@ dependency direction forbids, or run a cancellation loop of its own, which is the second loop this milestone forbids, and it could not admit a durable command on its own authority at all. -**A graceful stop has a stated maximum**, because an operator configuring a -service manager needs one, and it is the **sum of eight bounded phases** rather -than one clock that has to cover everything: five seconds for the admission -cut — which is two phases, because closing admissions is instant and waiting -for what was already admitted is not: five seconds for the close and three -hundred for the settle, after which the stop proceeds. Then two hundred and -ten for admitting every session's abort, the drain budget **core -derives and reports** for the cancellation, five for terminating every coordinator it enumerated, ninety for fencing -every one of those sessions afterwards, five for every non-Store -action after the drain — the stop records, the closes, the lease owners, the -runtime tree and the edges, the runtime being attempted with what remains and -killed at the bound — and thirty for the Store stop that releases the marker. Seven of -the eight are fixed, so the maximum is **`budget_ms` plus 645 seconds** — a -worst case assembled from the store adapter's ceiling for a wedged -filesystem, not the cost of an ordinary stop, which finishes in milliseconds. **Five** of the seven are counts of the -adapter's own thirty-second call timeout, or the coordinator's own shutdown -value: a phase that makes seven Store calls in sequence is bounded at two -hundred and ten and one that makes ten at three hundred, and the drain retries nothing, which -is what keeps those counts finite. The other two — the five seconds for -closing admissions and the five for the teardown — are **this plan's own -numbers**, chosen rather than derived, and the technical companion says so -where it names them. **Four of those counts are taken from a traced run** — a fresh create's nine, -an attach's one and two, a resume's eleven and a fence's three. **Phase 2's -seven is not**: it is derived by reading which commits one coordinator -callback can compose, and it waits on its witness like the others. The -distinction is drawn rather than glossed, because reading is exactly how that -count was wrong twice before a trace settled it, and a plan that called every -number traced when one was not would be repeating the error it is warning -about. The drain term is core's because each session drains under the grace it -committed, which a daemon reading its own flag would not know for a session -composed earlier. A +**A graceful stop has a maximum, and the implementation is what states it.** +An operator configuring a service manager needs a figure, and three revisions +of this plan tried to supply one by deriving each step's seconds from a count +of sequential Store calls and summing them. That derivation was corrected in +four consecutive reviews, each time moving a number the plan had published, so +the maintainer withdrew it on 2026-09-20. What this pair fixes instead is the +**order** of the stop and the **guarantee** at each step; what it costs is +**measured at implementation**, and the operator page carries that measured +figure as a closure obligation rather than a promise made here. + +Two numbers stay, because neither is derived from a drain: a **fail-stop** +exits in at most **thirty-five seconds**, and the **Store stop** that releases +the writer marker has a fixed **thirty**, which is the store adapter's own +call timeout. Every other bound the implementation uses is stated there as an +**executed count** — a number a test asserts by running the path rather than +by reading it — which is the rule the four corrections earned. A service manager that kills the daemon sooner turns the stop into a forced shutdown — the journal stays crash-equivalent, but work that would have settled does not, and the writer marker may be left for the next daemon's From dc264cdbe9ec5592422301bd1e9eb5fb2b443e24 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:23:46 -0700 Subject: [PATCH 165/585] docs(M5): closure names a tested SHA and an administrative SHA Maintainer decision of 2026-09-20 (D2). The closure packet asked for the checks, the review and the record from one commit, which no sequence of commits can satisfy: recording a closure is itself a commit, and it comes after the evidence it records. Closure now names two. The **tested implementation SHA** is what the runs and the review are of. The **administrative closure SHA** records the decision and touches only four places -- the register row, the plan's Closure row, the context-map entry -- so `git show` over its diff is the check that it is administrative; anything else there means the evidence no longer covers the tree and the packet is reassembled. The plan's Closure row carries both, since recording one leaves either the evidence or the decision unlocatable. Two obligations follow. The documentation and archive checks run **on the tagged SHA**, being the two whose subject is the published bytes -- the gate reads every tracked file under `docs/` and the archive proof builds an extraction of the exact commit -- so running them on the implementation SHA alone leaves the administrative commit's own documentation unchecked and the archive proved for a tree nobody publishes. And run evidence is **immutable**: attached to the annotated tag or held outside the repository with its digest recorded, so that what a reviewer read and what a reader later finds are the same thing. Concept decision in `milestones.md`, mechanics in the companion inside the existing closure-packet section so the reciprocal-link rule stays satisfied, and M5's closure section follows both -- including the operator page's stop figure, which this round's other decision makes a measured closure item. --- docs/developer/milestones-technical.md | 41 ++++++++++++++++++++++++-- docs/developer/milestones.md | 18 +++++++++++ docs/plans/M5.md | 20 +++++++++++++ 3 files changed, 76 insertions(+), 3 deletions(-) diff --git a/docs/developer/milestones-technical.md b/docs/developer/milestones-technical.md index c22eb2a83..ca38629d4 100644 --- a/docs/developer/milestones-technical.md +++ b/docs/developer/milestones-technical.md @@ -93,12 +93,47 @@ At the candidate commit: correctness, test honesty, public impact, security and rollback; blocking findings are fixed first. 5. The packet to the maintainer: outcomes and their proof, the runs, the - review, what remains. On their decision, the closure commit moves the - register row to `Closed`, fills the plan's Closure row with the reviewed - candidate SHA, and records the maintainer's words in + review, what remains. On their decision, the **administrative closure + commit** moves the register row to `Closed`, fills the plan's Closure row, + and records the maintainer's words in `docs/developer/agent-context-map.md`. `mix loopex.status` derives the `Closed` capsule; run it and copy what it expects. +**The two SHAs, and what each one carries.** + +| | Tested implementation SHA | Administrative closure SHA | +| --- | --- | --- | +| What it is | The candidate the checks ran on and the reviewer read | The commit that records the decision | +| What it changes | Everything the milestone implemented | The register row, the plan's Closure row, the context-map entry, and nothing else | +| What names it | Every run on the evidence page, and the review | The register, once `Closed` | +| Its evidence | The runs of step 3, taken from it | None of its own; it is a record, not a claim | + +The plan's **Closure row carries both**: the tested implementation SHA the +packet was assembled from, and the administrative SHA that closed it. A +reviewer checking the milestone reads the first; a reader tracing the decision +reads the second. Recording only one leaves either the evidence or the +decision unlocatable. + +**The administrative commit is verifiable as administrative**, and that is +what keeps the split honest rather than decorative: its diff touches only the +four places above, so `git show` over it is the check. Anything else in that +diff means the evidence no longer covers the tree, and the packet is +reassembled from a new implementation SHA. + +**The documentation and archive checks run on the tagged SHA.** They are the +two whose subject is the published bytes — the documentation gate reads every +tracked file under `docs/`, and the archive proof builds an extraction of the +exact commit — so running them only on the implementation SHA leaves the +administrative commit's own documentation changes unchecked and the archive +proved for a tree nobody publishes. They run again on the tag, and their +results join the evidence page with the tag named. + +**Run evidence is immutable.** A run's identity, platform, toolchain, result +and duration are retained where they cannot be edited after the packet is +read: attached to the annotated tag, or held outside the repository with its +digest recorded here. An evidence page that can be rewritten after a reviewer +read it is a record of what someone later wished had happened. + ### Tags diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index a34099d29..6dceb9ab2 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -62,6 +62,24 @@ page; ask an independent reviewer to read the candidate; then present the packet to the maintainer. The maintainer closes it; the register moves to `Closed`, and the plan records the closing decision and the candidate. Use the `close-milestone` skill. + +**Closure names two commits, because one cannot name itself.** The checks and +the review are of a **tested implementation commit**; recording the closure — +the register row, the Closure row, the context-map entry — is a further commit +that necessarily comes after, and that the evidence therefore cannot have +been taken from. Earlier wording asked for both from one SHA, which no +sequence of commits can satisfy. So a closure carries the **tested +implementation SHA**, which the runs and the review name, and the +**administrative closure SHA**, which records the decision and changes nothing +the runs covered. A closure whose administrative commit touches anything +else is not administrative, and its evidence is stale. + +**Two obligations follow from that split.** The documentation and archive +checks are the ones a later commit can invalidate, so they run **on the tagged +SHA** — the exact bytes published — rather than on the implementation commit +alone. And run evidence is **immutable**: retained where it cannot be edited +after the fact, attached to the tag or held outside the repository, so that +what a reviewer read and what a reader later finds are the same thing. Technical depth: [The closure packet](milestones-technical.md#technical-milestones-close). diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 2ddf555f6..e75d5e0de 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -742,6 +742,26 @@ result and measured duration is retained on `docs/evidence/M5-closure-runs.md` with the security review of Outcome 6. An independent reviewer reads the candidate; the maintainer closes it. +M5 closes on the two SHAs the +[milestone guide](../developer/milestones.md#concept-milestones-close) now +fixes, and its Closure row carries both: the **tested implementation SHA** +every run above names and the reviewer read, and the **administrative closure +SHA** that records the decision and touches only the register row, this pair's +Closure row and the context map. The **documentation gate and the source +archive are proved again on the tagged SHA** — they are the two whose subject +is the published bytes, and the administrative commit changes documentation — +with those results joining the evidence page beside the tag. The runs +themselves are retained immutably, attached to the annotated tag or held +outside the repository with their digests recorded on that page, so the +evidence a reviewer read is the evidence a reader finds. + +**The operator page's stop figure is a closure item on that same packet.** +Because this pair states the drain's guarantees and not its arithmetic, the +maximum graceful stop `docs/operator/daemon.md` carries is **measured against +the tested implementation SHA** and recorded with the conditions it was +measured under. Closure cannot complete with that row empty, which is what +makes the withdrawal of the derived sum an obligation rather than a gap. + **Release.** The release is one annotated `v0.2.0` tag on the exact integrated closure commit, reusing the closure evidence because the source is unchanged, plus a verified source archive of that commit. It publishes no Hex package, From 259403eb44207c413331a440ffae40406aaa3c33 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:25:18 -0700 Subject: [PATCH 166/585] plan(M5): Control is single-attachment too, and change 1 must fix it P0-1. Two reviews of this pair traced the concurrent-attachment change through the dispatcher and never read `Control`, which holds attachment state of its own -- one field per session. `finish_attach/5` **overwrites** it on every successful attach (`control.ex:1273-1283`), the command path validates against that one field (`:343`, `current_attachment?/3` at `:1649-1657`, which answers `{:error, :stale_attachment}` for anything else), and `attachment_repetition/4` keeps its repetition state for the same single slot (`:1312-1314`). With only the dispatcher changed, two coexisting attachments still break the session at `Control`: an observer attaching after a controller overwrites the controller's slot and the controller's **next command fails**. That is the daemon's central case -- one driver, several watchers -- failing on the component nobody had looked at. Core change 1 therefore has three parts rather than two, and the third is `Control`'s attachment and repetition state **keyed by a stable holder identity**: the holder pid the dispatcher already monitors for the release half, so both components key on the same thing and one `DOWN` drops the entry in both. One holder still has one attachment -- the per-connection rule does not change -- which is exactly why the key is the holder rather than the attachment id. Its witness is the case that fails today: a controller and an observer attached to one session, both asserted still usable. --- ...tachment-residency-and-replay-technical.md | 35 +++++++++++++++++-- docs/plans/M5-technical.md | 10 +++--- docs/plans/M5.md | 13 +++++-- 3 files changed, 48 insertions(+), 10 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 826ddfa49..687e423bb 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -165,10 +165,39 @@ an entry is same-session **supersession** (`:812-823`) — which M5's concurrent-attachment change removes, because coexisting attachments are the point. -So that change has two halves and this pair states both: supersession stops -removing attachments **unconditionally**, **and the dispatcher keeps its +**And there is a third place the change has to reach, which two reviews of +this pair missed: `Control` is single-attachment too.** The dispatcher is not +the only component holding attachment state. `Control`'s session entry has one +`attachment` field, `finish_attach/5` **overwrites** it on every successful +attach (`control.ex:1273-1283`), the command path validates against that one +field (`:343`, `current_attachment?/3` at `:1649-1657`, answering +`{:error, :stale_attachment}` for anything else), and `attachment_repetition/4` +keeps its repetition state for that same single attachment (`:1312-1314`). + +So with only the dispatcher changed, two coexisting attachments would still +break the session at `Control`: an observer attaching after a controller +overwrites the controller's slot, and the controller's **next command** fails +— the daemon's central case, failing on the component nobody had looked at. + +**Core change 1 therefore includes `Control`'s attachment and repetition +state, keyed by a stable holder identity.** That identity is the **holder +pid** — the connection process the dispatcher already monitors for the release +half of this change — so the two components key on the same thing and a +`DOWN` drops the entry in both. `Control` keeps one attachment *per holder* +per session rather than one per session, validates a command against the +holder's own attachment, and keeps repetition state per holder. Nothing about +the single-attachment-per-connection rule changes: one holder still has one +attachment, which is why the key is the holder and not the attachment id. + +Its witness is the case that fails today: a controller attaches, an observer +attaches to the same session, and **both remain usable** — the controller's +next command is admitted and the observer keeps receiving. + +So that change has three parts and this pair states all of them: supersession +stops removing attachments **unconditionally**, **the dispatcher keeps its monitor after install and -removes the attachment on that process's `DOWN`**. Without the second half M5 +removes the attachment on that process's `DOWN`**, and **`Control` scopes its +attachment and repetition state by holder**. Without the second half M5 would leave core with no release path at all, and every attachment ever made would live until the runtime stopped. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 1e62106dc..9cf7e9ea2 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes, with `Control`'s own attachment and repetition state scoped by the same holder pid**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -339,7 +339,7 @@ core-internal states a daemon cannot construct through the socket. | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | +| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | | **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the phase-4 enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during phases 2 and 3`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | @@ -4409,12 +4409,14 @@ daemon is a host and a host is an application. One daemon owner process, one new the two callers that need the edges assembled, `RuntimeOwner` and the daemon's owner, and which direct code cannot replace because the alternative is a second copy of the whole wiring layer. One socket listener, **one narrow core -concurrent-attachment change with two halves** — supersession stops removing +concurrent-attachment change with three parts** — supersession stops removing an attachment *unconditionally*, becoming conditional on ADR 0023's existing `replace` flag and scoped to the attaching process's own prior attachment, and the dispatcher monitors the attaching process, keeps that monitor and the attacher pid **on the installed attachment**, and removes -on its `DOWN`, releasing that attachment's transfers — because the first half +on its `DOWN`, releasing that attachment's transfers, and `Control` scopes +its own attachment and repetition state by that holder pid rather than +keeping one slot per session — because the first half alone would leave core with no release path at all, supersession being the only one there is today, and would leave the only caller of `release_transfers/2` with no replacement, which accepted diff --git a/docs/plans/M5.md b/docs/plans/M5.md index e75d5e0de..2c5619834 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -1040,7 +1040,7 @@ the dispatcher demonitors the attaching process the moment its snapshot scan finishes, and `disconnect/2` marks an attachment disconnected without removing it. Made as written, that change would have left core with no attachment release path at all, and every attachment ever made would have lived until the -runtime stopped. Core change 1 therefore has two halves: supersession stops +runtime stopped. Core change 1 therefore has three parts: supersession stops removing **unconditionally** — it becomes conditional on the `replace` flag ADR 0023 already puts on `session.attach`, and narrows to the attaching process's own prior attachment for that session — and the dispatcher keeps its @@ -1048,8 +1048,15 @@ monitor and removes on the attaching process's `DOWN`, **releasing that attachment's transfers as it goes** — for which the dispatcher keeps the attacher's pid and that monitor's reference **on the installed attachment**, which it records neither of today, and which -both halves need: the `DOWN` handler to find the attachment to drop, and the -narrowed replacement to know whose prior attachment it may supersede. +both need: the `DOWN` handler to find the attachment to drop, and the +narrowed replacement to know whose prior attachment it may supersede. And +**`Loopex.Runtime.Control` scopes its own attachment and repetition state by +that same holder pid**, because it is single-attachment too: it keeps one +`attachment` field per session, overwrites it on every attach and validates +every command against it, so without this an observer attaching after a +controller makes the controller's next command fail. That is the daemon's +central case, and it failed on the component two reviews of this plan never +read. Both qualifications were found by reading the dispatcher rather than the design. Core never sees `replace`: the app server parses it and uses it only From 21910cfa39f369570b2100b9927838263a03e14a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:26:15 -0700 Subject: [PATCH 167/585] adr(M5): spawn a token-free bootstrap, because entry itself is traced P0-2. This pair said for several revisions that the sender calls `exclude_self/2` "before it resolves anything". That is true of the function body and beside the point. `set_on_spawn` gives a spawned process its parent's trace flags **at spawn**, so the closure's own entry call is traced -- and the closure **holds the token**, because that is how a spawned function receives anything. An audit probe saw the entry call, token included, delivered to the tracer before the first line of the body could run. No ordering inside the body fixes an exposure at the boundary into it. The bridge now spawns a **token-free bootstrap process**: it holds no token, no registry handle and no credential, only the capability reference it needs to exclude itself and the pid to report to. It establishes and confirms its exclusion first, and **only then** receives the token and the registry reference **by message** -- a message to an already-excluded process is not a traced call -- and only then resolves and writes the frame. The witness asserts what the old ordering could not: no raw trace message from that process carries the token **at any point in its life**, entry included, while a non-excluded control process spawned with the same closure shape does produce one, so the case cannot pass by tracing nothing. ADR 0034's MFA table, the exclusion paragraph and Outcome 6 all say this. --- ...andoff-over-bootstrap-channel-technical.md | 39 ++++++++++++++++--- docs/plans/M5-technical.md | 2 +- 2 files changed, 34 insertions(+), 7 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 94a4070c1..1b45151aa 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -311,9 +311,35 @@ boundary, not an absolute: future one, is outside the list again. An enumeration of callees is not a contract anyone can keep. - **So the core API takes both, and the adapter supplies the function list.** - The sender — the short-lived process that resolves the credential and writes - the frame — calls, **before it resolves anything**: + **The sender cannot exclude itself first, because it is already traced when + it starts.** This pair said for several revisions that the sender "calls + `exclude_self/2` before it resolves anything", which is true of the + function body and beside the point: `set_on_spawn` gives a spawned process + its parent's trace flags **at spawn**, so the closure's own entry call is + traced — and the closure **holds the token**, because that is how a spawned + function receives anything. An audit probe saw exactly that: the entry call, + token included, delivered to the tracer before the first line of the body + could run. Ordering inside the body cannot fix an exposure that happens at + the boundary into it. + + **So the bridge spawns a token-free bootstrap process.** What is spawned + holds **no token, no registry handle and no credential** — nothing but the + capability reference it needs to exclude itself and the pid to report back + to. Its body does one thing first: establish its exclusion, synchronously, + and confirm it. **Only then** does it receive the token and the registry + reference **by message**, and only then does it resolve and write the frame. + A message sent to an already-excluded process is not a traced call, so + nothing the tracer can see ever carries the token. + + Its witness asserts the property the old ordering could not: the tracer + receives **no raw trace message from that process carrying the token, at any + point in its life** — entry included — while a non-excluded control process + spawned with the same closure shape does produce one, so the case cannot + pass by tracing nothing. + + **The core API takes both inputs, and the adapter supplies the function + list.** The bootstrap process — which becomes the sender once it has the + token — calls, **before it receives anything**: ```elixir Loopex.Trace.exclude_self(capability, functions: [{module, function, arity}]) @@ -333,8 +359,9 @@ boundary, not an absolute: it is listed below. It returns `:ok` once the caller is excluded from **every** live trace - session and recorded as excluded for every future one. Only then does the - sender route the token, receive the credential and write the frame. Nothing + session and recorded as excluded for every future one. Only then is the + token sent to it, and only then does it route the token, receive the + credential and write the frame. Nothing the sender does after that point can appear in a trace, whatever modules or functions a host names — including `:gen_tcp`, including modules nobody has thought of. @@ -514,7 +541,7 @@ boundary, not an absolute: | MFA | What it holds | | --- | --- | - | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | The registry handle and the token | + | `Loopex.LLM.ReqLLM.ProviderBridge.route_credential/2` | The registry handle and the token — received **by message** after the exclusion, never carried into the process | | `Loopex.LLM.ReqLLM.ProviderBridge.receive_custody_reply/2` | The resolved credential | | `Loopex.LLM.ReqLLM.ProviderBridge.write_credential_frame/2` | The resolved credential | diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 9cf7e9ea2..ff6c32cd1 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -148,7 +148,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted: `exclude_self/2` returns before the token is routed, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted, and it is proved at the **process boundary** rather than inside the body: what the bridge spawns holds no token, no registry handle and no credential — `set_on_spawn` traces a spawned closure's **entry call**, so a token in that closure is exposed before any line of it runs — and it receives the token by message only after its exclusion is established and confirmed. The tracer is asserted to receive **no raw trace message from that process carrying the token at any point**, entry included, while a non-excluded control process spawned with the same closure shape does produce one; `exclude_self/2` returns before the token is sent, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the From bc627ef464bca6db3729cc6ee1dae80c0cbb89e9 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:31:15 -0700 Subject: [PATCH 168/585] plan(M5): the P1 batch: binding, ownership, slotting, manifests Session binding: the first `session.attach` or `session.acquire_control` a connection completes pins which session it is about, and a later call naming another is refused. Without it a connection could hold a lease on one session and an attachment on another, and `control_owner_lost` -- whose close ends the **connection** -- would take down an unrelated session's attachment. `event_cursor` on that record is **absent exactly when no attachment existed**, with a vector for each shape, because a connection that acquired and never attached has no emitted cursor to name. Attach is ticketed but not relay-performed: the dispatcher monitors **its caller** (`event_dispatcher.ex:186-192`), so an attach made from a short-lived relay task would be released the instant that task exited. Core change 1 gains an internal attach form taking a stable holder pid, the daemon passes its connection process, and the witness asserts the monitored pid *is* that process. Duplicate creates coalesce: a reservation has an owner and a waiter set, an exact re-presentation of the same `command_id` joins the waiters rather than reserving a second slot, and the 63-active race witness is made deterministic -- both calls held at the serial owner and released in a fixed order -- so it asserts which one is refused rather than that one of them is. Connections: the slot is reserved at **accept**, not at `initialize`, and an excess socket is closed at once with no record; a peer that connects and never speaks otherwise counts as zero while holding a socket, a process and a buffer. And connections get an owner -- one fixed **connection registry** holding the slot, the monitor, the buffer-control interface and the negotiated generation, so generation-2 records reach only connections that completed a generation-2 `initialize` and uninitialized sockets are closed with EOF. Its loss is daemon-fatal; the listener's is not, and the two reasons are stated. Startup index bound: the listing the daemon builds from is **core's**, and `SessionDirectory.list_sessions/1` (`session_directory.ex:230-253`) reads every entry before returning -- so a root with a hundred thousand is read in full before the daemon can refuse at 4,097. `Loopex.list_sessions/2`, taking a bound and stopping past it, is named as a **sixth** core change, and every "five core changes" sentence follows. Trace sessions: `Control` retains the excluded pid set **and** a ref-counted MFA union, so a session starting later finds the function clears and not only the pids; session creation is serialised against exclusion installation, both being `Control` operations; and the set is described as leak-free and proportional rather than "bounded", which implied a ceiling it does not have. Archive: a canonical **NUL-safe manifest** -- path, kind and mode, contents digest or link target -- taken before and after the build and compared, which catches a mode change, a file replaced by a link, and paths appearing or vanishing, where a contents digest alone does not. `export-subst`'s actual behaviour is stated, including that it cannot carry a path list. ADR residue: ADR 0032 loses the marker-ownership check that does not exist -- the marker's lifetime is the Store process's lifetime, so the Store's exit is the event -- and ADR 0031 credits the **fence**, not a stopped Store, with refusing a straggler, since the Store is still alive when one is most likely to be unwinding. --- ...store-selection-and-migration-technical.md | 17 ++- ...tachment-residency-and-replay-technical.md | 67 +++++++++-- ...-daemon-attachment-residency-and-replay.md | 6 +- ...andoff-over-bootstrap-channel-technical.md | 25 ++++- docs/plans/M5-technical.md | 105 +++++++++++++++--- docs/plans/M5.md | 15 ++- 6 files changed, 196 insertions(+), 39 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 05d3a38e2..5a1c3af7c 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -27,12 +27,17 @@ section. The qualification is deliberate and is the strongest true form. Where the runtime does not stop within its grace the daemon kills its supervisor, and a *trapping* descendant — an owner group, or a trapping worker beneath one — -may still be unwinding when the Store goes. Such an orphan meets a stopped -Store and gets the same refusal it would get after a VM death: it cannot -write, because there is nothing left to write to. So the marker is never held -open by a straggler, and no straggler appends behind the daemon's back; what -the daemon does not promise is that every process has finished before it -exits. +may still be unwinding when the Store goes. **What refuses such a straggler is the drain's fence, not a stopped Store**, +and an earlier revision of this paragraph had it the other way round. The +Store is *not* stopped while a straggler is most likely to be unwinding: the +daemon stops it last, in its own phase, so there is a window in which the +Store is alive and accepting. What makes the straggler harmless is that the +drain moved that session's owner epoch before the runtime came down, so its +commit is refused `:stale_owner_epoch` like any other stale writer. The marker +is therefore never held open by a straggler and no straggler appends behind +the daemon's back — but for the fence's reason, which holds whether the Store +is alive or not, rather than for an absence that only begins later. What the +daemon does not promise is that every process has finished before it exits. The adapter also **traps exits**, which this arrangement relies on: an owner that crashes rather than stopping gives the Store's `terminate/2` the chance diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 687e423bb..597417f79 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -111,11 +111,16 @@ ownership and then unlinked would be acting across a window in which the Store can die, the marker can be released and a successor can bind, and the predecessor would then delete the successor's socket. The next daemon to acquire and verify the marker removes the stale pathname before binding, which -is the one moment at which removing a socket file is unambiguously correct. If the daemon loses store ownership while -running, because its Store child exits or the marker can no longer be -proved held, it closes the listener and every connection before anything -else and then exits; no connection outlives the daemon's ownership of the -root. +is the one moment at which removing a socket file is unambiguously correct. If the daemon's **Store process exits**, it closes the listener and every +connection before anything else and then exits; no connection outlives the +daemon's ownership of the root. An earlier revision wrote that as "its Store +child exits **or the marker can no longer be proved held**", which named a +check that does not exist: nothing polls the marker, and the read-only +ownership call a revision once invented for it was withdrawn with the unlink +it existed for. **The marker's lifetime is the Store process's lifetime** — +`Loopex.Store.Local` takes it at start and releases it in its own +`terminate/2` — so the Store's exit *is* the event, and there is no second +condition to observe. Framing, the initialize handshake, admission records, snapshot, event and progress records, the frame ceiling, the strict UTF-8/LF rule and @@ -482,6 +487,24 @@ added keys are enumerated so the digest covers them: ADR 0023's own framing and input ceilings are unchanged; these are additions beside them, and **all five** digest inputs therefore change in generation 2. +**A connection is pinned to one session, and both paths pin it.** The first +`session.attach` or `session.acquire_control` a connection completes fixes +which session that connection is about; every later call on it naming a +different session is refused with the existing invalid-argument reason, and +the daemon's per-connection state is keyed by that one session rather than by +whatever the last frame said. Without the rule a connection could hold a lease +on one session and an attachment on another, and `control_owner_lost` — whose +close ends *the connection* — would take down an attachment belonging to a +session that had nothing to do with the lost owner. + +**`control_owner_lost` therefore carries `event_cursor` exactly when there was +an attachment to carry one for.** A connection that acquired and never +attached has no emitted cursor, and inventing one would be a lie about what it +received; the field is **absent** in that case and present otherwise, which +is an optional-field rule the DTO tables already have vocabulary for. Both +shapes are generation-2 vectors — one with the cursor, one without — because a +client parsing the record has to know that absence is legal. + **Connections are bounded, and an earlier revision said they were bounded by the attachment ceiling, which they are not.** A client may connect, `initialize`, call `session.list`, `daemon.status` or @@ -493,6 +516,17 @@ the attachment number reused rather than a fourth 512 invented, and the daemon reports it as `connection_limit` with the live count as `connections` so an operator can see the headroom before it is gone. +**The slot is taken at `accept`, not at `initialize`.** A ceiling enforced +only at the handshake bounds nothing that matters: a peer that connects and +never speaks holds a socket, a process and a buffer, and the daemon would +count it as zero. So the listener **reserves a connection slot as it accepts** +and closes the socket immediately when none is free — before any frame is +read, before the peer check, with no record, because a connection that was +never admitted has no generation to be told anything in. The slot is released +when the connection process ends, which is the same `DOWN` everything else +about a connection hangs from. The `initialize`-time refusal below still +exists for the case a slot was free at accept and the handshake is what fails. + **The refusal is ADR 0023's, not a new one.** A connection accepted beyond the ceiling is answered, at its `initialize`, with a correlated **`capacity_exceeded`** — which generation 1 already carries, so generation @@ -1074,10 +1108,10 @@ awaiting an answer, a recovery in progress, an unresolved `commit_unknown`, or an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and -none of M5's five core changes (concurrent attachment, the read-only existence -query, the trace exclusion, `quiesce/1`, and the `disposition` and -`control_entry` fields on the detailed create and resume functions) stops a -coordinator, +none of M5's six core changes (concurrent attachment, the read-only existence +query, the trace exclusion, `quiesce/1`, the `disposition` and +`control_entry` fields on the detailed create and resume functions, and the +bounded session listing) stops a coordinator, so a deactivation call would be a further core change this milestone does not make. @@ -1114,6 +1148,21 @@ make. as `store_log_too_large`: refuse rather than serve a truncated view of what the root records. The ceiling is on recorded entries only, and it never makes a session unreachable — see the crash cut below. + + **Enforcing it needs a bounded read, and core does not have one.** The + listing the daemon builds its index from is core's: + `Loopex.list_sessions/1` (`loopex.ex:452-453`) calls + `SessionDirectory.list_sessions/1` (`session_directory.ex:230-253`), which + does `File.ls` and then reads **every** entry before sorting and returning. + A root holding a hundred thousand entries is therefore read in full before + the daemon can refuse at the four-thousand-and-ninety-seventh — a refusal + whose point is to avoid exactly that cost. So this milestone adds one + further narrow read to core and counts it: **`Loopex.list_sessions/2` + taking a bound and stopping after the bound-plus-first valid entry**, + answering what it read and whether it stopped early. It is read-only and + additive — the arity-one form keeps its exact meaning and its callers — and + it is the smallest thing that lets the bound be enforced rather than + discovered. - **Homogeneity.** One state root is one host composition for the daemon's process lifetime. The daemon is composed once, with one workspace, policy, provider configuration and set of project resources, and serves every diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 6034547bb..fc101447f 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -57,10 +57,10 @@ connection closes whatever happened, so a client may learn of a shutdown only by its socket closing. It adds no durable method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core -has no durable stop command, and M5's five core changes — concurrent +has no durable stop command, and M5's six core changes — concurrent attachment, a read-only existence query, the trace exclusion, the bounded -`quiesce/1`, and the create and resume results' two new fields — are none of -them durable commands. Ending a client's involvement is releasing control and +`quiesce/1`, the create and resume results' two new fields and a bounded +session listing — are none of them durable commands. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by acquiring control and attaching. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 1b45151aa..e2983674f 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -459,7 +459,30 @@ boundary, not an absolute: every tracer restart; it already holds per-runtime process state; and it already monitors pids and handles `DOWN` (`control.ex:805-826`), which is the exact machinery the set needs. - - **The set is bounded because Control monitors every excluded sender and + - **A future trace session must find the MFA exclusions too, not only the + pids.** `Control` holding excluded pids answers "skip this process" for a + session that starts later; it does not answer "clear these functions", + which is the half ADR 0030 names by name. So `Control` retains **both**: the + excluded pid set, and a **ref-counted union of the excluded MFAs** — a + count per identity, incremented when a sender installs it and decremented + when that sender's `DOWN` arrives, so an identity is cleared for a new + session exactly while some live sender needs it. A set without counts + would either leak the identity forever or drop it while another sender + still relied on it. + - **And starting a session is serialised against installing an exclusion.** + Both are `Control` operations, so both run in its process, one at a time: + a session cannot be created between a sender's flag going on and its MFA + clear being recorded. Without that, a session starting in that window + traces a sender that had already excluded itself. The witness starts a + session concurrently with an exclusion, many times, and asserts the + tracer receives nothing from the sender in either order. + - **The set is leak-free and proportional rather than bounded**, and the + distinction is worth the word: nothing caps it, because nothing may refuse + a sender. What holds is that every entry has an owner whose `DOWN` + removes it, so the set is proportional to the senders alive at that + instant and returns to its baseline — normally empty — as they exit. + Calling it "bounded" implied a ceiling the design does not have. + - **Control monitors every excluded sender and removes it on `DOWN`.** An earlier revision kept a pid per invocation forever, which is a leak measured in invocations; senders are short-lived by construction, so the set returns to its baseline — normally empty — diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index ff6c32cd1..d4805a7b2 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -679,9 +679,16 @@ M5 therefore adds an archive-carried source identity that both paths accept, and one shared resolver they both call: - a tracked `SOURCE_IDENTITY` file holding `$Format:%H$` and the commit date, - with a tracked `.gitattributes` marking it `export-subst`, so `git archive` - substitutes the exact commit into the extracted copy while the checkout's - copy keeps the unsubstituted literal; + with a tracked `.gitattributes` marking it `export-subst`. What that does, + stated because the refusals below depend on it: `git archive` rewrites + `$Format:…$` placeholders **inside a file's contents** as it exports, so the + extracted copy carries the exact commit while the copy in a checkout keeps + the unsubstituted literal — which is why an unsubstituted value is a + reliable "this was not exported" signal rather than a formatting accident. + It substitutes only into files marked `export-subst`, and only the + placeholders `git log --format` defines, so the mechanism cannot be extended + to carry a path list — which is why the inventory lives outside the + archive; - a resolver that prefers git when `.git` is present — the existing behaviour, unchanged, including the clean-tree requirement — and otherwise reads `SOURCE_IDENTITY`; @@ -716,12 +723,19 @@ repository: `docs/evidence/M5-closure-runs.md` **beside the archive's own digest and commit**. The closure runner is in the checkout when it stages the archive, so this costs one command it is already positioned to run; -- **the extracted-build witness compares against that recorded inventory**, - not against anything inside the extraction: it takes the built tree's - **path set**, so a file created or deleted during the build is caught even - if every file it names is byte-identical, and its **bytes**, as a SHA-256 - over each path's contents in inventory order, and requires both to match - what was recorded; +- **the extracted-build witness compares a canonical manifest**, taken over + the extraction before the build and again after, and requires the two to be + identical. The manifest is one record per path, **NUL-separated** so no + filename containing a newline or a quote can forge a boundary — `git + ls-files -z` is read the same way — holding the **path**, its **kind and + mode** (regular with its permission bits, symbolic link, directory), and + either the **SHA-256 of its contents** or, for a link, its **target**. A + digest over contents alone would miss a file made executable, a regular + file replaced by a link to one, or a path that appeared and another that + vanished; the path set, the kind and the mode are what close those, and the + before/after pair is what catches a build that writes into its own source + tree. The first manifest is also compared with the inventory the closure + evidence recorded, which is what ties the extraction to the commit; - exactly **one** exclusion, named rather than implied: the build-output roots `_build/` and `deps/`, which the build is supposed to create. Nothing else is excluded, and the list of exclusions is part of the retained evidence, so @@ -1149,6 +1163,16 @@ core is called at all**, which is the only place a refusal can be both truthful and early. The reservation is taken in the daemon's own serial owner, so "atomic" needs no new mechanism: it is one process deciding. +**A duplicate create does not take a second reservation; it waits on the +first.** A reservation is owned by the call that took it and carries a +waiter set: an **exact** re-presentation of the same `command_id` while that +reservation is in flight is not a new activation and must not reserve a +second slot, so it is **coalesced** — it joins the waiters and is answered +with the same result, converting or releasing once for all of them. A +different `command_id` is a different call and reserves on its own. Without +this a client retrying a create it never heard back from spends two of the +sixty-four for one coordinator. + **A reservation is keyed by `(command_id, session_id)`**, and the pair matters in both directions. An earlier revision keyed a resume's reservation by its **session ID alone**, which collides the moment two clients send two different @@ -1583,6 +1607,35 @@ before composition, for the reason all three share: model options carry their references, and options are built before the runtime exists. It is handed the runtime reference as soon as the composition function returns one. +**Connections have an owner, and it is not the listener.** A connection is a +process, a reserved slot, a monitor, an output buffer and — once it has +negotiated — a generation. Something has to hold all five together, and an +earlier revision left them scattered: the listener accepted, the connection +process held its own buffer, and nothing owned the set. So the daemon runs one +fixed **connection registry** beside the relay, and it owns exactly that: + +- **the slot**, reserved at `accept` and released on the connection's `DOWN`, + which is what makes the 512 ceiling a ceiling rather than a handshake rule; +- **the monitor**, so a connection that dies releases its slot, its buffer and + its attachment without anyone calling anything; +- **the buffer-control interface**, so backpressure and the bounded + best-effort writes go through one place rather than each caller reaching + into a connection's state; +- **the generation**, so a broadcast reaches only connections that negotiated + one. **Generation-2 records — `daemon.stopping`, `daemon.notice`, + `control_owner_lost`, `detached` — go only to connections that completed a + generation-2 `initialize`.** An uninitialized socket has agreed no encoding, + so it is **closed with EOF** and told nothing; writing a generation-2 record + to it would be sending bytes under a contract the peer never accepted. + +**Losing the listener does not lose the connections, and losing the registry +does.** `listener_lost` stops new connections arriving; every open one is +still served until the fail-stop closes it, which is why that class has no +wire reason — the listener is what would have written it. The registry is +daemon-fatal for the opposite reason: without it no slot is released, no +`DOWN` is observed and no buffer can be controlled, so every later connection +is a leak and every write is unbounded. + **The admission relay is new in this revision, and it exists because of a window nothing else closes.** Core has no writer epoch — the lease is the daemon's, and core never sees it — so when a lease owner dies with an @@ -1645,7 +1698,17 @@ as though it does: outside the relay entirely, which made the cut a promise the daemon could not keep. - **The tenth is `session.attach`, and it is ticketed for the cut alone.** An + **The tenth is `session.attach`, and it is ticketed for the cut alone — but +it is not performed by a relay task.** The dispatcher monitors **its caller** +(`event_dispatcher.ex:186-192`), so an attach made from a short-lived relay +task would be released the instant that task exited, which is immediately. So +core change 1 adds an internal attach form taking a **stable holder pid** the +dispatcher monitors instead of the caller, the daemon passes its +**connection process**, and the relay's ticket accounts for the call without +owning it. The witness asserts the monitored pid **is** the connection +process, and that the attachment survives the task that started it. + + An earlier revision called it a read and left it out, which it is not: its second leg **mutates the dispatcher**. `Runtime.attach/3` calls `{:attach, …}` on the dispatcher (`runtime.ex:199-210`, `:538`), whose @@ -3803,20 +3866,21 @@ could not be checked.** Every witness here names the **surface** it reads, the **two answers** that must differ on it, and — where the surface is new — the **change that creates it**. A case asserting "core holds N" without saying where N is read is not a case anybody can write; nor is one whose difference -depends on a code path that does not exist. **Five** of this plan's surfaces +depends on a code path that does not exist. **Six** of this plan's surfaces are new work rather than existing behaviour — one per core change, which is not a coincidence: a core change that no witness could read would be a change nothing proves. Each is named where it is used: | Surface | Created by | Read by | | --- | --- | --- | -| The dispatcher's release on `DOWN`, the attacher pid and monitor reference it keeps on the attachment to do it, and the transfers it releases with it | Core change 1 | The concurrent-attachment cases, the ADR 0028 transfer case, the scoped-replacement case and the attach connection-loss case | +| The dispatcher's release on `DOWN`, the attacher pid and monitor reference it keeps on the attachment to do it, the transfers it releases with it, **and `Control`'s per-holder attachment and repetition state** | Core change 1 | The concurrent-attachment cases, the ADR 0028 transfer case, the scoped-replacement case and the attach connection-loss case | | The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | | `Control`'s excluded-pid set, and `Entry`'s redaction of a keyword pair under its own key | Core change 3 | The trace-exclusion cases, and the render pair that must differ | | `quiesce/1`'s three lists, `budget_ms`, `drain_id` and the per-session `fences` map | Core change 4 | The drain cases, the fence cases and the stop line | | `disposition` and `control_entry`, on `create_session_detailed/3` and `resume_session_detailed/3` | Core change 5 | The create and resume connection-loss cases, and the case asserting `create_session/3`'s own return is byte-identical to today's | +| `Loopex.list_sessions/2`'s bound and its early-stop answer | Core change 6 | The startup index-bound case, which asserts a root past the bound is refused **without** the directory having been read in full | -Everything read outside those five exists today — the journal, a supervisor's +Everything read outside those six exists today — the journal, a supervisor's children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. - **Idle shutdown.** A daemon with sessions activated and no work in flight @@ -4215,6 +4279,18 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. and that core started **one** coordinator, not two: the refusal happens before the second call is made, so there is no second coordinator to discover afterwards. + + **It is deterministic, not a race the case hopes to lose.** Both calls are + held at the daemon's serial owner — the one process that takes reservations + — and released in a fixed order, so the case asserts *which* one is refused + rather than that one of them is. A witness that ran two calls and accepted + either outcome would pass against a daemon that reserved after the call. +- **A duplicate create coalesces rather than reserving twice.** A create is + held in flight and the identical `command_id` is re-presented on a second + connection. The case asserts **one** reservation existed throughout, that + both callers received the same result, and that the activation count rose by + **one** — where a second reservation would have spent two slots for one + coordinator, and a second *call* would have been a second create. - **A dormant resume at the ceiling is refused before the call.** A daemon at **64** receives `session.resume` for a dormant session. The case asserts the refusal, and asserts core was **not called** — proved by that session having @@ -4329,7 +4405,8 @@ links rather than one of them, and an earlier revision headed eleven rows | Group | Started by | Bound | Its death | | --- | --- | --- | --- | | **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | -| **Connections**, one per accepted client | The listener | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | +| **Connection registry**, one fixed process | Daemon owner, beside the relay | one | `connections_lost`, daemon-fatal: it owns every connection's monitor and the buffer-control interface, so a daemon without it can neither release a slot nor stop writing to a gone peer | +| **Connections**, one per accepted client | The listener, their slots reserved at `accept` and their monitors held by the connection registry | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | | **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time, except the teardown's lease-owner sweep, which spawns one per lease owner at once and so is bounded by the 512 above | Nothing: monitored, never linked | | **Relay tasks**, one per ticketed call — the eight lease-authorized mutations, `session.create` and `session.attach`; **not** the three artifact-transfer methods, which mutate neither `Control` nor the journal | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 2c5619834..568aa4f19 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -54,7 +54,7 @@ channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above -the core. Core gains exactly five narrow things: support for several +the core. Core gains exactly six narrow things: support for several independent attachments to one session — which is two halves of one change, since it stops same-session supersession from removing an attachment and therefore has to add what removes one instead, a monitor on the attaching @@ -69,7 +69,9 @@ drains through — which carries one coordinator change in two halves, an admission that pauses where cleanup would have begun and a commit that does not re-present itself on an ambiguous answer, both in the same clause, and one new `Control` read, a plain-data projection of every session entry that -quiesce enumerates from and that `Control` has no equivalent of today; and two plain fields on **two new runtime-side functions beside** create and +quiesce enumerates from and that `Control` has no equivalent of today; a bounded session listing, `list_sessions/2`, because the daemon's index bound +cannot be enforced by a read that returns every entry first; +and two plain fields on **two new runtime-side functions beside** create and resume — `create_session_detailed/3` and `resume_session_detailed/3`, so the existing pair keeps its exact return and the embedded facade forwards what it forwards today — `disposition`, saying whether the call was fresh or a replay, @@ -104,7 +106,7 @@ independent attachments to one session through its existing race-free attach barrier and dispatcher, and answers one read-only question about it: given a session ID, does this root hold that session durably. -That query is the second of core's five M5 changes, and it exists because +That query is the second of core's six M5 changes, and it exists because the alternative was worse. The daemon has to validate durable existence before it grants a lease, and before it records a session its index does not hold, and it may not read Store internals to do it. Learning existence by *calling* @@ -149,9 +151,10 @@ effect dispatched, an interaction awaiting an answer, a recovery running, an unresolved `commit_unknown` or an admission executing inside core, so "idle" is not "quiescent" and stopping on idleness would destroy exactly what Outcome 1 exists to prove. And there is nothing to stop it with: core owns -coordinator lifetime, and M5's five core changes — concurrent attachment, a -read-only existence query, trace exclusion, the bounded `quiesce/1` and the -create and resume results' two new fields — none of them stops a coordinator. +coordinator lifetime, and M5's six core changes — concurrent attachment, a +read-only existence query, trace exclusion, the bounded `quiesce/1`, the +create and resume results' two new fields and a bounded session listing — +none of them stops a coordinator. The cost is a real limitation and is recorded as one rather than hidden: at most 64 sessions are activated per daemon lifetime, the 65th activation From c71ff61ae2d0f4022f50e4e247f71c0af808b80a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:40:13 -0700 Subject: [PATCH 169/585] plan(M5): finish D1, and say true things about the tag and M5 The drain contract landed, but thirteen places still spoke the arithmetic's language. The teardown section named "five seconds" twice under a heading that says the implementation measures it; the relay's ticket call derived its bound from "the teardown number, 5 s"; two lease-owner sweeps justified themselves against a five-second phase; the admission cut still had phases 1a and 1b, the second "bounded at the deepest ticket kind's own Store-call depth"; and the executed-count section pointed at an empty table of "the three derived phase bounds". All of them now say what the plan states and what the implementation measures. Numbered drain phases become step names: the fence's own fresh enumeration rather than the phase-4 one, the admission and the cancellation rather than phases 2 and 3, the termination and the fence rather than phases 4 and 5. Two witness names move with them. The fail-stop path stops borrowing the ordered path's deadline and names its own 5 s, which is what keeps its stated 35 s an arithmetic of two numbers this plan still states rather than one it withdrew. Material corrections beside it: a replacing attach at the attachment ceiling takes an atomic net-zero reservation on the slot its own connection already holds, so a request that leaves the count at 512 is not refused at 512; the `v0.1.0` tag is applied rather than awaiting authority, in the README and the roadmap alike; and M5's state comes from the register rather than from a red gate this branch no longer carries. --- README.md | 5 +- docs/README.md | 2 +- ...tachment-residency-and-replay-technical.md | 31 ++- ...-daemon-attachment-residency-and-replay.md | 2 +- ...andoff-over-bootstrap-channel-technical.md | 4 +- ...edential-handoff-over-bootstrap-channel.md | 4 +- docs/plans/M5-technical.md | 178 ++++++++++-------- docs/roadmap.md | 5 +- 8 files changed, 139 insertions(+), 92 deletions(-) diff --git a/README.md b/README.md index 779b6bbf3..cc57e0e72 100644 --- a/README.md +++ b/README.md @@ -112,8 +112,9 @@ version and nothing more: accepted [ADR 0023](docs/adr/0023-experimental-public-session-protocol.md#concept) keeps it independent of the negotiated protocol generation, and it is not a tag, a package, a publication or a compatibility freeze. The source-only `v0.1.0` tag -is applied to the exact `main` integration commit only under separate release -and tag authority; no release has happened. See the +**has been applied** to M4's exact `main` integration commit under the +maintainer's separate release decision; it publishes no package, installer or +service unit and freezes no surface. See the [M4 plan](docs/plans/M4.md#concept) for the accepted scope and its workstreams, [App server operations](docs/operator/app-server.md#concept) for driving it, and the [canonical register](docs/plans/README.md) for its current status. diff --git a/docs/README.md b/docs/README.md index 1f43bbe05..7c9e86f55 100644 --- a/docs/README.md +++ b/docs/README.md @@ -93,7 +93,7 @@ whose path or explicit fragment does not resolve. - [M3 foundations](plans/M3.md#concept) and [technical plan](plans/M3-technical.md#technical-depth) — project skills and core repairs; Closed with retained evidence in the plan. - [M4 headless external consumption](plans/M4.md#concept) and [technical plan](plans/M4-technical.md#technical-depth) — durable interactions, artifact transfers, the floor refresh, observability, and the experimental session protocol driven by an independent Node consumer in plain JavaScript; Closed, with its runs in [M4 closure runs](evidence/M4-closure-runs.md). -- [M5 durable service](plans/M5.md#concept) and [technical plan](plans/M5-technical.md#technical-depth) — daemon-owned session lifetime on the ADR-selected local store within its documented limits, generation-2-only Unix-domain-socket transport, in-memory controller lease with observers and takeover, and at-least-once replay with residency limits over M4; Open planning lookahead with a red gate. +- [M5 durable service](plans/M5.md#concept) and [technical plan](plans/M5-technical.md#technical-depth) — daemon-owned session lifetime on the ADR-selected local store within its documented limits, generation-2-only Unix-domain-socket transport, in-memory controller lease with observers and takeover, and at-least-once replay with residency limits over M4. The [plans register](plans/README.md) carries its state, which is `Open`. - [Development contract](../AGENTS.md) — canonical tool-neutral authority, autonomy, documentation, milestone, and enforcement rules. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 597417f79..90be5ba7e 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -405,8 +405,12 @@ The rule is that **a reservation counts**: `activation_limit` are directly comparable and a client can never read `activations_used < activation_limit` on a daemon that would refuse its next create; -- `active_sessions` is `|activation set|` alone — sessions with a coordinator - now, which is a different question and is why the two fields both exist; +- `active_sessions` is `|activation set|` alone — **the sessions this daemon + has activated in this lifetime**, which is what the set holds and what + `residency: active` means. It is *not* "sessions with a live coordinator": + activation is one-way and the daemon has no way to know a coordinator died, + which this pair says twice elsewhere. It differs from `activations_used` + only by the reservations in flight; - `attachments` counts installed attachments plus reserved attachment slots, for the same reason `activations_used` does; - `connections` counts accepted connections, reservation-free by nature. @@ -415,6 +419,19 @@ So `activations_used` may exceed `active_sessions` for as long as a call is in flight, and settles to it. Reporting the set alone would advertise headroom the very next call would refuse. +**At the attachment ceiling a `replace: true` is net-zero, and it reserves +that way.** A replacing attach ends one attachment and installs one, so it +needs no free slot — but the daemon reserves before it calls core, and a naive +reservation would refuse at 512 a request that leaves the count at 512. So a +replacing attach takes an **atomic net-zero reservation**: in the daemon's +serial owner it claims the slot its own connection's prior attachment for that +session already holds rather than a free one, and it converts or releases that +claim through the same table every other reservation uses, so the count never +moves and no second caller can take the slot in between. A `replace: true` +from a connection that holds no prior attachment for that session is not +net-zero — core will install a second attachment rather than supersede one — +so it reserves ordinarily and is refused at the ceiling like any other attach. + **`session.acquire_control`** | Direction | Key | Type | Optionality | @@ -583,7 +600,7 @@ carry. | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost`, `fatal:listener_lost` — nine in a daemon with artifact transfers and eight without, one per linked component of the fixed set. A lease owner's death is not among them: it closes one session's controller connection with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost`, `fatal:connections_lost` — nine in a daemon with artifact transfers and eight without. **`fatal:listener_lost` is not among them**: the listener is what would have written the record, so no client can be told that reason, which the plan's own class table says and this set contradicted. A lease owner's death is not among them: it closes one session's controller connection with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | @@ -810,6 +827,14 @@ adds a **second notification record family**, `daemon.notice`, beside | `session_id` | the session the notice is about | | `message` | a bounded non-secret sentence for an operator | +**It goes to the connection whose command caused it, and only that one**, and +it is written **after** that command's result rather than before: a client +that sees the notice first would be told about a session it has not yet been +told the identity of. If that connection is gone by then the notice is +**dropped** — it is about a command nobody is waiting on, the session is +reachable regardless, and the daemon's own `stderr` keeps the operator's copy. +It is never broadcast; other connections did not ask. + The activation it follows **succeeded**: the session is usable and reachable by ID, and only its directory entry and index row are missing, to be written by the retry the plan already describes. Reporting that as an `error` would diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index fc101447f..4b169db90 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -47,7 +47,7 @@ brings this ADR also renames the released generation-1 string to `loopex.experimental/1`, so the two generations are named on one scheme and neither claims the `v1` the vision reserves for the stable protocol; that rename is the plan's decision under the 0.x experimental policy, and its -consequence here is that generation 1's pinned digests are recomputed with +consequence here is that generation 1's pinned **schema digest** is recomputed with its new name while everything else about generation 1 stays as it is. That record is a new record family, so it is part of what generation 2's diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index e2983674f..a90209275 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -1006,7 +1006,9 @@ seeds, exactly as the M4 speed work converted the other twenty-one modules. The result is recorded against the baseline in the [verification companion](../developer/verification-technical.md#technical-verification-speed): that application was the fast check's critical path at M4 closure, with 96% of -its time in those twelve modules. Any module that stays serial keeps its +its time in those thirteen modules -- eleven of which reference the credential +variable, the count measured by loading them rather than by globbing +`test/*.exs`. Any module that stays serial keeps its reason recorded beside it. The measurement is evidence about the change, never a condition a test may be weakened to meet. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 8eb5af6cc..d31020166 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -30,12 +30,12 @@ weaker property than the rest of the plane: a secret that has to sit in a process-wide slot for the duration of every call is reachable by anything in the VM that can read the environment, and it is exactly the kind of ambient authority the runtime refuses everywhere else. And it forces serialisation: -the twelve heavy `loopex_llm_reqllm` test modules each install their own +the thirteen heavy `loopex_llm_reqllm` test modules each install their own canary in that slot, so two of them running at once would hand each other's canary to each other's child. The [verification companion](../developer/verification-technical.md#technical-verification-speed) measured the result at M4 closure — that application is the critical path of -the fast check, 96% of its time sits in those twelve modules, and no further +the fast check, 96% of its time sits in those thirteen modules, and no further test change shortens the check while the slot is shared. **Decide that the credential is named by an opaque token bound at diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index d4805a7b2..8af96cb2b 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its four parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fresh phase-4 enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its four parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | @@ -341,7 +341,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the phase-4 enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during phases 2 and 3`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -363,30 +363,35 @@ lifetime suite proves the drain happens in the stop sequence a real operator triggers, and the adapter's credential suite proves a real invocation is not traceable. Neither can reach the branches above, and neither is asked to. -**Every bound derived from a call count carries a witness that executes the -path and asserts the count.** This is a rule of this plan rather than a remark -about one case, and it exists because two independent readings of the create -path produced two wrong numbers before a traced run produced the right one: -six by reading, then nine — ten with the retry — by executing. A count read -off the source is a hypothesis; only a run is evidence, and a bound built on a -miscount is a bound the stop silently exceeds. - -So each of the three derived phase bounds has a case that **counts adapter -calls while the path runs**, by tracing the adapter module — +**Every bound the implementation derives from a call count carries a witness +that executes the path and asserts the count.** This is a rule of this plan +rather than a remark about one case, and it exists because two independent +readings of the create path produced two wrong numbers before a traced run +produced the right one: six by reading, then nine — ten with the retry — by +executing. A count read off the source is a hypothesis; only a run is +evidence, and a bound built on a miscount is a bound the stop silently +exceeds. + +**The plan itself now states no such bound.** The maintainer withdrew the +derived stop arithmetic on 2026-09-20, and what the drain costs is measured at +implementation. The rule survives for the implementation, which does state +bounds: each one is asserted by a case that **counts adapter calls while the +path runs**, by tracing the adapter module — `:erlang.trace_pattern({Loopex.Store.Local, :_, :_}, true, [:global])` where the adapter is reachable, and the suite's controllable store's own call log where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and -`Loopex.Store.Local` is not) — and asserts an exact number, not a bound: - -| Bound | What the case executes and counts | File | Case | Lane | -| --- | --- | --- | --- | --- | - -All three are **core** witnesses, because all three paths are core's: the -daemon contributes no Store call of its own to any of them. A case that -asserted "at most N" would pass on a path that had grown shorter *or* been -restructured into something the phase no longer bounds; asserting the exact -number is what makes a later change to the path fail here rather than at an -operator's `TimeoutStopSec`. +`Loopex.Store.Local` is not) — and asserts an exact number, not a bound. The +executed counts this plan already holds are the ones named in the `quiesce/1` +row of the evidence table above: a fresh create's nine Store calls, ten with +the retry; an attach's one over an empty session and two over eight events; a +resume's eleven over a twelve-record session; a fence's three at worst. + +Those are **core** witnesses, because those paths are core's: the daemon +contributes no Store call of its own to any of them. A case that asserted "at +most N" would pass on a path that had grown shorter *or* been restructured +into something the count no longer describes; asserting the exact number is +what makes a later change to the path fail here rather than at an operator's +`TimeoutStopSec`. **Test honesty.** Future test bodies are written with their implementation; a missing witness is never a pass. **Every witness named in this plan pair names @@ -1431,7 +1436,11 @@ runtime — rather than against a staged one the plan would have to invent: 8. **Begin accepting**, then **print the readiness line**. No lease owner exists at this point, and none is started here: one is started -when a session is activated, which cannot happen before a client connects. +at the **first lease operation for a session** — an `acquire_control`, whether +or not that session is active — which cannot happen before a client connects. +An earlier revision said "when a session is activated", which is the rule this +pair corrected elsewhere and forgot here: dormant recovery acquires before it +resumes. A failure at any step exits non-zero with that step's reason class, after the reverse cleanup below, and touches nothing after it. @@ -1490,7 +1499,8 @@ Four rules, each narrow: continue before the caller's next line. The `:go` message turns a hope about scheduling into a happens-before: the owner cannot pass step 5 until a message exists, and the message does not exist until the monitor does. The - wait is bounded by the same phase-6 number every other wait uses, and a + wait is bounded like every other wait in this plan — an absolute deadline + the implementation measures — and a `:go` that never arrives — a command process that died between steps 2 and 4 — ends the owner through the reverse cleanup with nothing acquired, which is correct, because there is nobody left to report a daemon to. @@ -1742,13 +1752,14 @@ process, and that the attachment survives the task that started it. replacement would see no ticket for a call that was about to be made. **That call carries an explicit bound and does not inherit - `GenServer.call/2`'s hidden five seconds**, which is the same discipline the - rest of this plan applies to every call that matters: the bound is the - teardown number, 5 s, because the relay's whole job here is to write a row - and answer, and a relay that cannot do that in five seconds is a relay the - daemon has lost. An unanswered ticket call is therefore not a silent - five-second stall inside a client's mutation; it is `relay_lost`, the class - that already exists for a relay the daemon can no longer account through. + `GenServer.call/2`'s hidden default**, which is the same discipline the rest + of this plan applies to every call that matters. The relay's whole job here + is to write a row and answer, so the bound is sized for that and for nothing + else — the implementation states it as an executed count and measures it — + and a relay that cannot write a row and answer inside it is a relay the + daemon has lost. An unanswered ticket call is therefore not a silent stall + inside a client's mutation; it is `relay_lost`, the class that already + exists for a relay the daemon can no longer account through. - **The relay installs that monitor inside the owner's first ticket call, before it acknowledges**, which is what makes the ordering argument below true rather than nearly true. A relay that monitored on some other occasion @@ -1788,7 +1799,7 @@ process, and that the attachment survives the task that started it. later with `GenServer.reply/2` when the last of that session's tickets settles. A relay that ran the wait inside its callback would stop answering every other session's ticket calls for as long as one session's mutation - took, and the five-second bound on a ticket call would then be measuring + took, and the bound on a ticket call would then be measuring somebody else's core work rather than the relay's own responsiveness — turning an unrelated slow mutation into `relay_lost`. With deferral that bound measures exactly what it claims to: whether the relay is alive and @@ -1809,13 +1820,15 @@ process, and that the attachment survives the task that started it. leaving the sentence standing gave this file two cut semantics — one that waits unconditionally and one that proceeds at a bound — with every witness written against the second. One stands: **the cut closes, the wait - waits, 1b proceeds.** + waits, the stop proceeds.** What the cut buys is therefore narrower than that sentence claimed, and it - is the true thing: after 1a **no new work enters core through the daemon**, + is the true thing: after the cut **no new work enters core through the + daemon**, so the set quiesce is about to read can only shrink from admitted work finishing, never grow from new work arriving — except by a ticket still - settling, which is why phases 4 and 5 re-read the enumeration and why the + settling, which is why the termination and the fence re-read the + enumeration and why the create residual below is stated. That is why every call that mutates `Control` or the journal goes through this one process. The narrower claim is the true one; the transfer methods above are the reason it has to be @@ -1874,8 +1887,8 @@ Store, last of all**, out of reverse order. The lease owners go before the relay because the relay is what holds their tickets, and stopping it first would discard a ticket an owner could still be waiting on. They are stopped as **one collective sweep, not one at a time**, against the teardown deadline: -up to 512 of them exist, and 512 sequential stops inside a five-second phase -is arithmetic that does not work. The sweep — every stop sent at once, one +up to 512 of them exist, and 512 sequential stops inside one teardown +deadline is arithmetic that does not work. The sweep — every stop sent at once, one wait for all of the exits, a kill for whatever is left at the phase's end — and the disposition of a lease owner killed that way are written out with the teardown below. The @@ -1987,7 +2000,7 @@ only from the exit the owner observes on its own link.** For each component: 1. The owner sets `stopping` to that component, as before. 2. It `spawn_monitor`s a **helper** whose whole body is `GenServer.stop(pid, :normal, remaining(deadline))`, where `remaining/1` is - what is left of the phase's own deadline and no component carries a budget + what is left of that step's own deadline and no component carries a budget of its own. The helper is monitored, never linked, so whatever that call raises, exits or returns dies with the helper and never reaches the owner. The owner needs nothing from it — not its @@ -2030,10 +2043,10 @@ revision, its `{:timeout, _}` / `{:noproc, _}` / catch-all clauses, its component's fate from what a library function did to the caller, and row 1 shows that is not derivable. -**What bounds each step.** The outer `receive` waits until the phase's +**What bounds each step.** The outer `receive` waits until that step's **absolute deadline** — the shared teardown deadline for every non-Store stop, the Store's own fixed phase for the Store — and the helper is given what -remains of it, so a component is bounded once rather than twice and the phase +remains of it, so a component is bounded once rather than twice and the step is bounded whatever the component does. The inner `receive` after the kill carries no `after`, and needs none: `Process.exit(pid, :kill)` on a live process is unconditional, and on one already dead the exit the owner is @@ -2400,8 +2413,8 @@ late `session.attach` is not in this class: `begin_attach/3` requires the entry to be `:active` already (`control.ex:1237`). **The teardown stops the lease owners as a collective sweep, not one at a time.** -Up to 512 of them exist, and stopping them in sequence inside five seconds was -arithmetic nobody did: the owner spawns one stop helper **per lease owner, all +Up to 512 of them exist, and stopping them in sequence inside one teardown +deadline was arithmetic nobody did: the owner spawns one stop helper **per lease owner, all at once**, then waits in **one** loop until every one of those pids has produced an exit on the owner's own link — the same link it already holds, so the exits are `{:EXIT, pid, reason}` and not monitor `DOWN`s — and at the @@ -2431,8 +2444,9 @@ stopped after them. Its session's controller connection is already gone, step 3 having closed every connection, so a lease owner ended here produces no `control_owner_lost` and there is nothing left to send one to. -**`budget_ms` is still core's to derive and report**, for the reason below; -what changed is that it is one phase among eight rather than the whole drain. +**`budget_ms` is still core's to derive and report**, for the reason below: +it bounds the drain's own wait, and it is the one figure in the stop that no +part of the daemon can compute. The budget is derived rather than chosen because the cancellation it waits on is already bounded by core: `cli_backstop_ms` is the number core itself says a @@ -2464,13 +2478,16 @@ the failed-start reverse cleanup, for the same reason. **The teardown has one deadline covering every non-Store action after the drain, and the implementation measures it rather than this plan naming a -number.** An -earlier revision named the clock and never gave it a value, which left the -operator bound unstatable and every "what remains" reference undefined. Five -seconds is **chosen, not derived**: the notification writes are one +number.** An earlier revision named the clock and never gave it a value, +which left every "what remains" reference undefined; the revision after that +named a number and derived an operator bound from it, which the maintainer +withdrew with the rest of the arithmetic. What this plan fixes is the shape: +**one deadline, `teardown_ms`, covering every non-Store action**, sized for +work that is milliseconds by construction — the notification writes are one attempt into an existing buffer, the closes are closes, the lease owners and the daemon's own processes run no `terminate/2`, and the transfers owner's -closes the descriptors it holds — each of them milliseconds. +closes the descriptors it holds. The figure the implementation settles on is +the one the operator page carries. **One process under this deadline is not like the others, and an earlier revision's justification was false for it.** That revision said "of the @@ -2487,11 +2504,12 @@ teardown deadline and killed at it.** A tree killed that way is crash-equivalent only sense this plan ever claims — about the journal, not about processes — and its trapping descendants go on unwinding on their own clock afterwards, which the daemon does not wait for and the halt at the end of the sequence -ends. Five seconds is therefore a ceiling for the work the teardown *performs*, not -a promise about what the runtime's subtree has finished, and the drain is why -that is affordable: by the time step 5 runs, every coordinator quiesce could -not settle has already been fenced and terminated inside core. It is -recorded in the limits table with that rationale. +ends. `teardown_ms` is therefore a ceiling for the work the teardown +*performs*, not a promise about what the runtime's subtree has finished, and +the drain is why that is affordable: by the time step 5 runs, every +coordinator quiesce could not settle has already been fenced and terminated +inside core. The closure obligation carries the measured figure into the +operator page with that rationale. **The teardown deadline starts when `quiesce/1` returns**, and it covers every remaining non-Store action: the stop records, the connection closes, the @@ -2536,7 +2554,7 @@ long wait but an immediate exit in the waiting process — which for the owner would be a shutdown that never runs. Nothing in this repository slices a wait today, so the rule is stated here: -- **Every phase is an absolute instant**, `System.monotonic_time(:millisecond) +- **Every wait is an absolute instant**, `System.monotonic_time(:millisecond) + budget`, computed once. Deadlines compose by comparison, not by subtracting one timeout from another, so no arithmetic can produce a negative `after` — which is the other way `after` fails, as the 1 ms stop @@ -2544,7 +2562,7 @@ today, so the rule is stated here: - **Every wait is taken in slices of at most `@wait_slice_ms`, 60_000** — the obligation falling on **`quiesce/1`'s own waits**, the cancellation being the only bound that is unbounded by construction and core being where it is - enforced; every other phase is a fixed number far inside the domain. A + enforced; every other wait is a fixed number far inside the domain. A minute is long enough that slicing costs nothing measurable and short enough to be far inside that domain. After each slice the waiter compares the clock with the deadline and either waits again or gives up. A budget of @@ -2572,25 +2590,24 @@ the owner fixes. set of sessions that could still grow underneath it. So the cut is a call **and then a wait**, which an earlier revision folded - into one five-second step it could not possibly contain. The owner calls + into one step it could not possibly contain. The owner calls the **relay** — whose scope this extends to cover `session.create` and `session.attach` as well as every ticketed mutation, ten calls in all — and the relay **closes admissions and - answers at once**: that is phase **1a**, an acknowledgement of a state - change, five seconds being a bound on the relay's responsiveness and on - nothing else. The owner then **waits for the tickets already inside core to - settle**, which is phase **1b**, bounded at the deepest ticket kind's own - Store-call depth. + answers at once**: an acknowledgement of a state change, bounded on the + relay's responsiveness and on nothing else. The owner then **waits for the + tickets already inside core to settle**, for a bound the implementation + measures. Folding the two together was the defect: a ticket settles only when its core call answers, a prompt's commit is bounded by the Store's 30 s and by core's one retry, and `SessionCoordinator.command/3` waits `:infinity` for it (`session_coordinator.ex:146-149`) — so a `SIGTERM` arriving during any - ordinary prompt would have blown a five-second acknowledgement and turned - an operator stop into `relay_lost`. Refusing new work is instant; waiting + ordinary prompt would have blown an acknowledgement sized for a relay and + turned an operator stop into `relay_lost`. Refusing new work is instant; waiting for admitted work is not, and the two now have their own bounds. - **At 1b's bound the stop proceeds**, and what that costs is stated. A + **At the wait's bound the stop proceeds**, and what that costs is stated. A ticket still settling is a core call still running, so `Control` is not quite the frozen set an unconditional wait would have given: a still-running mutation leaves its session `:active`, which drains and fences exactly as @@ -2835,8 +2852,8 @@ revision passed the daemon's teardown deadline in, which contradicted the rule two paragraphs later that the teardown clock starts when `quiesce/1` *returns*: a deadline cannot both bound the drain and begin after it. It takes the runtime and nothing else. Core derives the budget, enforces it, and -returns it as `budget_ms`; the daemon's own five seconds start when the call -comes back. A long derived budget is not a hazard the argument would have +returns it as `budget_ms`; the daemon's own `teardown_ms` starts when the +call comes back. A long derived budget is not a hazard the argument would have fixed either — it is what the operator bound above already reports, and what a service manager's own timeout is set against. @@ -2849,7 +2866,8 @@ can hold. `budget_ms` is the drain budget core derived and used. `drain_id` is the label this drain reports, and `fences` is what the fence below actually did for each session it touched — `:committed` where the epoch moved, `:superseded` where the one transaction that could still linearize won the -race first, `:not_needed` where the phase-4 enumeration holds no entry for the session at all, and +race first, `:not_needed` where the fence's own fresh enumeration holds no +entry for the session at all, and `{:unknown, head}` where the Store could not say, **carrying the head the fence was built from**, because that head is the only thing a successor can discriminate on. **Without `fences` a fence's failure is @@ -2989,7 +3007,7 @@ carried: it described three outcomes and returned none of them. was available and was declined, because it would buy a journal annotation at the price of a one-way root. -3. **Terminate every coordinator, then fence every session — two phases, in +3. **Terminate every coordinator, then fence every session — two steps, in that order, over the same set.** When the budget is spent, core terminates **every enumerated coordinator** — settled, unsettled and acquiring alike — and waits for every `DOWN`; that is the **termination**, bounded by the deadline the implementation @@ -3229,8 +3247,8 @@ carried: it described three outcomes and returned none of them. epoch has moved and the adapter refuses it `:stale_owner_epoch` (`state.ex:548-551`). - `:not_needed` therefore survives for one case only: a session the **fresh - phase-4 enumeration holds no entry for**. Not an `:unavailable` entry, + `:not_needed` therefore survives for one case only: a session the + **fence's own fresh enumeration holds no entry for**. Not an `:unavailable` entry, which an earlier revision used and which proves nothing about whether a coordinator once existed; no entry at all. @@ -3301,7 +3319,7 @@ carried: it described three outcomes and returned none of them. coordinator is gone. A stale refusal is proof that it did — and proof that nothing else will, there being no process left to send one. Reattempting would spend a third and fourth Store call to fence a session that no longer - has anything to fence, and would make the phase's bound a number nobody + has anything to fence, and would make this step's bound a number nobody could state. A `commit_unknown` is the opposite case: the transaction may have linearized, so it is **resolved once**, never re-proposed under a new identity and @@ -3358,8 +3376,8 @@ carried: it described three outcomes and returned none of them. idle session `"admission" => "rejected_no_active_run"` (`session_state.ex:1750-1761`); there was nothing to cancel, nothing is owed, and the session is reported `settled` without waiting for a terminal - that no run will produce. It is still terminated and fenced in phases 4 - and 5 like every other enumerated session. + that no run will produce. It is still terminated and fenced like every + other enumerated session. **Otherwise a session is `settled` exactly when the run the drain aborted has its terminal fact committed**, and that is read on a surface core already @@ -3617,9 +3635,9 @@ to write. the component that already died — under the same discipline as every other stop: a monitored helper calling `GenServer.stop(pid, :normal, remaining(deadline))`, the owner waiting on - its own link until the shared teardown deadline and killing on expiry — the - same five-second deadline the ordered path uses, started when this path - began. This is not tidiness: the executor is + its own link until this path's own deadline and killing on expiry. That + deadline is **5 s**, named here rather than measured, because on this path + it covers one stop and nothing else; it is started when this path began. This is not tidiness: the executor is the one linked process whose work reaches outside the VM, and stopping it is what tells its Port-owning workers to terminate the captured process groups. Halting without stopping it would never start that cleanup at @@ -3665,7 +3683,7 @@ to write. **A fail-stop has an operator bound too, and it is much smaller than an orderly stop's.** Only two of its steps can wait: the executor stop, under - the same teardown deadline, and the Store stop, in its own fixed + this path's own 5 s, and the Store stop, in its own fixed thirty. Nothing else waits on anything — there is no drain, no admission, no fence, no coordinator to terminate and no runtime tree to bring down. So **the maximum for any fatal class is 5 s + 30 s = 35 s**, with no @@ -4251,7 +4269,7 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. **And the slicing obligation is `quiesce/1`'s, not the daemon owner's.** The cancellation is the one part whose bound is unbounded by construction, and it is - enforced inside core; every other phase is a fixed number far below the + enforced inside core; every other wait is a fixed number far below the domain. The wait rule therefore binds core's own waits in the drain, and the daemon's owner inherits it as a rule it cannot violate rather than one it must remember. All of them run diff --git a/docs/roadmap.md b/docs/roadmap.md index 42caae3c2..ffb7b0c05 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -96,8 +96,9 @@ with its complete holder inventory. It maps the shared facade through strict foreground stdio JSONL, and an independent consumer written in plain JavaScript selects a skill, answers an interaction, observes a real tool result, retrieves an artifact and recovers after process loss. The daemon remains a later host. -The source `VERSION` is `0.1.0`; the annotated `v0.1.0` tag on M4's exact -integration commit on `main` awaits separate release authority. Neither is a +The source `VERSION` is `0.1.0`, and the annotated `v0.1.0` tag **is applied** +to M4's exact integration commit on `main`, taken under the maintainer's +separate release decision. Neither is a package, installer, service or public-surface freeze. The [plans register](plans/README.md) remains the authority for its current state. From e8dfbc72dfd2a8bab717824c7f0e12120e4f3ad2 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:45:12 -0700 Subject: [PATCH 170/585] plan(M5): the relay's two rules, the drain's context, one migration The relay acknowledged a ticket it had not yet started a task for, which made the acknowledgement mean less than every later reading of the ticket set assumes: a relay dying in that window lost the call with the ticket and left a client's mutation neither made nor refused. It now writes the row and spawns the monitored task before it replies, in the one callback. Pipelining had no rule at all. It gets the narrow one: at most one unresolved mutation ticket per session, the queue living in the lease owner that is the only process making those calls for a session, so pipelined mutations are admitted in arrival order one at a time and "the in-flight admission set is empty" is a set of at most one rather than a queue of unknown depth. Within a session the daemon promises ordering, not parallelism, which core's coordinator imposes anyway. `quiesce/1` ran in the daemon owner's process with a `%Loopex.Runtime{}` that is a supervisor and a token, and then committed a fence as a Store transaction. The store handle lives in `Control`'s state, so the enumeration now answers a transient core-internal drain context that carries it beside each entry's status, coordinator pid and owner. The status census stops costing 5,000 ms per session and takes one absolute deadline for all of them. The Concept copied the recovery algorithm backwards -- ask the Store, then compare -- which is the reading this pair's mechanics section spends three paragraphs refuting. It compares heads first. Two claims were false and are corrected rather than softened. The embedded API is not unchanged: the dispatcher supersedes on `session_id` alone today with no `replace` option anywhere in core, so a second attach ends the first, and after core change 1 it does not. That is a behaviour note in the Concept and a second migration note beside the generation string. And a failed start does not always leave no marker held: its Store stop is the same fixed 30 s, so a wedged filesystem leaves the stale marker ADR 0031 already recovers. The startup text also still said a lease owner begins at activation, the rule this pair corrected twice elsewhere. --- docs/plans/M5-technical.md | 130 ++++++++++++++++++++++++++++++++----- docs/plans/M5.md | 24 ++++++- 2 files changed, 135 insertions(+), 19 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 8af96cb2b..bdeb152ad 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes, with `Control`'s own attachment and repetition state scoped by the same holder pid**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes, with `Control`'s own attachment and repetition state scoped by the same holder pid**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from — a transient, core-internal drain context carrying the Store handle `Control` holds beside each entry's status, coordinator pid and owner, because `%Loopex.Runtime{}` carries a supervisor and a token and no store**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -145,7 +145,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its four parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in arrival order, one at a time**, the second held in its lease owner until the first ticket resolves, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; and a relay killed in the instant after it acknowledged a ticket asserted to have **already started that call**, proved by the mutation reaching core and producing its durable record, which a relay that replied before spawning would have lost with the ticket. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted, and it is proved at the **process boundary** rather than inside the body: what the bridge spawns holds no token, no registry handle and no credential — `set_on_spawn` traces a spawned closure's **entry call**, so a token in that closure is exposed before any line of it runs — and it receives the token by message only after its exclusion is established and confirmed. The tracer is asserted to receive **no raw trace message from that process carrying the token at any point**, entry included, while a non-excluded control process spawned with the same closure shape does produce one; `exclude_self/2` returns before the token is sent, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -341,7 +341,7 @@ core-internal states a daemon cannot construct through the socket. | --- | --- | --- | --- | | Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split` | fast | +| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split`; `the status census is bounded by one deadline, not one per session` — five hundred and twelve enumerated sessions whose coordinators never answer, asserted to be reported `unsettled` within one census deadline rather than within five hundred and twelve of them; `the enumeration carries the store handle the fence commits through`, asserted by a drain that fences with no store handle of its own | fast | | **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | @@ -454,8 +454,24 @@ over generation 1's method set under the exact-generation rule: a generation-1 client sees no daemon method and no lease field, the daemon refuses a generation-1-only initialize, and the foreground server keeps serving generation 1 unchanged. No mixed-generation stream is promised. The private -journal, its adapter and its format are unchanged; the embedded API, public -events, snapshots, artifact formats and the executor protocol are unchanged. +journal, its adapter and its format are unchanged; public events, snapshots, +artifact formats and the executor protocol are unchanged. + +**The embedded API's *shape* is unchanged and one of its *behaviours* is +not**, which an earlier revision folded into "the embedded API is unchanged" +and thereby denied. `Loopex.attach/3` (`loopex.ex:134`) keeps its arity, its +arguments and its result. What changes is what a second attach to the same +session does. Today the dispatcher supersedes unconditionally: it splits +`state.attachments` on `session_id` alone +(`runtime/event_dispatcher.ex:812-818`), and no `replace` option exists +anywhere in core — `Loopex.attach/3`, `Runtime.attach/3` and the dispatcher +mention none. So an embedded caller that attaches twice for one session, from +one process or from two, sees the first attachment superseded and its +transfers released. **After core change 1 it does not**: supersession +requires `replace: true` and is scoped to the attaching process's own prior +attachment, and a second attach without it leaves both attachments live. That +is the behaviour the daemon exists to have, and it is the one the migration +note below names. Source `VERSION` is distinct from protocol generation, provider build and schema digest. @@ -568,7 +584,7 @@ root grew past the ceiling under an earlier process. A session in a retired root is reached only by reopening that root. -**The one migration note M5 owes, and it is one string.** A `0.1.0` client +**M5 owes two migration notes, and the first is one string.** A `0.1.0` client sends `loopex.session.v1-experimental` in its `initialize` generations list. Against a `0.2.0` server that list has no common generation, so the server refuses with `unsupported_generation` — the refusal ADR 0023 already defines @@ -586,6 +602,22 @@ There is no compatibility mode and none is offered: accepting both strings for one generation would put two names on one contract, which is the thing this rename exists to stop, and it would have to be removed later anyway. +**The second note is for embedded callers, and it is one behaviour.** A +caller that relied on `Loopex.attach/3` superseding its own earlier +attachment to a session — the only way core offers today, since the +dispatcher supersedes on `session_id` alone with no option to say otherwise — +must **pass `replace: true`** after core change 1, and must pass it from the +**same process** that holds the attachment it means to replace. A caller that +does neither gets two live attachments where it used to get one, which is a +resource leak rather than a refusal and so will not announce itself: the +older attachment keeps its resident window and its queue until its process +ends, and the dispatcher's `DOWN` release is what eventually collects it. +Callers that attach once per session, which is every caller in this +repository, need no change at all. **Rollback is symmetric and needs no +note**: a root carries no attachment state, attachments being runtime-local +and transient, so reverting core change 1 restores the old behaviour for +whatever is running next. + **Rollback is unaffected by the rename**, because a generation string is negotiated and never persisted. A root written by a `0.2.0` daemon carries no generation name anywhere, so removing the daemon restores the `0.1.0` @@ -1743,13 +1775,40 @@ process, and that the attachment survives the task that started it. construction (`runtime.ex:236-244`) — so a quiet observer sitting on a read would have blocked every takeover for that session for as long as it sat there. A read grants nothing, orders nothing and cannot overtake a mutation. -- **The ticket is recorded synchronously, before the call exists.** The lease - owner — or, for a create, the connection process — **calls** the relay and - waits for the acknowledgement, and only then - does the relay spawn the monitored task that performs the core call. A cast - would have left the window open at the other end: an owner could pass its - holder check, send its ticket and die before the message arrived, and a - replacement would see no ticket for a call that was about to be made. +- **The ticket is recorded and the call is started before the + acknowledgement, both inside the one callback.** The lease owner — or, for a + create, the connection process — **calls** the relay and waits, and the + relay writes the ticket row **and spawns the monitored task that performs + the core call** before it replies. A cast would have left the window open at + the other end: an owner could pass its holder check, send its ticket and die + before the message arrived, and a replacement would see no ticket for a call + that was about to be made. Replying before the spawn would open the window + at *this* end, and an earlier revision did exactly that: the owner would + hold an acknowledgement meaning "admitted" for a call no process had yet + been created to make, and a relay that died in between would lose the call + with the ticket, leaving the client's mutation neither made nor refused. The + acknowledgement therefore means two things at once — the ticket exists and + the call is running — which is what every later reading of the ticket set + assumes. + +- **At most one unresolved mutation ticket per session**, which is the + relay's rule and the answer to pipelining. A client may send several + mutations on one connection without waiting, and ADR 0023 does not forbid + it. The **lease owner** is the only process that makes ticket calls for a + session, so it is where the queue lives: it holds the client's next mutation + until its current ticket resolves, replying later with + `GenServer.reply/2`, and pipelined mutations are therefore admitted in + arrival order, one at a time. The relay asserts the invariant rather than + relying on it — a second ticket call for a session that already has an + unresolved one is answered `{:error, :ticket_outstanding}`, which a correct + daemon never produces and a case asserts is never produced. What this costs + is stated: within one session the daemon promises **ordering, not + parallelism**, which costs nothing real because core serializes a session's + mutations at its coordinator anyway. What it buys is that "the session's + in-flight admission set is empty" — the condition ADR 0033's takeover waits + on, and the condition a lease owner retires on — is a set of at most one, + decided by one resolution rather than by draining a queue of unknown + depth. **That call carries an explicit bound and does not inherit `GenServer.call/2`'s hidden default**, which is the same discipline the rest @@ -3401,6 +3460,18 @@ carried: it described three outcomes and returned none of them. session lands in `unsettled` with its terminal still committed by the coordinator before termination ends it. + **The census as a whole is bounded by one absolute deadline, not by 5,000 + ms per session.** The per-coordinator bound is the coordinator's own and is + not the drain's; taken one session after another it would make the census + cost the number of enumerated sessions times that bound — up to 512 of + them — which is the arithmetic this plan stopped doing. So the reads are + **issued together** and waited for against **one absolute instant the + implementation measures**, computed once when the census begins, and a + session whose status has not answered by it is `unsettled` under the same + fail-closed rule that covers a refusal or a timeout. Nothing is lost by + that: a status that did not answer was never going to be read as + settled. + No core change is needed for this, which is worth saying plainly after several rounds of adding things: the read exists, quiesce is outside `Control` and can make it, and a coordinator that refuses it — @@ -3499,6 +3570,22 @@ per-session calls the caller's own tasks make **directly to coordinators and to the Store**, never through `Control`. (An earlier revision said "exactly two bounded reads" and then listed one and a negation.) +**The enumeration carries the drain context, because the runtime reference +does not.** `%Loopex.Runtime{}` is `defstruct [:supervisor, :token]` +(`runtime.ex:46`) — a supervisor pid and a token, and nothing else. The Store +handle lives in `Control`'s own state (`control.ex:218`), and the drain needs +it directly: the fence is a Store transaction and the `{:unknown, head}` +resolution is a Store query, and both are made by the caller's tasks rather +than through `Control`. So the enumeration answers a **drain context**, not +only a session list: the Store handle `Control` holds, and per session the +status, the coordinator pid and the owner. It is core-internal by +construction — one part of core answering another, in the caller's process, +crossing no durable, public or executor boundary — and it is **transient**, +valid for the call that received it and never retained by the daemon, which +holds no Store handle before the drain and holds none after it. That is part +of core change 4 with the enumeration itself, and the ownership table names it +there. + **That enumeration does not exist today, and adding it is part of core change 4.** `Control` answers `{:session_status, token, session_id}` for **one** session (`control.ex:473-481`) and has no call that projects `state.sessions` @@ -3833,7 +3920,8 @@ earlier revision named. A bound socket is **closed, and its path left in place** — reverse cleanup unlinks nothing, for the same reason no shutdown path does — a `daemon/` subdirectory this start created is removed **when it is empty**, by the matrix below — no lease owner can exist -yet, since none is started before a session is activated — and **every pid the +yet, since none is started before a client's first lease operation and no +client has connected — and **every pid the composition function returned is stopped in reverse start order** — runtime, executor, workspace lease, transfers where it exists — then the tracing capability, custody and the registry, and the Store last, so its `terminate/2` @@ -3852,8 +3940,18 @@ map it already holds. The owner does this in its own start path rather than leaving it to a crash, because a crashing owner would take the links down without releasing the marker or removing the directory it made. A daemon that refuses to start -leaves **no marker held** — which is what lets an operator fix the cause and -try again without a recovery step. +**releases the marker on the ordinary path**, which is what lets an operator +fix the cause and try again without a recovery step. + +**With one residual, and it is the orderly stop's residual reached by the +other road.** The Store stop here is the same fixed 30 s, so a Store that does +not release within it is killed and the marker it held survives — exactly the +stale marker ADR 0031's verified recovery answers, reclaimed where the +recorded holder is proved dead and refused `store_writer_unverifiable` where +it cannot be decided. "Leaves no marker held" is therefore a claim about the +path, not about every outcome, and the witnesses below assert the path. No +second rule is needed and none is stated: a failed start that wedges the +filesystem leaves the root in the state a wedged orderly stop leaves it in. **What a failed start leaves on disk is one matrix, because three passages gave three answers.** One said a bound socket is closed with its path left in diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 568aa4f19..aa86d3de7 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -435,8 +435,12 @@ transaction still in flight either wins before the fence and is observed or loses after it and is refused as stale. **That fence's identity is derived from the session's own durable head**, not from anything the daemon holds in memory, so a fence the Store could not resolve is resolvable by whatever -starts next: it rereads the head, recomputes the same identity and asks the -Store what became of it. And the answer says, per session, what the fence +starts next, in this order: it **rereads the head and compares it with the +recorded one**, and a head that has moved is already the answer — that fence +either moved it or can no longer commit at all. Only an unmoved head sends it +on to ask the Store what became of the transaction that identity names. +Asking first and comparing after answers nothing, because a moved head makes +the question name a transaction nobody ever proposed. And the answer says, per session, what the fence actually did — committed, superseded by a transaction that won the race, unknown, or not needed — because a fence whose failure no caller can observe is not a fence anybody can rely on. Terminating the coordinator alone @@ -805,7 +809,21 @@ state root between the daemon and the foreground surfaces is stopping one and starting the other. That is also the rollback: dropping back to `0.1.0` means stopping the daemon and using the M4 foreground server and CLI on the same root, which nothing durable prevents, because no journal record depends on the -lease, the session index or any residency state. Outcome 6 changes no public +lease, the session index or any residency state. + +**One embedded behaviour does change, and it is named here rather than left +to the mechanics, because it is observable.** `Loopex.attach/3` keeps its +shape, but today a second attach to a session supersedes the first whoever +made it — core has no way to ask for anything else — and after the +concurrent-attachment change it supersedes nothing unless the caller says +`replace: true` and holds the attachment it means to replace. A caller that +attached twice to one session and relied on the older one going away must now +say so, and one that does not gets two live attachments rather than a +refusal. Every caller in this repository attaches once and is unaffected. +Nothing durable is involved — attachments are runtime-local and transient — so +rollback needs no step. + +Outcome 6 changes no public or durable surface at all; its one visible effect is that a host composing this adapter passes a credential token with the call and composes a routing registry and a custody process behind it. From 794517c7a751e2f6ac218c39efb1c62d51e657ba Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:47:59 -0700 Subject: [PATCH 171/585] plan(M5): adversarial pass over the relay and drain additions Three findings against this round's own additions. Core change 4 makes the drain's fence tasks call `Store.transact` directly on the handle the enumeration hands them, which makes the second caller in core. The `:awaiting_owner_barrier` row rests its whole argument on that caller count -- "no owner group or worker can commit" is proved by enumerating them -- so the count is corrected where it is used rather than left to be found false later. It weakens nothing: the fence is the writer that row protects the session with, and it runs after the coordinator is gone. The one-unresolved-mutation-ticket rule said "per session" without saying which of the ten calls are mutations. Two are not: `session.create` has no session to be one-per and its ticket is the connection process's, and `session.attach` is ticketed for the cut alone and is not performed by a relay task at all. Both already had their own ceilings and reservations; the rule covers the eight epoch-carrying methods. The relay-ordering witness was a kill race -- "killed in the instant after it acknowledged" -- which is a synchronization nobody can write. It becomes an in-VM read of the relay's own state at the instant the acknowledgement arrives: the ticket row and a live task pid for it, the task monitored rather than linked. A relay that replied before spawning passes the first assertion and fails the second, which is the difference the case exists to make. --- docs/plans/M5-technical.md | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index bdeb152ad..f03eabaea 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -145,7 +145,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its four parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in arrival order, one at a time**, the second held in its lease owner until the first ticket resolves, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; and a relay killed in the instant after it acknowledged a ticket asserted to have **already started that call**, proved by the mutation reaching core and producing its durable record, which a relay that replied before spawning would have lost with the ticket. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in arrival order, one at a time**, the second held in its lease owner until the first ticket resolves, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; and the ordering inside the ticket callback asserted on the surface that shows it: at the instant the acknowledgement arrives at the caller, the relay's own state is read in-VM and asserted to hold **both** the ticket row **and** a live task pid for that ticket, and the task is asserted to be monitored rather than linked, so a relay that died next would leave the call running rather than take it down. A relay that replied before spawning passes the first assertion and fails the second, which is the difference the case exists to make. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted, and it is proved at the **process boundary** rather than inside the body: what the bridge spawns holds no token, no registry handle and no credential — `set_on_spawn` traces a spawned closure's **entry call**, so a token in that closure is exposed before any line of it runs — and it receives the token by message only after its exclusion is established and confirmed. The tracer is asserted to receive **no raw trace message from that process carrying the token at any point**, entry included, while a non-excluded control process spawned with the same closure shape does produce one; `exclude_self/2` returns before the token is sent, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -1810,6 +1810,18 @@ process, and that the attachment survives the task that started it. decided by one resolution rather than by draining a queue of unknown depth. + **Two of the ten are not mutation tickets and the rule does not reach + them**, stated because a rule that silently excluded them would be read as + covering them. `session.create` has no session to be one-per, its ticket is + the connection process's rather than a lease owner's, and it already takes + no part in the per-session grant-blocking rule for the reason given above; + what bounds creates is the activation ceiling and its reservation. + `session.attach` is ticketed for the cut alone and is not performed by a + relay task at all; what bounds attaches is ADR 0032's attachment ceiling and + its reservation. Neither is a mutation of an existing session's durable + state, and neither is in the in-flight admission set a takeover waits on. + The eight epoch-carrying methods are what the rule covers. + **That call carries an explicit bound and does not inherit `GenServer.call/2`'s hidden default**, which is the same discipline the rest of this plan applies to every call that matters. The relay's whole job here @@ -3417,7 +3429,7 @@ carried: it described three outcomes and returned none of them. | `:active` whose coordinator is already dead | Its `DOWN` handler releases the dispatcher fence and **leaves the entry** (`control.ex:805-826`), which is right for residency and misleading for a drain | `absent` | **Yes** — an old transaction from that dead coordinator is precisely the case the fence exists for | | `:unavailable` | The status `Control` writes when an acquisition it was waiting on failed or its coordinator went down mid-acquisition (`control.ex:620`, `:818`, `:862`, `:1150`) | `absent` | **Yes, always.** An earlier revision let this be the `:not_needed` case on the reading that such an entry never had a coordinator. It can have had one: `unavailable_owner/3` (`:1149-1158`) writes `%{status: :unavailable, durable: nil}` with **no coordinator key**, and one of its callers reaches it at `:1134` *after* terminating a coordinator that had already been started (`:1132`). The absent key proves nothing about the past, so every `:unavailable` entry is fenced | | `:acquiring` | The status while an owner is being started (`control.ex:569`, `:1030`, `:1189`) | `unsettled` | **Yes** | - | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when the bounded wait proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes, and the fence is what makes it safe.** Its coordinator is already gone, so termination has nothing to reach; what could still write is **the dead coordinator's at-most-one already-delivered transaction** — the same case every other fenced row rests on — and nothing else, because no owner group or worker can commit: `Store.transact` has one caller in core (`store/owner_lane.ex:121`), and `OwnerLane.transact` is called only from the coordinator (`session_coordinator.ex:1242`, `:1363`, `:1761-1762`) and `Control` (`control.ex:1680-1681`). The owner group that outlived the coordinator unwinds on its own clock past the runtime kill, which ends the root only, but it writes nothing. The fence's moved epoch is what refuses that one transaction `:stale_owner_epoch`. An earlier revision credited the kill, and the one before it named the owner group as a writer | + | `:awaiting_owner_barrier` | A coordinator has died with its **owner group still alive** and a caller still waiting (`control.ex:835`, `:1040`, `:1046-1053`, consumed at `:833-857`) — reachable exactly when the bounded wait proceeds with a resume in flight | `unsettled`; no abort is admitted, there being no ready coordinator to admit one | **Yes, and the fence is what makes it safe.** Its coordinator is already gone, so termination has nothing to reach; what could still write is **the dead coordinator's at-most-one already-delivered transaction** — the same case every other fenced row rests on — and nothing else, because no owner group or worker can commit: `Store.transact` has one caller in core today (`store/owner_lane.ex:121`), and `OwnerLane.transact` is called only from the coordinator (`session_coordinator.ex:1242`, `:1363`, `:1761-1762`) and `Control` (`control.ex:1680-1681`). Core change 4 adds the second caller — the drain's own fence tasks, calling `Store.transact` directly on the handle the enumeration hands them — and it is named here rather than left to contradict this count, because it weakens nothing: the fence is the writer this row protects the session *with*, it runs after the coordinator is gone, and it is the only thing core change 4 lets reach the Store outside a lane. The owner group that outlived the coordinator unwinds on its own clock past the runtime kill, which ends the root only, but it writes nothing. The fence's moved epoch is what refuses that one transaction `:stale_owner_epoch`. An earlier revision credited the kill, and the one before it named the owner group as a writer | | No entry | The session is dormant in this daemon, or belongs to no daemon at all | In no list; quiesce enumerates `Control` and nothing else | No — the **only** `:not_needed` case, and it is read from the fresh enumeration termination takes, never from the admission's snapshot | | **An admission that did not answer** inside its bound, its task shut down | The session's abort is neither known-committed nor known-refused **to the drain** — see below for what the coordinator does | `unsettled`, with no cleanup released | **Yes** | | **A fence that did not answer** inside its bound, its task shut down **after** the head was read | The fence's outcome cannot be read | `unsettled`, `{:unknown, head}` | The attempt was made; the domain stays fenced | From e2294dc818302949083c4c4dd4fdf2382544d844 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:49:25 -0700 Subject: [PATCH 172/585] plan(M5): three counts that stopped being true `quiesce/1` had three parts in the mechanics and four in the Concept and the evidence row, which is the stale-count class this set has been caught by before. Three is right: the termination and the fence are one part in two steps, in a fixed order, and the Concept and the row say so now. ADR 0032 still said M5 makes five core changes, in the very section that adds the sixth -- the bounded session listing -- and rejected two alternatives as "a further core change beyond the five". Six, and the rejection now says why the listing is one of them and a notification would be a seventh. The Concept's workstream 1 said "Core's five changes" and then listed four, leaving the create and resume fields and the listing out of the workstream that lands them. --- ...mon-attachment-residency-and-replay-technical.md | 7 ++++--- docs/plans/M5-technical.md | 2 +- docs/plans/M5.md | 13 +++++++++---- 3 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 90be5ba7e..016650ebc 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -923,12 +923,13 @@ counts activations per daemon lifetime, for the same reason — it counts what the daemon did. Two alternatives were rejected, and both would be **a further core change** -beyond the five this milestone makes. A lifecycle notification from core to the daemon +beyond the six this milestone makes. A lifecycle notification from core to the daemon would be a new core-to-host signal, with its own delivery and ordering questions, added for a listing field. A monitorable coordinator handle handed out to the daemon would export core's supervision topology across the boundary -and invite the daemon to reason about it. M5's core changes stay at five, and -neither of these is among them. +and invite the daemon to reason about it. M5's core changes stay at six, and +neither of these is among them — the bounded listing this section adds is one +of the six, and a notification or a handle would be a seventh. ADR 0033's lease-owner rule is untouched by this and stays — and it is a **session-scoped** rule, not a fatal one; this sentence said "fatal" from the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index f03eabaea..b9eb51fc3 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -143,7 +143,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its four parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its three parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in arrival order, one at a time**, the second held in its lease owner until the first ticket resolves, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; and the ordering inside the ticket callback asserted on the surface that shows it: at the instant the acknowledgement arrives at the caller, the relay's own state is read in-VM and asserted to hold **both** the ticket row **and** a live task pid for that ticket, and the task is asserted to be monitored rather than linked, so a relay that died next would leave the call running rather than take it down. A relay that replied before spawning passes the first assertion and fails the second, which is the difference the case exists to make. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index aa86d3de7..3f4ad218a 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -409,7 +409,8 @@ did not settle; stop the remaining edges; and stop the Store last, which is when its `terminate/2` releases the marker. **The drain has a mechanism, and it is core's.** M5 adds `quiesce/1` to -`Loopex.Runtime`, and it has four parts, in this order. +`Loopex.Runtime`, and it has three parts, in this order, the last of them two +steps in a fixed order. **The abort admission** durably admits the existing abort command for every active session and stops there, because ADR 0023 fixes that only a durable `session.abort` cancels and nothing may infer @@ -843,15 +844,19 @@ sixth runs last because it describes what the others built. Workstream 1 lands in two parts — the core change first, its daemon-side residency after the lease — and the companion's rejoin order says where each part goes. -1. **Core's five changes, and the residency above them.** The narrow core +1. **Core's six changes, and the residency above them.** The narrow core change that lets distinct attachments to one session coexist without implicit replacement; the read-only session-existence query the daemon's acquire and activation paths need; `Loopex.Trace.exclude_self/2`, the two-part trace exclusion that accepted ADR 0030 already requires, which lands with workstream 5's credential work because that is what it - protects; and the bounded + protects; the bounded `quiesce/1` the orderly stop drains through, which lands before workstream - 2's shutdown sequence because that sequence cannot be proved without it. + 2's shutdown sequence because that sequence cannot be proved without it; + the `disposition` and `control_entry` fields on the detailed create and + resume functions, which are what let the daemon tell a fresh activation + from a replayed one; and the bounded session listing the daemon pages + through. The first two land first, because nothing about the daemon can be proved without them — and then, once the lease exists, the daemon-side residency over it: the resident window as a From 598d5ce9cb7c85ad08654ed77af538c7d520aa01 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 17:50:14 -0700 Subject: [PATCH 173/585] docs(M5): keep the closure link its own paragraph --- docs/developer/milestones.md | 1 + 1 file changed, 1 insertion(+) diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index 6dceb9ab2..44cb95a7e 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -80,6 +80,7 @@ SHA** — the exact bytes published — rather than on the implementation commit alone. And run evidence is **immutable**: retained where it cannot be edited after the fact, attached to the tag or held outside the repository, so that what a reviewer read and what a reader later finds are the same thing. + Technical depth: [The closure packet](milestones-technical.md#technical-milestones-close). From 49485a5c164f898add2dc23f0c2781b7b31e3a07 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:14:23 -0700 Subject: [PATCH 174/585] plan(M5): one cut semantics, caller-is-holder, eleven links Three fixes of the same class: a rule changed in one paragraph while its neighbours went on stating the old one. The bounded wait replaced "the relay answers only when every ticket it holds has settled" two rounds ago, and the mechanics retired it twice -- but Outcome 1 in the Concept still promised it and ADR 0032 still said an admitted command "has settled by the time it returns", while the witness asserts the opposite. The cut is an admission instant and nothing more, in all three places, and the ADR now says so where a reader meets it. The internal attach form taking a stable holder pid was proposed in one bullet while four passages and ADR 0032 kept caller-is-holder, and no inventory or witness carried it. It is withdrawn: the connection process writes the attach ticket and makes the attach, the dispatcher monitors it, and the relay holds the ticket without owning the call. The connection registry was introduced as a fixed linked daemon-fatal process and then left out of five inventories -- the fixed process table, the Concept's fixed set, the numbered start order, the startup steps, the stop order and the fail-stop class list -- while sitting in the dynamic table under the heading "one fixed process". It is the eleventh link in all of them: twelve rows, eleven links, eleven where transfers are enabled and ten where they are not, started tenth because a slot is reserved at accept, stopped first in step 4 because step 3 writes through the interface it owns. Its class joins the twelve that reach the fail-stop path, and leaves the wire vectors for the same reason `listener_lost` did: the record would have to go out through the thing that is gone. Vectors are eight with transfers and seven without. --- ...tachment-residency-and-replay-technical.md | 14 ++- docs/plans/M5-technical.md | 95 ++++++++++++------- docs/plans/M5.md | 10 +- 3 files changed, 77 insertions(+), 42 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 016650ebc..6efce0580 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -600,7 +600,7 @@ carry. | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost`, `fatal:connections_lost` — nine in a daemon with artifact transfers and eight without. **`fatal:listener_lost` is not among them**: the listener is what would have written the record, so no client can be told that reason, which the plan's own class table says and this set contradicted. A lease owner's death is not among them: it closes one session's controller connection with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost` — eight in a daemon with artifact transfers and seven without. **`fatal:listener_lost` and `fatal:connections_lost` are not among them**: the listener is what would have written the record, and the connection registry owns the buffer-control interface it would have been written *through*, so no client can be told either reason. The plan's own class table says both, this set contradicted the first, and a later revision added `fatal:connections_lost` here without noticing it had the same defect. A lease owner's death is not among them: it closes one session's controller connection with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | | `message` | A bounded non-secret sentence for an operator to read | | `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | @@ -805,9 +805,15 @@ closes nothing on its own. The connection is closed a moment later by step 3 of the stop sequence, which is where a client is told the reason it is going away; `daemon_stopping` answers the one request that arrived in between. -The instant it names is the relay's acknowledgement, not the signal: a command -whose relay ticket was recorded **before** the acknowledgement has settled by -the time it returns, and one that arrives after it is refused. Those are +The instant it names is the relay's acknowledgement, not the signal, and it +is an **admission instant and nothing more**. A command whose relay ticket was +recorded **before** the acknowledgement was admitted and is carried; one that +arrives after it is refused. The acknowledgement says nothing about whether an +admitted command has *finished*: the daemon waits for that separately, for a +bounded time, and its stop proceeds at that bound with anything still running +classified and fenced. An earlier revision of this passage said an admitted +command "has settled by the time it returns", which was the design the bounded +wait replaced and which a resume paging a long history defeats. Those are the two witnesses, and they must give different answers on the same surface — the connection's own reply stream. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index b9eb51fc3..5b1201933 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -144,7 +144,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its three parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — **not `listener_lost`**, which has no vector because the listener is what would have written it, so no client ever receives that reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — eight where artifact transfers are enabled and seven where they are not, and **neither `listener_lost` nor `connections_lost`**, which have no vector for the same reason: the listener is what would have written the record and the connection registry owns the buffer-control interface it would have been written through, so no client ever receives either reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in arrival order, one at a time**, the second held in its lease owner until the first ticket resolves, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; and the ordering inside the ticket callback asserted on the surface that shows it: at the instant the acknowledgement arrives at the caller, the relay's own state is read in-VM and asserted to hold **both** the ticket row **and** a live task pid for that ticket, and the task is asserted to be monitored rather than linked, so a relay that died next would leave the call running rather than take it down. A relay that replied before spawning passes the first assertion and fails the second, which is the difference the case exists to make. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | | 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | @@ -1441,7 +1441,7 @@ runtime — rather than against a staged one the plan would have to invent: the daemon's own, as ADR 0034's host, and all three must exist before the model configuration that carries the registry handle, the token and the capability reference is built. The capability is listed here rather than - left to the process table: it is one of the ten links, ADR 0034 now makes + left to the process table: it is one of the eleven links, ADR 0034 now makes it mandatory wherever a token is configured, and a startup sequence that named two of the three would have left the third's position to inference. It is handed the runtime reference as soon as step 4 returns one. @@ -1453,12 +1453,18 @@ runtime — rather than against a staged one the plan would have to invent: never reads, unlinks or binds the socket path. 5. **Read the session directory and build the index**, refusing at the recorded-entry bound. -6. **Start the admission relay.** It is the ninth of the ten linked - processes and the last before the listener: it needs the runtime step 4 - returned, and it must exist before any connection can be accepted, because - every call that changes core state goes through it. An earlier - revision gave it a row in the process table and no step here, which left - the one process the admission cut depends on with no place in the order. +6. **Start the admission relay, then the connection registry.** They are the + ninth and tenth of the eleven linked processes and the last two before the + listener. The relay needs the runtime step 4 returned, and it must exist + before any connection can be accepted, because every call that changes core + state goes through it. The connection registry must exist before the + listener accepts, because the slot it reserves is reserved **at** `accept` + and the monitor it takes is taken there too — a listener accepting before + it exists would accept connections nothing owns. An earlier + revision gave the relay a row in the process table and no step here, and + the revision after it added the connection registry with neither, which + left the two processes the admission cut and the connection ceiling depend + on with no place in the order. 7. **Create the `0700` subdirectory, remove any stale socket pathname, and bind the `0600` socket**, then read back and verify ownership and mode. Removing the stale pathname is this daemon's right and only this daemon's: @@ -1642,7 +1648,8 @@ exist. The fixed set is this: | 7 | The local executor | `start_edge(Local, …)` | no | | 8 | The runtime root | `start_edge(Loopex, …)` | no | | 9 | The **admission relay** | The daemon's own; every one of the ten core calls that change core state is routed through it | no | -| 10 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | +| 10 | The **connection registry** | The daemon's own; it owns every connection's slot, monitor and output buffer, and the slot is reserved at `accept`, so it must exist before anything accepts | no | +| 11 | The listener | Bound and permission-checked last, so nothing accepts before the rest exists | no | The tracing capability starts with the other two host-owned processes and before composition, for the reason all three share: model options carry their @@ -1740,15 +1747,20 @@ as though it does: outside the relay entirely, which made the cut a promise the daemon could not keep. - **The tenth is `session.attach`, and it is ticketed for the cut alone — but -it is not performed by a relay task.** The dispatcher monitors **its caller** -(`event_dispatcher.ex:186-192`), so an attach made from a short-lived relay -task would be released the instant that task exited, which is immediately. So -core change 1 adds an internal attach form taking a **stable holder pid** the -dispatcher monitors instead of the caller, the daemon passes its -**connection process**, and the relay's ticket accounts for the call without -owning it. The witness asserts the monitored pid **is** the connection -process, and that the attachment survives the task that started it. + **The tenth is `session.attach`, and it is ticketed for the cut alone — the +ticket is written by the connection process and the call is made from that +same process, never from a relay task.** The dispatcher monitors **its +caller** (`event_dispatcher.ex:186-192`), so an attach made from a short-lived +relay task would be released the instant that task exited, which is +immediately. Caller-is-holder is therefore kept exactly as the attachment +rules above state it: the connection process calls, the dispatcher monitors +it, and its `DOWN` is the release. What the relay holds for an attach is the +**ticket alone**, so the cut can account for a call in flight; it neither +performs the call nor owns its lifetime. An earlier revision proposed an +internal attach form taking a stable holder pid instead of the caller, which +would have added a core surface no inventory carried and contradicted every +caller-is-holder passage in this pair; it is withdrawn, and nothing needs it +once the connection process is the caller. An earlier revision called it a read and left it out, which it is not: its @@ -1951,7 +1963,8 @@ first, then the artifact placement and the executor's own edges, and the runtime last within that chain, because it depends on all of them. **The stop order is the reverse, with one deliberate exception.** Reversed: -listener, then **every lease owner**, then the **relay**, then runtime, +listener, then the **connection registry**, then **every lease owner**, then +the **relay**, then runtime, executor, workspace lease, transfers, then the tracing capability, custody and the registry — and then **the Store, last of all**, out of reverse order. The lease owners go before the @@ -2727,8 +2740,13 @@ the owner fixes. client may learn of a shutdown only by its socket closing. **Nothing unlinks the pathname**, on this path or any other: the next daemon to prove it holds the marker removes it before binding, which is the only safe moment there is. -4. **Every lease owner stops as one sweep, then the admission relay**, inside - the teardown deadline. Every lease vanishes with the +4. **The connection registry stops, then every lease owner as one sweep, then + the admission relay**, inside + the teardown deadline. The registry goes first of the three and **not + before step 3**: step 3's stop records and closes go through the + buffer-control interface it owns, so stopping it earlier would leave the + daemon unable to write the record it promises. By the time it stops, every + connection it monitored is already gone. Every lease vanishes with the owners; the relay goes after them because it is what holds their admission tickets, and stopping it first would discard a ticket a lease owner could still be waiting on. Nothing durable is involved, and no client is left @@ -3710,13 +3728,16 @@ information lost on the way. **The steps below are the fail-stop path for every fatal class, not only the two store ones.** Store loss is the instance worth reading first because it is the one where the thing the daemon would otherwise stop is already gone; the -other **nine** differ only in which component is missing by the time the owner -runs them. **Eleven classes reach this path**, one per linked component of the +other **ten** differ only in which component is missing by the time the owner +runs them. **Twelve classes reach this path**, one per linked component of the fixed set: the two store classes, and `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, -`capability_lost`, `runtime_lost`, `relay_lost` and `listener_lost` — ten in a -daemon without artifact transfers. Earlier revisions said six and eight here, -which was the count from a design with fewer linked processes. In every one of +`capability_lost`, `runtime_lost`, `relay_lost`, `connections_lost` and +`listener_lost` — eleven in a +daemon without artifact transfers. Earlier revisions said six, then eight, +then eleven here, each being the count from a design with fewer linked +processes; the last of them had already added the connection registry without +adding its class to this list. In every one of them the owner has a class in hand, runs no ordered sequence, and does not return to serving. A step whose component is already gone is a no-op, by the rule the `stopping` field states above: under @@ -4191,11 +4212,14 @@ children, a pid's liveness, a socket's EOF, or the daemon's own `stderr`. that component's class, to send that component's `fatal:` on the wire where a socket still exists, and — for the classes where the Store is still alive — **to leave no stale marker**, proved by the next daemon - opening that root with nothing to recover; nine of them in a daemon with - transfers enabled and eight without — `runtime_lost`, `transfers_lost`, + opening that root with nothing to recover; ten of them in a daemon with + transfers enabled and nine without — `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, - `capability_lost`, `relay_lost`, `listener_lost`, beside the two store - classes. The set is closed for the + `capability_lost`, `relay_lost`, `connections_lost`, `listener_lost`, + beside the two store + classes — with the two that reach **no** client asserted to send nothing and + still exit with their class, since the listener and the connection registry + are what a record would have gone out through. The set is closed for the fixed set, so one of those dying without a class is a failing case rather than a silent `:shutdown`. A lease owner is deliberately not in this case: its own witness is below, and it asserts the daemon **keeps running**. @@ -4511,8 +4535,11 @@ individually would make this table a copy that rots. **The daemon's fixed processes — eleven rows, ten without transfers: the owner and the ten it links.** The count is stated that way because the table has one more row than the link set does, the owner being the process that holds the -links rather than one of them, and an earlier revision headed eleven rows -"ten". +links rather than one of them. Earlier revisions headed eleven rows "ten", and +then left the **connection registry** — a fixed, linked, daemon-fatal process +— in the dynamic table below under the heading "one fixed process", where a +reader looking for the linked set could not find it. Twelve rows, eleven +links. | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | @@ -4526,14 +4553,14 @@ links rather than one of them, and an earlier revision headed eleven rows | **Local executor** | The composition function | Daemon owner | Orderly step 6, before the lease | `executor_lost` | | **Runtime root** (a supervisor; its children are core's, below) | The composition function | Daemon owner | Orderly step 5 | `runtime_lost` | | **Admission relay** | Daemon owner, after the runtime | Daemon owner | Orderly step 4, after the lease owners whose tickets it holds | `relay_lost`, daemon-fatal | -| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Step 1 stops it accepting; step 3 closes it, leaving the pathname | `listener_lost`, and the one fatal class no client can be told | +| **Connection registry** | Daemon owner, tenth, beside the relay and before the listener | Daemon owner | Orderly step 4, first — after step 3's records and closes, which go through the buffer-control interface it owns | `connections_lost`, daemon-fatal: it owns every connection's monitor and the buffer-control interface, so a daemon without it can neither release a slot nor stop writing to a gone peer. **No client can be told this class**, for the same reason as the listener's: the write goes through the interface that is gone | +| **Listener** | Daemon owner, last of the fixed set | Daemon owner | Step 1 stops it accepting; step 3 closes it, leaving the pathname | `listener_lost`, one of the two fatal classes no client can be told | **The daemon's dynamic processes, each with its bound:** | Group | Started by | Bound | Its death | | --- | --- | --- | --- | | **Lease owners**, one per session under lease or acquisition | Daemon owner, on the first lease operation after existence validation | At most 512 at once, ADR 0032's per-daemon ceiling reused | **Session-scoped**: that session's controller closes with `control_owner_lost`, observers stay, the replacement's first grant waits on the relay's tickets | -| **Connection registry**, one fixed process | Daemon owner, beside the relay | one | `connections_lost`, daemon-fatal: it owns every connection's monitor and the buffer-control interface, so a daemon without it can neither release a slot nor stop writing to a gone peer | | **Connections**, one per accepted client | The listener, their slots reserved at `accept` and their monitors held by the connection registry | **512 concurrent**, ADR 0032's connection ceiling — the attachment number reused, and not the attachment ceiling itself, which bounds nothing about a client that never attaches | That client's connection closes | | **Stop helpers**, one per stop | Daemon owner, `spawn_monitor` | One at a time, except the teardown's lease-owner sweep, which spawns one per lease owner at once and so is bounded by the 512 above | Nothing: monitored, never linked | | **Relay tasks**, one per ticketed call — the eight lease-authorized mutations, `session.create` and `session.attach`; **not** the three artifact-transfer methods, which mutate neither `Control` nor the journal | The relay, after the ticket is acknowledged | One per outstanding ticket | Keeps its ticket; the relay exits `relay_lost` | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 3f4ad218a..f25f00784 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -87,7 +87,7 @@ second loop and no new durable command. | # | Outcome | Evidence class | Witness | | --- | --- | --- | --- | -| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — the relay answering only when every ticket it holds has **settled**, so a command admitted before the cut has finished inside core before the drain begins and one arriving after it is refused `daemon_stopping` — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline **terminates every coordinator it enumerated — the settled as well as the unsettled — waiting for every one of them to be gone, and only then fences every one of those sessions**, in that order, so no fence races a live writer — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | +| 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — the relay closing admissions and **answering at once**, the tickets already inside core then awaited for a bound the implementation measures, after which **the stop proceeds** — so a request of any kind arriving after the cut is refused `daemon_stopping` with nothing admitted, and a ticket still running at the bound leaves its session classified and fenced rather than waited on — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline **terminates every coordinator it enumerated — the settled as well as the unsettled — waiting for every one of them to be gone, and only then fences every one of those sessions**, in that order, so no fence races a live writer — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | | 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | @@ -646,13 +646,15 @@ supervisor.** Its top-level component is one `GenServer` that traps exits and `start_link`s a **fixed set** of them: the five the composition function assembles in its caller's process — the Store adapter, the runtime root, the artifact transfers owner where enabled, the workspace lease and the local -executor — plus five of the daemon's own: the credential routing registry, the +executor — plus six of the daemon's own: the credential routing registry, the custody process and the tracing capability ADR 0034 gives the host, the **admission relay** that holds a ticket for every one of the ten calls the daemon makes that change core state — the eight lease-authorized mutations, `session.create` and `session.attach` — and whose acknowledged cut is what an -orderly stop closes admissions with, -and the listener. Ten where transfers are enabled, nine where they are not. **Beside them it links one +orderly stop closes admissions with, the **connection registry** that owns +every connection's slot, monitor and output buffer, +and the listener. Eleven where transfers are enabled, ten where they are +not. **Beside them it links one lease owner per session under lease or acquisition**, started at the first lease operation rather than at activation, retired when the lease is free and nothing is outstanding, and capped at the 512 ADR 0032 already fixes. That one From 7e447cb18cbea06335cf0c22372a68f56e71a2d1 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:15:37 -0700 Subject: [PATCH 175/585] adr(M5): the slot is at accept, so nothing is refused at initialize The connection ceiling moved to `accept` in one paragraph and the paragraph after it kept answering `capacity_exceeded` at `initialize`, with a witness asserting the 513th connection initializes and is refused -- which a slot taken at accept makes unreachable, since that socket never reads a frame. The initialize-time refusal and its witness are deleted. The new witness matches the rule: the 512th is served, the 513th is accepted and closed with no frame read and no record written, and closing one of the 512 lets the next through. What that costs is stated rather than glossed: a peer beyond the ceiling is closed without being told why and cannot tell a full daemon from a wedged one. `daemon.status` is where the headroom is visible instead. `capacity_exceeded` stays in generation 2 because another path produces it, and that path is now named rather than assumed: the two attachment ceilings, whose "stable reason when exhausted" had never been given a code. The limits row stops describing a refusal that cannot happen. Beside them, the connection-to-session pin named "the existing invalid-argument reason" without saying which; it is `invalid_request`, answered before any gate, since neither `control_not_held` nor `not_attached` would be true. --- ...tachment-residency-and-replay-technical.md | 52 ++++++++++++------- docs/plans/M5-technical.md | 2 +- 2 files changed, 33 insertions(+), 21 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 6efce0580..d4ae39e36 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -507,7 +507,11 @@ beside them, and **all five** digest inputs therefore change in generation 2. **A connection is pinned to one session, and both paths pin it.** The first `session.attach` or `session.acquire_control` a connection completes fixes which session that connection is about; every later call on it naming a -different session is refused with the existing invalid-argument reason, and +different session is refused with ADR 0023's existing **`invalid_request`** +(`0023-…-technical.md:304-307`) — the request is well-formed bytes but names a +session this connection is not about, which is an argument fault rather than a +lease or attachment one, so it is answered before any gate and never with +`control_not_held` or `not_attached`, neither of which would be true — and the daemon's per-connection state is keyed by that one session rather than by whatever the last frame said. Without the rule a connection could hold a lease on one session and an attachment on another, and `control_owner_lost` — whose @@ -541,22 +545,28 @@ and closes the socket immediately when none is free — before any frame is read, before the peer check, with no record, because a connection that was never admitted has no generation to be told anything in. The slot is released when the connection process ends, which is the same `DOWN` everything else -about a connection hangs from. The `initialize`-time refusal below still -exists for the case a slot was free at accept and the handshake is what fails. - -**The refusal is ADR 0023's, not a new one.** A connection accepted beyond the -ceiling is answered, at its `initialize`, with a correlated -**`capacity_exceeded`** — which generation 1 already carries, so generation -2's ordered error list gains nothing for it — and then closed. It is answered -at `initialize` rather than refused at `accept` because a peer that is never -answered cannot tell a full daemon from a wedged one, and because ADR 0023 -already fixes what a refused `initialize` means: the connection remains -uninitialized and gets no second negotiation attempt -(`0023-…-technical.md:357-358`). The peer-credential and filesystem checks -still run first; a foreign peer is closed before any of this. Its witness is a -boundary pair: the 512th connection initializes and is served, the 513th is -refused `capacity_exceeded` and closed, and closing one of the 512 lets the -next through. +about a connection hangs from. + +**There is no `initialize`-time refusal for the connection ceiling, and an +earlier revision of this section kept one beside the accept-time slot.** The +two cannot both hold: a slot taken at `accept` means the 513th socket never +reaches `initialize` to be answered anything, and a ceiling answered at +`initialize` is the ceiling on nothing that the paragraph above rejects. The +accept-time slot is the rule. What is lost with the refusal is stated rather +than glossed: a peer beyond the ceiling is closed **without being told why**, +and cannot tell a full daemon from one that is wedged or gone. That is the +price of bounding sockets rather than handshakes, and `daemon.status` is where +an operator sees the headroom instead. The peer-credential and filesystem +checks are unaffected, running on connections that did get a slot; a foreign +peer is closed before any of this. + +Its witness is the boundary pair that matches the rule: the **512th** +connection is accepted, initializes and is served; the **513th socket is +accepted and closed with no frame read and no record written**, asserted from +the client side as an immediate EOF rather than as an error record; and +closing one of the 512 lets the next one through. A witness asserting a +`capacity_exceeded` at `initialize` would be asserting a path this decision +does not have. **An accepted connection that never initializes is closed on a deadline**, and without one the ceiling would be a ceiling on nothing: a peer that connects @@ -630,7 +640,7 @@ limits — five inputs, and generation 2 changes **all five**: | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` and `daemon.notice` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 reuses for the connection ceiling | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 keeps for the two **attachment** ceilings — `attachments_per_session` and `attachments_per_daemon`, the "stable reason when exhausted" the attachment-lifecycle list names — and no longer for the connection ceiling, which is enforced at `accept` and therefore reaches no `initialize` | | **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `connections_per_daemon`, `initialize_deadline_ms`, `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 @@ -1306,8 +1316,10 @@ delivered contiguously after the snapshot. The daemon adds: buffers and resident windows; on aggregate pressure, evict or detach the slowest eligible attachment before admitting more bytes, without stalling a journal transaction, and by the same record-then-close; -- 64 attachments per session and 512 per daemon, refused at attach with a - stable reason when exhausted; +- 64 attachments per session and 512 per daemon, refused at attach with + **`capacity_exceeded`** when exhausted — ADR 0023's existing code, and after + the connection ceiling moved to `accept` the only thing in generation 2 that + produces it; - eviction of an **observer** attachment that has consumed nothing for ten minutes; the `detached` record names the cursor the client may resume from and the diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 5b1201933..34c345322 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -4736,7 +4736,7 @@ line; M5 introduces none of its own. | Log capacity per state root | 256 MiB; an append past it refused as `store_capacity_exceeded`, which terminates the store and closes the daemon, a log already past it refused at open as `store_log_too_large` | ADR 0031 | | Frame ceiling on any single store record | 4 MiB | ADR 0031 | | Retention and replay | Full history, no compaction, full replay at open | ADR 0031 | -| Concurrent connections per daemon | 512, the attachment number reused; the 513th is refused `capacity_exceeded` at `initialize` and closed | ADR 0032 | +| Concurrent connections per daemon | 512, the attachment number reused; the slot is taken at `accept`, so the 513th socket is accepted and **closed with no frame read and no record written** — an EOF, not a refusal, because a connection that was never admitted has no generation to be told anything in | ADR 0032 | | Time an accepted connection may take to complete `initialize` | 30 s, advertised under its own limits key `initialize_deadline_ms`, after which the connection is closed with no record; without it the connection ceiling would bound nothing | ADR 0032, its value derived from ADR 0033's lease term rather than chosen, and carried as a separate key so neither contract moves the other | | Attachments per session | 64 | ADR 0032 | | Attachments per daemon | 512 | ADR 0032, its attachment-lifecycle list, with the limit key in its limits table | From 837dec822e13358ece1736554382fcd9b42c776a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:19:11 -0700 Subject: [PATCH 176/585] docs(M5): the tag re-proof belongs to Release, not to Close The two-SHA rule landed under Close and took the tagged-SHA re-proof with it, which made closure depend on a tag that closure authorizes -- the circularity the rule exists to remove, reinstated one paragraph lower. Close now states only the two SHAs and their relation and says the matrix runs once, from the tested implementation SHA. Release owns the rest, and on the maintainer's decision the tag names the ADMINISTRATIVE closure SHA, because that is the tree a reader who fetches the tag actually gets. That is safe only if the commit is confined, so the release verifies it rather than trusting it: `git diff --stat ..` touching nothing outside `docs/`. On that basis two documentation-scoped checks are sufficient -- `check.sh --docs` on the tagged SHA, and the archive manifest recomputed from the tagged SHA against the one the tested SHA recorded. No suite, no release check and no provider credential run twice. Two claims of the earlier wording are withdrawn rather than carried: the docs gate does not read all of `docs/` (its scope is docs/operator + docs/developer, as the verification guide fixes), and run evidence produced before the tag cannot be attached to it -- all of the closure matrix is in that class, so it is held outside the repository with its digests recorded. AGENTS.md steps 3 and 4 and the verification guide's stage table carry the same words, since a rule stated in one of the three and not the others is the defect this round keeps finding. The maintainer authorized the guide change; extending it to those two files is flagged in the report. The register capsule stopped saying "from the candidate" and the closure row capsule now names both SHAs, with the test that pins those strings updated in the same change. The override is recorded twice, as the contract requires: one entry in M5's progress section covering both of this round's rule changes, and one disposition in the context map naming what changed in what a check proves. --- AGENTS.md | 13 ++++++- apps/loopex/lib/mix/tasks/status/register.ex | 7 ++-- apps/loopex/test/status_check_test.exs | 8 ++-- docs/developer/agent-context-map.md | 31 ++++++++++++++++ docs/developer/milestones-technical.md | 37 ++++++++++++------- docs/developer/milestones.md | 35 +++++++++++++++--- docs/developer/verification.md | 4 +- docs/plans/M5-technical.md | 16 ++++++-- docs/plans/M5.md | 39 +++++++++++++++----- 9 files changed, 147 insertions(+), 43 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index d77d4e984..c30f71b5f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -169,9 +169,18 @@ A milestone runs in four steps; the `bash scripts/check-release.sh` once, counting the current-pair CI run the candidate already produced rather than repeating it. An independent reviewer reads the candidate; the maintainer closes it and the register moves to - `Closed`. + `Closed`. Closure names **two commits**: the *tested implementation SHA* + the matrix ran on and the reviewer read, and the *administrative closure + SHA* that records the decision and changes nothing the runs covered. One + commit cannot name itself. Run evidence is immutable — held where it cannot + be edited after the packet is read. 4. **Release.** Publication, tags, and packages are separate maintainer - decisions that reuse the closure evidence when the source is unchanged. + decisions that reuse the closure evidence when the source is unchanged. The + tag names the **administrative** closure SHA, whose diff from the tested + SHA is verified to touch nothing outside `docs/`; on that basis the release + re-proves documentation only — `bash scripts/check.sh --docs` on the tagged + SHA and a recomputed archive manifest — and re-runs no suite and no release + check. Historical milestones keep their plans, evidence logs, and dispositions as records of what was proved at the revisions they name. Current tests belong to diff --git a/apps/loopex/lib/mix/tasks/status/register.ex b/apps/loopex/lib/mix/tasks/status/register.ex index 3ad388ae3..04e8cc581 100644 --- a/apps/loopex/lib/mix/tasks/status/register.ex +++ b/apps/loopex/lib/mix/tasks/status/register.ex @@ -775,8 +775,8 @@ defmodule Loopex.Checks.Register do |> Map.put( "Next transition", "Map every outcome to evidence, run `bash scripts/check.sh` under the floor toolchain " <> - "pair and `bash scripts/check-release.sh` once from the candidate, then move " <> - "`#{name}` to In review" + "pair and `bash scripts/check-release.sh` once from the tested implementation SHA, " <> + "then move `#{name}` to In review" ) end @@ -793,7 +793,8 @@ defmodule Loopex.Checks.Register do ) |> Map.put( "Next transition", - "Record the closure governance row and move `#{name}` to Closed" + "Record the closure governance row, naming both the tested implementation SHA and " <> + "the administrative closure SHA, and move `#{name}` to Closed" ) end diff --git a/apps/loopex/test/status_check_test.exs b/apps/loopex/test/status_check_test.exs index ad568c9ed..f40f66991 100644 --- a/apps/loopex/test/status_check_test.exs +++ b/apps/loopex/test/status_check_test.exs @@ -1553,8 +1553,8 @@ defmodule Loopex.StatusCheckTest do | "Blockers" => "None; `#{name}` is in progress against its accepted plan pair", "Next transition" => "Map every outcome to evidence, run `bash scripts/check.sh` under the floor " <> - "toolchain pair and `bash scripts/check-release.sh` once from the candidate, " <> - "then move `#{name}` to In review" + "toolchain pair and `bash scripts/check-release.sh` once from the tested " <> + "implementation SHA, then move `#{name}` to In review" } "In review" -> @@ -1563,7 +1563,9 @@ defmodule Loopex.StatusCheckTest do | "Blockers" => "None; `#{name}` awaits independent review of its closure candidate", "Next maintainer decision" => "Close `#{name}` or reject its closure candidate on the review findings", - "Next transition" => "Record the closure governance row and move `#{name}` to Closed" + "Next transition" => + "Record the closure governance row, naming both the tested implementation " <> + "SHA and the administrative closure SHA, and move `#{name}` to Closed" } "Closed" -> diff --git a/docs/developer/agent-context-map.md b/docs/developer/agent-context-map.md index fcba4c3cc..01da3090a 100644 --- a/docs/developer/agent-context-map.md +++ b/docs/developer/agent-context-map.md @@ -5375,3 +5375,34 @@ above remain records of what was proved at the revisions they name. The source version is `0.1.0` as accepted ADR 0023 decides; the `v0.1.0` tag is a separate maintainer decision on the integrated closure. This record grants no tag, release or publication. + +### Closure names two commits — 2026-09-20 + +The maintainer changed what a closure must show. Closure had asked for its +evidence and its closure record at one SHA, which no sequence of commits can +satisfy: recording the decision is itself a commit, and it comes after the +runs. Closure now names a **tested implementation SHA** — the candidate the +matrix ran on and the reviewer read — and an **administrative closure SHA** +that records the decision and changes nothing the runs covered. The matrix +runs once, from the first. + +The **tag names the administrative SHA**, because that is the tree a reader +who fetches the tag gets. The release verifies that commit is confined — +`git diff --stat ..` touching nothing outside +`docs/` — and on that basis re-proves documentation only: `check.sh --docs` on +the tagged SHA and a recomputed archive manifest against the one the tested +SHA recorded. **No suite and no release check run twice**, and no provider +credential is spent again. Run evidence is immutable, held where it cannot be +edited after the packet is read. + +What changed in what a check proves: the documentation gate and the archive +identity are now proved of the **published** bytes rather than only of the +tested ones, at the cost of two documentation-scoped runs at release. Nothing +else moved, and the documentation gate's scope is unchanged — `docs/operator` +and `docs/developer`. Written into +[the milestone guide](milestones.md#concept-milestones-close) and its +[technical companion](milestones-technical.md#technical-milestones-close), +`AGENTS.md` § Milestones and Checks steps 3 and 4, and +[the verification guide](verification.md#concept-verification-stages)'s stage +table, in one change with this entry. It grants no tag, release or +publication. diff --git a/docs/developer/milestones-technical.md b/docs/developer/milestones-technical.md index ca38629d4..bee8ddc82 100644 --- a/docs/developer/milestones-technical.md +++ b/docs/developer/milestones-technical.md @@ -120,25 +120,36 @@ four places above, so `git show` over it is the check. Anything else in that diff means the evidence no longer covers the tree, and the packet is reassembled from a new implementation SHA. -**The documentation and archive checks run on the tagged SHA.** They are the -two whose subject is the published bytes — the documentation gate reads every -tracked file under `docs/`, and the archive proof builds an extraction of the -exact commit — so running them only on the implementation SHA leaves the -administrative commit's own documentation changes unchecked and the archive -proved for a tree nobody publishes. They run again on the tag, and their -results join the evidence page with the tag named. - -**Run evidence is immutable.** A run's identity, platform, toolchain, result -and duration are retained where they cannot be edited after the packet is -read: attached to the annotated tag, or held outside the repository with its -digest recorded here. An evidence page that can be rewritten after a reviewer -read it is a record of what someone later wished had happened. +**The closure matrix runs once, from the tested implementation SHA**, and the +administrative commit re-runs nothing. What the tag re-proves, and how it is +confined so that two documentation checks are enough, is in +[Tags](#technical-milestones-release) — it belongs to the release decision, +which is what creates a tag at all, and an earlier revision of this section +put it here and made closure depend on a tag that closure authorizes. ### Tags Concept: [Release](milestones.md#concept-milestones-release). +`COMMIT` is the **administrative closure SHA**, not the tested implementation +SHA: it is the commit that carries the closure record, so it is the tree a +reader who fetches the tag gets. Before tagging: + +| Step | Command | What a failure means | +| --- | --- | --- | +| Confine the administrative diff | `git diff --stat ..` | Any path outside `docs/` means the tag would publish source the closure evidence does not cover; the release stops and the packet is reassembled from a new implementation SHA | +| Re-prove the documentation | `bash scripts/check.sh --docs` on the tagged SHA | The administrative commit's own documentation changes are not green; fix and re-tag | +| Re-prove the archive identity | Recompute the archive manifest from the tagged SHA and compare it with the manifest the tested SHA recorded | The published bytes are not the closed bytes outside `docs/`, which the first step should already have caught | + +Nothing else is re-run. There is no second suite, no second release check and +no second provider credential: the tested tree and the tagged tree differ only +in documentation, which is exactly the property the first step establishes and +the reason two documentation-scoped checks suffice. The documentation gate's +scope is unchanged — `docs/operator` and `docs/developer`, as the verification +guide fixes it — and widening it to all of `docs/` was a claim an earlier +revision of the closure section made and nothing implements. + `git tag -a vVERSION COMMIT -m "NAME closure"` and `git push origin vVERSION`, on the maintainer's explicit decision. The source version in `VERSION` changes in an ordinary reviewed commit before closure when the diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index 44cb95a7e..9abcedace 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -74,12 +74,10 @@ implementation SHA**, which the runs and the review name, and the the runs covered. A closure whose administrative commit touches anything else is not administrative, and its evidence is stale. -**Two obligations follow from that split.** The documentation and archive -checks are the ones a later commit can invalidate, so they run **on the tagged -SHA** — the exact bytes published — rather than on the implementation commit -alone. And run evidence is **immutable**: retained where it cannot be edited -after the fact, attached to the tag or held outside the repository, so that -what a reviewer read and what a reader later finds are the same thing. +The closure matrix is run **once**, from the tested implementation SHA, and +nothing in closure is re-run because of the administrative commit. What that +commit can invalidate is a matter for the release, which is where the tag +exists; Close states the two SHAs and their relation and stops there. Technical depth: [The closure packet](milestones-technical.md#technical-milestones-close). @@ -89,6 +87,31 @@ Technical depth: [The closure packet](milestones-technical.md#technical-mileston A release is a separate maintainer decision: a tag on the exact integrated closure commit, reusing the closure evidence when the source is unchanged. A package, installer or publication is its own decision with its own evidence. + +**The tag names the administrative closure SHA**, which is the commit that +carries the closure record and therefore the tree a reader who fetches the tag +gets. That is only safe because the administrative commit is confined: its +diff from the tested implementation SHA must touch **nothing outside +`docs/`**, and the release step verifies that rather than trusting it — +`git diff --stat ..` with every path under `docs/`. +A diff that reaches anything else means the tag would publish source the +closure evidence does not cover, and the release stops. + +**Two checks run at the tag, and neither is a second closure.** The tagged +tree differs from the tested one only in documentation, so what is re-proved +is documentation: `bash scripts/check.sh --docs` runs on the tagged SHA, and +the archive manifest is recomputed from the tagged SHA and compared with the +one the tested SHA recorded. No suite is re-run, no release check is re-run, +and no provider credential is spent again. Their results join the evidence +page with the tag named. + +**Run evidence is immutable.** A run's identity, platform, toolchain, result +and duration are retained where they cannot be edited after the packet is +read: attached to the annotated tag once it exists, or — for everything +produced before the tag, which is all of the closure matrix — held outside the +repository with its digest recorded on the evidence page. An evidence page +that can be rewritten after a reviewer read it is a record of what someone +later wished had happened. Technical depth: [Tags](milestones-technical.md#technical-milestones-release). ### The skills diff --git a/docs/developer/verification.md b/docs/developer/verification.md index d06be0bb5..e92e8460f 100644 --- a/docs/developer/verification.md +++ b/docs/developer/verification.md @@ -32,8 +32,8 @@ Technical depth: [What each stage runs](verification-technical.md#technical-veri | Stage | Question | What runs | Who or what can stop it | | --- | --- | --- | --- | | Change | Is this change whole, and is it what it claims to be? | While editing: the focused tests for the changed boundary, `mix format`, a warning-free compile. Before merge to `main`: `bash scripts/check.sh` green in hosted CI on the branch, plus an independent review of the diff against its stated purpose. Every merge, not only milestone closures. | A red check or a blocking review finding; the integrator merges only a green, reviewed candidate | -| Close | Did the milestone deliver its outcomes? | `check.sh` once under the floor toolchain pair (the current pair is already proved by CI on every change), `bash scripts/check-release.sh` once, the outcome-to-evidence map in the plan, an independent review of the candidate | The maintainer, who closes it or does not | -| Release | Is the published source the closed source? | The closure evidence, reused when the source is unchanged; the tag on the exact integrated commit | The maintainer's separate release decision | +| Close | Did the milestone deliver its outcomes? | `check.sh` once under the floor toolchain pair (the current pair is already proved by CI on every change), `bash scripts/check-release.sh` once, the outcome-to-evidence map in the plan, an independent review of the candidate — all of it from the **tested implementation SHA**, once; the **administrative closure SHA** that records the decision re-runs nothing | The maintainer, who closes it or does not | +| Release | Is the published source the closed source? | The closure evidence, reused when the source is unchanged; the tag on the **administrative closure SHA**, whose diff from the tested SHA is verified to touch nothing outside `docs/`, plus the two documentation-scoped re-proofs that confinement makes sufficient — `check.sh --docs` on the tagged SHA and a recomputed archive manifest. No suite and no release check run twice | The maintainer's separate release decision | The fast check is the everyday gate. It is credential-free, needs no network, and is the same command locally and in CI, where it runs as diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 34c345322..b1972abb7 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -807,10 +807,18 @@ archive is staged from the exact committed candidate with `git archive`, extracted outside the checkout, compiled, and used to run the two-process workflow from the extraction following the operator guide; its SHA-256, source commit and tree are retained with the closure runs. The release itself is one -annotated `v0.2.0` tag on the integrated closure commit, created on the -maintainer's separate decision, after which the tag object is verified -annotated, `v0.2.0^{commit}` is the reviewed integration commit and reachable -from `main`, and `git show :VERSION` is exactly `0.2.0`. Do not +annotated `v0.2.0` tag created on the maintainer's separate decision, and the +commit it names is the **administrative closure SHA** — the one carrying the +closure record, and therefore the tree a reader who fetches the tag gets. +Four things are verified at the tag, in this order: `git diff --stat +..` touches **nothing outside `docs/`**, which is what +makes everything below sufficient; `bash scripts/check.sh --docs` is green on +the tagged SHA; the archive manifest recomputed from the tagged SHA equals the +one the tested SHA recorded; and the tag object is annotated, with +`v0.2.0^{commit}` reachable from `main` and `git show :VERSION` +exactly `0.2.0`. Nothing else re-runs — no suite, no release check, no +provider credential — because the confinement check is what proves the tagged +source and the closed source are the same source. Do not move the tag, and publish no package, binary, installer or service unit. diff --git a/docs/plans/M5.md b/docs/plans/M5.md index f25f00784..daa21dbbf 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -757,13 +757,12 @@ M5 closes on the two SHAs the fixes, and its Closure row carries both: the **tested implementation SHA** every run above names and the reviewer read, and the **administrative closure SHA** that records the decision and touches only the register row, this pair's -Closure row and the context map. The **documentation gate and the source -archive are proved again on the tagged SHA** — they are the two whose subject -is the published bytes, and the administrative commit changes documentation — -with those results joining the evidence page beside the tag. The runs -themselves are retained immutably, attached to the annotated tag or held -outside the repository with their digests recorded on that page, so the -evidence a reviewer read is the evidence a reader finds. +Closure row and the context map. The closure matrix runs **once**, from the +first of those; the second re-runs nothing, because closure cannot depend on a +tag that closure authorizes. The runs are retained immutably — held outside +the repository with their digests recorded on the evidence page, since every +one of them is produced before any tag exists — so the evidence a reviewer +read is the evidence a reader finds. **The operator page's stop figure is a closure item on that same packet.** Because this pair states the drain's guarantees and not its arithmetic, the @@ -772,9 +771,15 @@ the tested implementation SHA** and recorded with the conditions it was measured under. Closure cannot complete with that row empty, which is what makes the withdrawal of the derived sum an obligation rather than a gap. -**Release.** The release is one annotated `v0.2.0` tag on the exact integrated -closure commit, reusing the closure evidence because the source is unchanged, -plus a verified source archive of that commit. It publishes no Hex package, +**Release.** The release is one annotated `v0.2.0` tag, reusing the closure +evidence because the source is unchanged, plus a verified source archive of +the tagged commit. The tag names the **administrative closure SHA**, so the +release first verifies that commit is confined — its diff from the tested +implementation SHA touches nothing outside `docs/` — and on that basis +re-proves documentation only: `bash scripts/check.sh --docs` on the tagged SHA +and a recomputed archive manifest compared with the one the tested SHA +recorded. No suite and no release check run a second time, and the two results +join the evidence page with the tag named. It publishes no Hex package, binary, installer or service unit, and freezes no public protocol or embedded API. @@ -981,6 +986,20 @@ that adds the tests it names. | 5 | Open | No two-process workflow, daemon operator guide or `0.2.0` source archive exists | | 6 | Open | The adapter resolves the credential from the parent VM's environment inside each call; eleven of the thirteen heavy provider modules reference that variable and all thirteen declare `async: false` | +**Maintainer override of 2026-09-20.** Two development-time rules changed by +maintainer decision, recorded here because both change what a check proves. +**The drain's stop bound is no longer derived in this plan**: three revisions +summed per-step seconds from counted Store calls, four consecutive reviews +corrected the count, and the approach is withdrawn — the pair states the +order and the guarantee, the implementation measures the cost, and the +operator page's figure becomes a closure item. **Closure names two commits**: +the tested implementation SHA the matrix ran on, and the administrative +closure SHA that records the decision; the tag names the second, whose diff +from the first is verified to touch nothing outside `docs/`, and on that basis +the release re-proves documentation only rather than running any check twice. +The second change is to the milestone guide, `AGENTS.md` and the verification +guide, and is written into all three in the same change as this entry. + **Revision of 2026-09-14 (first).** On the independent review of `dc81212360327caa7e8b0ed371cb5ed531b960d9`, the maintainer narrowed this plan in three ways. The daemon-grade store, its selection experiments and its From 6e853ee5968b696a41830aa80c6ecc7ca1dea915 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:21:35 -0700 Subject: [PATCH 177/585] plan(M5): bound the queue, settle the count, fix three befores The one-unresolved-ticket rule left the queue behind it unbounded. It needs no new number: only the controller connection mutates a session, and ADR 0023 already bounds a connection to 32 requests in flight, checked at admission. One unresolved ticket and at most 31 behind it, with the limits row sourced there and no second bound invented. The core-change count said six in two places and five in three others, and the three that said five were the ones that enumerate the changes -- each omitting the bounded session listing. Six, everywhere, with the enumeration `quiesce/1` reads named as part of change 4 rather than left to be counted as a seventh. The provider module split was wrong in an accepted ADR and its verification companion in opposite directions: ADR 0034 said all thirteen install a canary, the companion said twelve share the variable. Derived again from the tree -- thirteen serial modules, eleven referencing the credential variable, the two that do not being serial only because an application runs its modules under one setting. Both documents now say the same thing, which is what the progress row already said. Three smaller befores. The composition chain is links 4 to 8, not 3 to 7 -- an off-by-one against the numbered link table beside it. The embedded migration note's "today" now distinguishes the surfaces it was collapsing: core supersedes and never refuses, `Control` refuses only a repeated request_id under a different binding, and ADR 0023's second-attachment refusal is the app server's connection-level check. And "retained immutably, attached to the tag" could not be the mechanism for a single closure run, every one of which happens before the tag exists; the mechanism is the digest recorded on a page committed at the tested SHA, with the tag anchoring only the two runs that postdate it. --- ...edential-handoff-over-bootstrap-channel.md | 10 ++++-- docs/developer/verification-technical.md | 14 +++++--- docs/plans/M5-technical.md | 29 +++++++++++++++- docs/plans/M5.md | 33 ++++++++++++------- 4 files changed, 66 insertions(+), 20 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index d31020166..dad13d9eb 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -30,9 +30,13 @@ weaker property than the rest of the plane: a secret that has to sit in a process-wide slot for the duration of every call is reachable by anything in the VM that can read the environment, and it is exactly the kind of ambient authority the runtime refuses everywhere else. And it forces serialisation: -the thirteen heavy `loopex_llm_reqllm` test modules each install their own -canary in that slot, so two of them running at once would hand each other's -canary to each other's child. The +**eleven of the thirteen** heavy `loopex_llm_reqllm` test modules install +their own canary in that slot, so two of *those* running at once would hand +each other's canary to each other's child — and because a suite cannot run +eleven of thirteen concurrently and the other two serially without knowing +which is which, all thirteen declare `async: false`. An earlier revision of +this sentence said all thirteen install a canary, which is the serial count +rather than the sharing one. The [verification companion](../developer/verification-technical.md#technical-verification-speed) measured the result at M4 closure — that application is the critical path of the fast check, 96% of its time sits in those thirteen modules, and no further diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index 53edbf2fb..ba3b01b98 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -125,8 +125,10 @@ asynchronous; after step 3, 49 of 119 are. Step 3 examined the four heavy applications only; the six light ones (62 s in sequence, 25 serial modules) were not read and are not claimed here. In the four examined, each module still serial carries one of: the one provider credential variable -written into this VM's environment so the child inherits it (the twelve heavy -`loopex_llm_reqllm` modules, `cli`, `session_directory`, `coding_tools`, +written into this VM's environment so the child inherits it (eleven of the +thirteen heavy `loopex_llm_reqllm` modules — the other two are serial with +them because the application cannot run part of itself concurrently — plus +`cli`, `session_directory`, `coding_tools`, `executor`, `host_policy`); a global `:erlang.trace_pattern` (`cancellation`, `cancellation_observation_contract`, `context_admission`, `skill_context`, `local_authority_contract`, `post_closure_hotfix`, `ledger_record_conformance`, @@ -219,9 +221,11 @@ on the Mac: `loopex` 191 → 125 s, the others within a few seconds of before; the whole fast check, warm build, 254 → 224 s at `69dd710`. The three returned modules run about 1 s, 0.1 s and 22 s. The limit on the critical path is structural: the applications run in parallel VMs, `loopex_llm_reqllm` is the longest, and 96% -of its 209 s sits in the twelve modules that share the process-wide -credential variable, so two of them running at once would hand each other's -canary to each other's child. Making those concurrent means passing the +of its 209 s sits in the **thirteen** modules that run serially — **eleven** +of which share the process-wide credential variable, so two of those running +at once would hand each other's canary to each other's child, and the other +two are serial with them because the application runs its modules under one +setting. Making those concurrent means passing the credential to the child per invocation instead of through the environment, which is a change to the credential plane and a maintainer decision, not a suite change; until then `loopex_llm_reqllm` pins the check near 210 s. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index b1972abb7..fe6e36bdb 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -803,6 +803,21 @@ merely extractable. reviewed commit before closure, as the [milestone guide](../developer/milestones-technical.md#technical-milestones-release) sets out; every application reads it at compile time. The release-ready source +**How a run is retained immutably, since a tag does not exist yet when the +runs happen.** Every run in the closure matrix is produced *before* any tag, +so "attach it to the annotated tag" cannot be the mechanism for any of them. +The mechanism is the other one: each run's full output is written to a file +outside the repository, its **SHA-256 recorded on +`docs/evidence/M5-closure-runs.md`** beside that run's identity, platform, +toolchain, result and measured duration, and the page itself committed at the +tested implementation SHA — so the page a reviewer reads is fixed by the +commit they review, and any later edit to it is a visible diff against that +commit rather than a silent rewrite. What the tag adds is a second anchor for +the two runs that happen *at* the tag: the release's `check.sh --docs` and the +recomputed archive manifest, which the tag's own annotation can carry because +they postdate it. + +The source archive is staged from the exact committed candidate with `git archive`, extracted outside the checkout, compiled, and used to run the two-process workflow from the extraction following the operator guide; its SHA-256, source @@ -1830,6 +1845,17 @@ once the connection process is the caller. decided by one resolution rather than by draining a queue of unknown depth. + **That queue is bounded, and by a number this milestone does not invent.** + Only the controller connection may mutate a session, so every queued + mutation for one session came from one connection — and ADR 0023 already + fixes that "no more than 32 requests are in flight per connection" + (`0023-…-technical.md:332-333`), checked at admission rather than after + enqueue. So a lease owner holds **at most one unresolved ticket and at most + 31 mutations behind it**, and the daemon adds no second queue and no second + bound. A client that exceeds the in-flight bound is refused by the rule that + already exists, at the connection, before any of this. The limits table + carries the row. + **Two of the ten are not mutation tickets and the rule does not reach them**, stated because a rule that silently excluded them would be read as covering them. `session.create` has no session to be one-per, its ticket is @@ -1966,7 +1992,7 @@ composition function builds that configuration — which means before the runtime starts, and the composition function starts the runtime at the end of its own chain, so before the composition call itself. -Order 3 to 7 is the composition's actual chain, not a tidied one: the Store +Links 4 to 8 are the composition's actual chain, not a tidied one: the Store first, then the artifact placement and the executor's own edges, and the runtime last within that chain, because it depends on all of them. @@ -4763,6 +4789,7 @@ line; M5 introduces none of its own. | Store stop | a fixed 30 s, the Store's own `@call_timeout` (`apps/loopex_store_local/lib/loopex/store/local.ex:65`), independent of any grace; the usual release takes milliseconds | This plan, against the Store's existing bound | | Maximum fail-stop exit | **35 s** — 5 s for the executor stop and the Store's own fixed 30 s, the only two steps of that path that wait; 5 s on the two store classes, where the Store is already gone | This plan, as the sum of its parts | | Wait slice | 60_000 ms, so no `receive … after` argument approaches the BEAM's 2^32-1 limit, probed at both pairs | This plan; the limit is the VM's | +| Queued mutations per session in its lease owner | at most 31, behind the one unresolved ticket: only the controller connection mutates a session, and ADR 0023 bounds a connection to 32 requests in flight, checked at admission | ADR 0023, reused; this plan adds no second queue bound | | Lease term | 30 seconds | ADR 0033 | | Lease renewal interval for the reference clients | 10 seconds | ADR 0033 | | Takeover grace beyond expiry | none; takeover is eligible at expiry and granted once the session's in-flight admission set is empty | ADR 0033 | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index daa21dbbf..32b939c65 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -131,9 +131,11 @@ because the daemon serves generation 2 only. The daemon serves generation `loopex.experimental/2` only, which adds `session.list`, `daemon.status`, the two control methods and the writer-epoch field, and lifts the one-attachment-per-process rule to residency limits. It adds no durable -method: core owns durable session truth and its M5 changes are concurrent -attachment, one read-only existence query, trace exclusion, the bounded -`quiesce/1` and two fields on the runtime-side create and resume results, none of which is +method: core owns durable session truth and its **six** M5 changes are +concurrent attachment, one read-only existence query, trace exclusion, the +bounded `quiesce/1` — whose new `Control` enumeration is part of that one +change and not a seventh — two fields on the runtime-side create and resume +results, and the bounded session listing, none of which is a durable command, so a daemon method that ended a session durably would have to add one, which M5 does not do. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, @@ -169,7 +171,7 @@ its loss is core's to supervise; it reaches a client as core's existing refusal on the next command for that session, which the daemon forwards unchanged. Making the daemon track it would need a core notification or a monitorable handle — a **further** core change M5 does not make, beyond the -five it does. Lifting it needs a core operation that can tell quiescent from idle, +six it does. Lifting it needs a core operation that can tell quiescent from idle, which is its own decision and not M5's. `session.list` is a daemon convenience, not an enumeration of durable truth. @@ -541,10 +543,13 @@ Technical depth: [Proportional minimalism budget](M5-technical.md#technical-plan ### Non-Goals No controller lease, transport, socket or collaboration rule inside core. Its -only M5 changes are independent concurrent attachment support, one read-only -session-existence query, the trace exclusion that accepted ADR 0030 already -requires, the bounded `quiesce/1` an orderly stop drains through, and two -plain fields on the runtime-side create and resume results — none of which is a durable +only M5 changes are the **six**: independent concurrent attachment support, +one read-only session-existence query, the trace exclusion that accepted +ADR 0030 already requires, the bounded `quiesce/1` an orderly stop drains +through — the enumeration it reads being part of that change rather than a +seventh — two +plain fields on the runtime-side create and resume results, and the bounded +session listing the daemon pages through — none of which is a durable command, and none of which changes a wire schema. No daemon-grade store adapter, journal format version, migration, backup tooling, compaction, retention cutoff or NIF dependency; no daemon-served generation 1; no durable @@ -821,9 +826,15 @@ lease, the session index or any residency state. **One embedded behaviour does change, and it is named here rather than left to the mechanics, because it is observable.** `Loopex.attach/3` keeps its -shape, but today a second attach to a session supersedes the first whoever -made it — core has no way to ask for anything else — and after the -concurrent-attachment change it supersedes nothing unless the caller says +shape, but today a second attach to a session **supersedes the first and never +refuses it**: the dispatcher splits its attachment map on `session_id` alone +and core carries no `replace` option to ask for anything else, while +`Control` refuses only a *repeated* `request_id` under a different binding, +which is idempotency rather than a second attachment +(`control.ex:1312-1335`). ADR 0023's rule that a second attachment refuses +unless replacement is named is the **app server's** connection-level check, +not core's, which is why an embedded caller meets neither. After the +concurrent-attachment change core supersedes nothing unless the caller says `replace: true` and holds the attachment it means to replace. A caller that attached twice to one session and relied on the older one going away must now say so, and one that does not gets two live attachments rather than a From 8421f9ae8da4ac0f3fa9260cb7a00fc190a9862f Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:23:39 -0700 Subject: [PATCH 178/585] plan(M5): adversarial pass, and class 42 catches its own heading Class 42 run over every phrase this round retired. One survivor, and it is the class exactly: the fixed process table's heading still read "eleven rows, ten without transfers: the owner and the ten it links" while the sentence below it had already been changed to twelve and eleven. Twelve rows, eleven links, in the heading a reader meets first. One finding against this round's own new rule. The release was to recompute the archive manifest from the tagged SHA and compare it with the tested SHA's -- a comparison that can never pass, because the archive carries `docs/` and the administrative commit is docs-only by construction. The comparison is over the entries OUTSIDE `docs/`, which is the property the release actually needs, and which earns its place beside the confinement diff rather than repeating it: `.gitattributes` moves bytes into and out of an archive without showing in any diff. Fixed in all six places that state the rule. --- AGENTS.md | 4 ++-- docs/developer/milestones-technical.md | 2 +- docs/developer/milestones.md | 9 +++++++-- docs/developer/verification.md | 2 +- docs/plans/M5-technical.md | 22 +++++++++++++--------- docs/plans/M5.md | 5 +++-- 6 files changed, 27 insertions(+), 17 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index c30f71b5f..7dca74df6 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -179,8 +179,8 @@ A milestone runs in four steps; the tag names the **administrative** closure SHA, whose diff from the tested SHA is verified to touch nothing outside `docs/`; on that basis the release re-proves documentation only — `bash scripts/check.sh --docs` on the tagged - SHA and a recomputed archive manifest — and re-runs no suite and no release - check. + SHA, and a recomputed archive manifest matching the tested SHA's for every + entry outside `docs/` — and re-runs no suite and no release check. Historical milestones keep their plans, evidence logs, and dispositions as records of what was proved at the revisions they name. Current tests belong to diff --git a/docs/developer/milestones-technical.md b/docs/developer/milestones-technical.md index bee8ddc82..7f883a323 100644 --- a/docs/developer/milestones-technical.md +++ b/docs/developer/milestones-technical.md @@ -140,7 +140,7 @@ reader who fetches the tag gets. Before tagging: | --- | --- | --- | | Confine the administrative diff | `git diff --stat ..` | Any path outside `docs/` means the tag would publish source the closure evidence does not cover; the release stops and the packet is reassembled from a new implementation SHA | | Re-prove the documentation | `bash scripts/check.sh --docs` on the tagged SHA | The administrative commit's own documentation changes are not green; fix and re-tag | -| Re-prove the archive identity | Recompute the archive manifest from the tagged SHA and compare it with the manifest the tested SHA recorded | The published bytes are not the closed bytes outside `docs/`, which the first step should already have caught | +| Re-prove the archive identity | Recompute the archive manifest from the tagged SHA and compare every entry **outside `docs/`** with the manifest the tested SHA recorded | The published bytes are not the closed bytes outside `docs/`. The entries under `docs/` are expected to differ and are not compared; comparing the whole manifest would be a check that can never pass. What this catches beyond step 1 is an archive that includes or excludes differently from the tree — `.gitattributes` moves bytes into and out of an archive without appearing in a `git diff` | Nothing else is re-run. There is no second suite, no second release check and no second provider credential: the tested tree and the tagged tree differ only diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index 9abcedace..6006a97b9 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -101,8 +101,13 @@ closure evidence does not cover, and the release stops. tree differs from the tested one only in documentation, so what is re-proved is documentation: `bash scripts/check.sh --docs` runs on the tagged SHA, and the archive manifest is recomputed from the tagged SHA and compared with the -one the tested SHA recorded. No suite is re-run, no release check is re-run, -and no provider credential is spent again. Their results join the evidence +one the tested SHA recorded **entry by entry outside `docs/`**, which must +match exactly. It is not compared whole — the archive carries `docs/` too, so +a whole-manifest equality could never hold and would be a check that always +fails. Comparing the rest is what catches an archive that includes or excludes +differently from the tree the first step examined, which `.gitattributes` can +do without any diff showing it. No suite is re-run, no release check is +re-run, and no provider credential is spent again. Their results join the evidence page with the tag named. **Run evidence is immutable.** A run's identity, platform, toolchain, result diff --git a/docs/developer/verification.md b/docs/developer/verification.md index e92e8460f..fbe318a40 100644 --- a/docs/developer/verification.md +++ b/docs/developer/verification.md @@ -33,7 +33,7 @@ Technical depth: [What each stage runs](verification-technical.md#technical-veri | --- | --- | --- | --- | | Change | Is this change whole, and is it what it claims to be? | While editing: the focused tests for the changed boundary, `mix format`, a warning-free compile. Before merge to `main`: `bash scripts/check.sh` green in hosted CI on the branch, plus an independent review of the diff against its stated purpose. Every merge, not only milestone closures. | A red check or a blocking review finding; the integrator merges only a green, reviewed candidate | | Close | Did the milestone deliver its outcomes? | `check.sh` once under the floor toolchain pair (the current pair is already proved by CI on every change), `bash scripts/check-release.sh` once, the outcome-to-evidence map in the plan, an independent review of the candidate — all of it from the **tested implementation SHA**, once; the **administrative closure SHA** that records the decision re-runs nothing | The maintainer, who closes it or does not | -| Release | Is the published source the closed source? | The closure evidence, reused when the source is unchanged; the tag on the **administrative closure SHA**, whose diff from the tested SHA is verified to touch nothing outside `docs/`, plus the two documentation-scoped re-proofs that confinement makes sufficient — `check.sh --docs` on the tagged SHA and a recomputed archive manifest. No suite and no release check run twice | The maintainer's separate release decision | +| Release | Is the published source the closed source? | The closure evidence, reused when the source is unchanged; the tag on the **administrative closure SHA**, whose diff from the tested SHA is verified to touch nothing outside `docs/`, plus the two documentation-scoped re-proofs that confinement makes sufficient — `check.sh --docs` on the tagged SHA, and a recomputed archive manifest matching the tested SHA's for every entry outside `docs/`. No suite and no release check run twice | The maintainer's separate release decision | The fast check is the everyday gate. It is credential-free, needs no network, and is the same command locally and in CI, where it runs as diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index fe6e36bdb..9b467f978 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -829,7 +829,11 @@ Four things are verified at the tag, in this order: `git diff --stat ..` touches **nothing outside `docs/`**, which is what makes everything below sufficient; `bash scripts/check.sh --docs` is green on the tagged SHA; the archive manifest recomputed from the tagged SHA equals the -one the tested SHA recorded; and the tag object is annotated, with +one the tested SHA recorded **for every entry outside `docs/`**, the `docs/` +entries being expected to differ and therefore not compared — which catches an +archive that includes or excludes differently from the tree, as +`.gitattributes` can without showing in any diff; and the tag object is +annotated, with `v0.2.0^{commit}` reachable from `main` and `git show :VERSION` exactly `0.2.0`. Nothing else re-runs — no suite, no release check, no provider credential — because the confinement check is what proves the tagged @@ -4566,14 +4570,14 @@ owned by core, the adapter or the executor appears as a **group with its owner**, because their counts are those components' business and naming them individually would make this table a copy that rots. -**The daemon's fixed processes — eleven rows, ten without transfers: the owner -and the ten it links.** The count is stated that way because the table has one -more row than the link set does, the owner being the process that holds the -links rather than one of them. Earlier revisions headed eleven rows "ten", and -then left the **connection registry** — a fixed, linked, daemon-fatal process -— in the dynamic table below under the heading "one fixed process", where a -reader looking for the linked set could not find it. Twelve rows, eleven -links. +**The daemon's fixed processes — twelve rows, eleven without transfers: the +owner and the eleven it links.** The count is stated that way because the +table has one more row than the link set does, the owner being the process +that holds the links rather than one of them. Earlier revisions headed eleven +rows "ten", and then left the **connection registry** — a fixed, linked, +daemon-fatal process — in the dynamic table below under the heading "one fixed +process", where a reader looking for the linked set could not find it. It is +the eleventh link and it is in this table. | Process | Started by | Linked to | Stopped by | Its death | | --- | --- | --- | --- | --- | diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 32b939c65..926ff7d9b 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -782,8 +782,9 @@ the tagged commit. The tag names the **administrative closure SHA**, so the release first verifies that commit is confined — its diff from the tested implementation SHA touches nothing outside `docs/` — and on that basis re-proves documentation only: `bash scripts/check.sh --docs` on the tagged SHA -and a recomputed archive manifest compared with the one the tested SHA -recorded. No suite and no release check run a second time, and the two results +and a recomputed archive manifest whose entries **outside `docs/`** match the +one the tested SHA recorded — the `docs/` entries are expected to differ, so +the whole manifest is never compared. No suite and no release check run a second time, and the two results join the evidence page with the tag named. It publishes no Hex package, binary, installer or service unit, and freezes no public protocol or embedded API. From 449475d732587358e8917e79773ae01196cca585 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:25:23 -0700 Subject: [PATCH 179/585] adr(M5): eleven share the slot, and the other two never did The count fix landed with a wrong justification of my own: that a suite cannot run eleven of thirteen modules concurrently and the other two serially, so all thirteen are serial for the credential variable. ExUnit runs exactly that arrangement, and the two are serial for reasons the credential decision does not touch -- `m0_child_environment_conformance_test.exs` writes a process-wide environment sentinel of its own, `provider_build_test.exs` builds a shared artifact. Read both files rather than inferring from the count. That matters beyond tidiness: ADR 0034's benefit claim was that removing the process-wide read frees "the twelve provider test modules" to run concurrently. It frees eleven. The other two stay serial either way, in the Concept, the technical companion and the verification companion alike. --- ...handoff-over-bootstrap-channel-technical.md | 7 ++++--- ...redential-handoff-over-bootstrap-channel.md | 18 +++++++++++------- docs/developer/verification-technical.md | 11 ++++++----- 3 files changed, 21 insertions(+), 15 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index a90209275..49916617b 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -999,9 +999,10 @@ that carries no bytes. Its record is retained with the milestone's evidence. ### Concurrency, as a measurement -With the process-wide read gone, the twelve `loopex_llm_reqllm` modules that -declare `async: false` for that reason may declare `async: true` one at a -time, each kept only after the application's suite stays green across several +With the process-wide read gone, the **eleven** `loopex_llm_reqllm` modules +that declare `async: false` for that reason may declare `async: true` one at a +time — the other two of the thirteen stay serial on reasons of their own, a +process-wide environment sentinel and a shared build artifact — each kept only after the application's suite stays green across several seeds, exactly as the M4 speed work converted the other twenty-one modules. The result is recorded against the baseline in the [verification companion](../developer/verification-technical.md#technical-verification-speed): diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index dad13d9eb..999adc77e 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -32,11 +32,13 @@ the VM that can read the environment, and it is exactly the kind of ambient authority the runtime refuses everywhere else. And it forces serialisation: **eleven of the thirteen** heavy `loopex_llm_reqllm` test modules install their own canary in that slot, so two of *those* running at once would hand -each other's canary to each other's child — and because a suite cannot run -eleven of thirteen concurrently and the other two serially without knowing -which is which, all thirteen declare `async: false`. An earlier revision of -this sentence said all thirteen install a canary, which is the serial count -rather than the sharing one. The +each other's canary to each other's child. The other two of the thirteen are +serial for reasons of their own, which this decision does not touch: one +writes a process-wide environment sentinel of its own +(`m0_child_environment_conformance_test.exs`) and one builds a shared artifact +(`provider_build_test.exs`). An earlier revision of this sentence said all +thirteen install a canary, which is the serial count rather than the sharing +one, and made this decision look like it frees two modules it does not. The [verification companion](../developer/verification-technical.md#technical-verification-speed) measured the result at M4 closure — that application is the critical path of the fast check, 96% of its time sits in those thirteen modules, and no further @@ -230,8 +232,10 @@ process, which holds it and answers for it, and the short-lived sender, which receives it once, writes it and dies — and in the child that needs it. Nowhere else: not in adapter state, not in the environment, not in a durable or public plane, and in no message but the one reply this pair permits. Two invocations in -one VM become independent, so the twelve provider test modules can run -concurrently and the fast check stops being pinned by that application. Host +one VM become independent, so the **eleven** provider test modules serial for +this reason can run concurrently and the fast check stops being pinned by that +application. The other two stay serial on their own reasons, which is why the +claim is eleven rather than thirteen. Host composition gains one explicit input and one explicit obligation: a host that starts a runtime with this adapter passes a credential token with the call, instead of relying on the VM's environment being right at call time, and it diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index ba3b01b98..fbd5d0017 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -126,8 +126,9 @@ applications only; the six light ones (62 s in sequence, 25 serial modules) were not read and are not claimed here. In the four examined, each module still serial carries one of: the one provider credential variable written into this VM's environment so the child inherits it (eleven of the -thirteen heavy `loopex_llm_reqllm` modules — the other two are serial with -them because the application cannot run part of itself concurrently — plus +thirteen heavy `loopex_llm_reqllm` modules; the other two of the thirteen +carry a different one of these reasons each — a process-wide environment +sentinel of their own, and a shared build artifact — plus `cli`, `session_directory`, `coding_tools`, `executor`, `host_policy`); a global `:erlang.trace_pattern` (`cancellation`, `cancellation_observation_contract`, `context_admission`, `skill_context`, @@ -223,9 +224,9 @@ run about 1 s, 0.1 s and 22 s. The limit on the critical path is structural: the applications run in parallel VMs, `loopex_llm_reqllm` is the longest, and 96% of its 209 s sits in the **thirteen** modules that run serially — **eleven** of which share the process-wide credential variable, so two of those running -at once would hand each other's canary to each other's child, and the other -two are serial with them because the application runs its modules under one -setting. Making those concurrent means passing the +at once would hand each other's canary to each other's child, while the +remaining two are serial on their own reasons and would stay serial either +way. Making those concurrent means passing the credential to the child per invocation instead of through the environment, which is a change to the credential plane and a maintainer decision, not a suite change; until then `loopex_llm_reqllm` pins the check near 210 s. From 9f3ca1d233ee8f2ee7857cc2312ecaf14a3e4d2b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:41:16 -0700 Subject: [PATCH 180/585] plan(M5): one confinement, and the class the map was missing Two findings of one class again, both against additions of the last two rounds. The fatal-class map never got a `connections_lost` row. The class enumeration says twelve classes and names it, the fail-stop witness asserts it, the process table assigns it -- and the map that is supposed to be the one place a class is decided carried eleven rows for eleven components, which made its own two closure claims false where they are stated: "one class per linked component" and "one row per linked process except the Store's". The row is there, with its wire cell reading like the listener's, since those are the two classes that reach no client. The administrative closure commit had three different confinements and the evidence page had no home under any of them. "Changes nothing the runs covered" and "the register row, the Closure row, the context-map entry" both exclude the page that records the runs -- while the closure steps still ran under "At the candidate commit" and asked that commit to retain runs of itself, which is the circularity the two-SHA rule was adopted to remove. There is now ONE confinement, stated once in the milestone guide's technical companion and referenced by the other five passages: exactly four paths -- register row, Closure row, context-map entry, and `docs/evidence/-closure-runs.md`, which carries the run identities, results, durations, the archive manifest's digest and the security review. All four are under `docs/`, so "nothing outside `docs/`" is a consequence and now says so. The runs move out from under the candidate heading: they are OF the tested commit and RECORDED by the administrative one. "The manifest the tested SHA recorded" became "the manifest recorded on the evidence page for the tested SHA", because a SHA records nothing. Three smaller ones. The Purpose still called core change 1 two halves, which five other passages and ADR 0032 correct to three parts -- the third being Control's own attachment and repetition state, the component whose absence made a controller's next command fail. A one-space-indented "An" orphaned a paragraph from its bullet and left "an earlier revision called it a read" with no antecedent. And the override disposition now names the register's capsule strings and the test that pins them, which were changed under it. --- AGENTS.md | 11 ++++-- docs/developer/agent-context-map.md | 18 +++++++-- docs/developer/milestones-technical.md | 54 +++++++++++++++++++------- docs/developer/milestones.md | 38 ++++++++++-------- docs/developer/verification.md | 2 +- docs/plans/M5-technical.md | 26 ++++++++----- docs/plans/M5.md | 40 ++++++++++++------- 7 files changed, 127 insertions(+), 62 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 7dca74df6..77be0ffc5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -171,13 +171,18 @@ A milestone runs in four steps; the reads the candidate; the maintainer closes it and the register moves to `Closed`. Closure names **two commits**: the *tested implementation SHA* the matrix ran on and the reviewer read, and the *administrative closure - SHA* that records the decision and changes nothing the runs covered. One - commit cannot name itself. Run evidence is immutable — held where it cannot + SHA* that records the decision. One commit cannot name itself, and the runs + are of the first, so the second is what writes them down. It is confined to + four paths — register row, Closure row, context-map entry, evidence page — + which the + [milestone guide](docs/developer/milestones-technical.md#technical-milestones-confinement) + states once. Run evidence is immutable — held where it cannot be edited after the packet is read. 4. **Release.** Publication, tags, and packages are separate maintainer decisions that reuse the closure evidence when the source is unchanged. The tag names the **administrative** closure SHA, whose diff from the tested - SHA is verified to touch nothing outside `docs/`; on that basis the release + SHA is verified to be confined to those four paths — all under `docs/`, so + nothing outside `docs/` moved; on that basis the release re-proves documentation only — `bash scripts/check.sh --docs` on the tagged SHA, and a recomputed archive manifest matching the tested SHA's for every entry outside `docs/` — and re-runs no suite and no release check. diff --git a/docs/developer/agent-context-map.md b/docs/developer/agent-context-map.md index 01da3090a..0dafccd9d 100644 --- a/docs/developer/agent-context-map.md +++ b/docs/developer/agent-context-map.md @@ -5383,8 +5383,15 @@ evidence and its closure record at one SHA, which no sequence of commits can satisfy: recording the decision is itself a commit, and it comes after the runs. Closure now names a **tested implementation SHA** — the candidate the matrix ran on and the reviewer read — and an **administrative closure SHA** -that records the decision and changes nothing the runs covered. The matrix -runs once, from the first. +that records the decision. The matrix runs once, from the first, and the +second is **confined to four paths** — the register row, the plan's Closure +row, this context map's own entry, and the milestone's closure-runs evidence +page — stated once in +[the confinement rule](milestones-technical.md#technical-milestones-confinement). +The evidence page is in that list deliberately: the runs are *of* the tested +commit, so the commit that records them is necessarily the later one, and an +earlier wording that let the administrative commit change "nothing the runs +covered" left that page with no home at all. The **tag names the administrative SHA**, because that is the tree a reader who fetches the tag gets. The release verifies that commit is confined — @@ -5404,5 +5411,10 @@ and `docs/developer`. Written into [technical companion](milestones-technical.md#technical-milestones-close), `AGENTS.md` § Milestones and Checks steps 3 and 4, and [the verification guide](verification.md#concept-verification-stages)'s stage -table, in one change with this entry. It grants no tag, release or +table — and, because the register derives its own prose, into +`apps/loopex/lib/mix/tasks/status/register.ex`, whose `In progress` and +`In review` capsule strings named "the candidate" and a single closure row, +together with `apps/loopex/test/status_check_test.exs`, which pins those exact +strings and would otherwise be the thing that decides what the guide says. All +of it in one change with this entry. It grants no tag, release or publication. diff --git a/docs/developer/milestones-technical.md b/docs/developer/milestones-technical.md index 7f883a323..e95b658d0 100644 --- a/docs/developer/milestones-technical.md +++ b/docs/developer/milestones-technical.md @@ -75,28 +75,33 @@ Concept: [Develop](milestones.md#concept-milestones-develop). Concept: [Close](milestones.md#concept-milestones-close). -At the candidate commit: +At the **tested implementation commit**, which is the closure candidate: 1. Every Progress and Evidence row reads `Proved` and names its tests, retained evidence or demonstration; an outcome the maintainer deferred says so and cites their decision. 2. Documentation the milestone changed is updated: `CHANGELOG.md`, `README.md`, the affected `docs/` pages and their indexes. -3. Runs from the exact candidate, retained on `docs/evidence/NAME-closure-runs.md` - (indexed in `docs/evidence/README.md`) with revision, platform, toolchain, - result and measured duration: `bash scripts/check.sh` under the floor pair +3. The closure matrix, run **from** that commit: `bash scripts/check.sh` under + the floor pair (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`, with its own `MIX_BUILD_ROOT`), and `bash scripts/check-release.sh` once on the current pair with the credential and pinned Node; CI already holds the - current-pair fast check for the candidate. + current-pair fast check for the candidate. Each run's revision, platform, + toolchain, result and measured duration is **recorded on + `docs/evidence/NAME-closure-runs.md`** (indexed in + `docs/evidence/README.md`) **by the administrative commit, not by this + one** — the runs are *of* the tested commit, and a commit cannot carry runs + of itself. That page is one of the four paths below. 4. An independent reviewer reads the candidate for outcome compliance, correctness, test honesty, public impact, security and rollback; blocking findings are fixed first. 5. The packet to the maintainer: outcomes and their proof, the runs, the review, what remains. On their decision, the **administrative closure commit** moves the register row to `Closed`, fills the plan's Closure row, - and records the maintainer's words in - `docs/developer/agent-context-map.md`. `mix loopex.status` derives the + records the maintainer's words in + `docs/developer/agent-context-map.md`, and writes the evidence page with + the runs of step 3. `mix loopex.status` derives the `Closed` capsule; run it and copy what it expects. **The two SHAs, and what each one carries.** @@ -104,7 +109,7 @@ At the candidate commit: | | Tested implementation SHA | Administrative closure SHA | | --- | --- | --- | | What it is | The candidate the checks ran on and the reviewer read | The commit that records the decision | -| What it changes | Everything the milestone implemented | The register row, the plan's Closure row, the context-map entry, and nothing else | +| What it changes | Everything the milestone implemented | The four paths below, and nothing else | | What names it | Every run on the evidence page, and the review | The register, once `Closed` | | Its evidence | The runs of step 3, taken from it | None of its own; it is a record, not a claim | @@ -114,11 +119,30 @@ reviewer checking the milestone reads the first; a reader tracing the decision reads the second. Recording only one leaves either the evidence or the decision unlocatable. -**The administrative commit is verifiable as administrative**, and that is -what keeps the split honest rather than decorative: its diff touches only the -four places above, so `git show` over it is the check. Anything else in that -diff means the evidence no longer covers the tree, and the packet is -reassembled from a new implementation SHA. + +**The confinement, stated once and referenced everywhere else.** The +administrative closure commit touches **exactly these four paths**: + +| Path | What it carries | +| --- | --- | +| `docs/plans/README.md` | The register row, moved to `Closed` | +| `docs/plans/.md` | The plan's Closure row, naming both SHAs | +| `docs/developer/agent-context-map.md` | The maintainer's closure disposition | +| `docs/evidence/-closure-runs.md` | The run identities, results and measured durations of step 3, the archive manifest's digest, and the security review | + +and **nothing else**. That is the whole rule; every other passage in this +repository that bounds the administrative commit refers here rather than +restating it, because three different formulations of it — "changes nothing +the runs covered", "the register row, the Closure row and the context-map +entry", "nothing outside `docs/`" — coexisted in five documents and disagreed +about whether the evidence page had a home. + +All four are under `docs/`, so "the administrative commit touches nothing +outside `docs/`" is a **consequence** of this rule rather than a second rule, +and that is how the release step states it. `git diff --name-only +..` against those four paths is the check; anything +else in that diff means the evidence no longer covers the tree, and the packet +is reassembled from a new implementation SHA. **The closure matrix runs once, from the tested implementation SHA**, and the administrative commit re-runs nothing. What the tag re-proves, and how it is @@ -138,9 +162,9 @@ reader who fetches the tag gets. Before tagging: | Step | Command | What a failure means | | --- | --- | --- | -| Confine the administrative diff | `git diff --stat ..` | Any path outside `docs/` means the tag would publish source the closure evidence does not cover; the release stops and the packet is reassembled from a new implementation SHA | +| Confine the administrative diff | `git diff --name-only ..`, against [the four paths](#technical-milestones-confinement) | Any other path means the tag would publish source the closure evidence does not cover; the release stops and the packet is reassembled from a new implementation SHA. Because all four are under `docs/`, a passing check also establishes that nothing outside `docs/` moved, which is what makes the two re-proofs below sufficient | | Re-prove the documentation | `bash scripts/check.sh --docs` on the tagged SHA | The administrative commit's own documentation changes are not green; fix and re-tag | -| Re-prove the archive identity | Recompute the archive manifest from the tagged SHA and compare every entry **outside `docs/`** with the manifest the tested SHA recorded | The published bytes are not the closed bytes outside `docs/`. The entries under `docs/` are expected to differ and are not compared; comparing the whole manifest would be a check that can never pass. What this catches beyond step 1 is an archive that includes or excludes differently from the tree — `.gitattributes` moves bytes into and out of an archive without appearing in a `git diff` | +| Re-prove the archive identity | Recompute the archive manifest from the tagged SHA and compare every entry **outside `docs/`** with the manifest recorded on the evidence page for the tested SHA | The published bytes are not the closed bytes outside `docs/`. The entries under `docs/` are expected to differ and are not compared; comparing the whole manifest would be a check that can never pass. What this catches beyond step 1 is an archive that includes or excludes differently from the tree — `.gitattributes` moves bytes into and out of an archive without appearing in a `git diff` | Nothing else is re-run. There is no second suite, no second release check and no second provider credential: the tested tree and the tagged tree differ only diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index 6006a97b9..ac1f2f58e 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -64,15 +64,19 @@ packet to the maintainer. The maintainer closes it; the register moves to the `close-milestone` skill. **Closure names two commits, because one cannot name itself.** The checks and -the review are of a **tested implementation commit**; recording the closure — -the register row, the Closure row, the context-map entry — is a further commit -that necessarily comes after, and that the evidence therefore cannot have -been taken from. Earlier wording asked for both from one SHA, which no -sequence of commits can satisfy. So a closure carries the **tested -implementation SHA**, which the runs and the review name, and the -**administrative closure SHA**, which records the decision and changes nothing -the runs covered. A closure whose administrative commit touches anything -else is not administrative, and its evidence is stale. +the review are of a **tested implementation commit**; recording the closure is +a further commit that necessarily comes after, and that the evidence therefore +cannot have been taken from — the runs are *of* the tested commit, so the +evidence page that holds them is written by the second, not the first. Earlier +wording asked for both from one SHA, which no sequence of commits can satisfy. +So a closure carries the **tested implementation SHA**, which the runs and the +review name, and the **administrative closure SHA**, which records the +decision. That second commit is **confined to four paths** — the register row, +the plan's Closure row, the context-map entry and the evidence page — which +the [technical companion](milestones-technical.md#technical-milestones-confinement) +states once and everything else refers to. A closure whose administrative +commit touches anything else is not administrative, and its evidence is +stale. The closure matrix is run **once**, from the tested implementation SHA, and nothing in closure is re-run because of the administrative commit. What that @@ -90,19 +94,21 @@ package, installer or publication is its own decision with its own evidence. **The tag names the administrative closure SHA**, which is the commit that carries the closure record and therefore the tree a reader who fetches the tag -gets. That is only safe because the administrative commit is confined: its -diff from the tested implementation SHA must touch **nothing outside -`docs/`**, and the release step verifies that rather than trusting it — -`git diff --stat ..` with every path under `docs/`. +gets. That is only safe because the administrative commit is confined to +[its four paths](milestones-technical.md#technical-milestones-confinement), +and the release step verifies that rather than trusting it — +`git diff --name-only ..` against exactly those four. A diff that reaches anything else means the tag would publish source the -closure evidence does not cover, and the release stops. +closure evidence does not cover, and the release stops. All four are under +`docs/`, so a passing check also establishes that nothing outside `docs/` +moved; that is a consequence of the confinement, not a second rule. **Two checks run at the tag, and neither is a second closure.** The tagged tree differs from the tested one only in documentation, so what is re-proved is documentation: `bash scripts/check.sh --docs` runs on the tagged SHA, and the archive manifest is recomputed from the tagged SHA and compared with the -one the tested SHA recorded **entry by entry outside `docs/`**, which must -match exactly. It is not compared whole — the archive carries `docs/` too, so +one recorded on the evidence page for the tested SHA, **entry by entry +outside `docs/`**, which must match exactly. It is not compared whole — the archive carries `docs/` too, so a whole-manifest equality could never hold and would be a check that always fails. Comparing the rest is what catches an archive that includes or excludes differently from the tree the first step examined, which `.gitattributes` can diff --git a/docs/developer/verification.md b/docs/developer/verification.md index fbe318a40..a8fec78d3 100644 --- a/docs/developer/verification.md +++ b/docs/developer/verification.md @@ -33,7 +33,7 @@ Technical depth: [What each stage runs](verification-technical.md#technical-veri | --- | --- | --- | --- | | Change | Is this change whole, and is it what it claims to be? | While editing: the focused tests for the changed boundary, `mix format`, a warning-free compile. Before merge to `main`: `bash scripts/check.sh` green in hosted CI on the branch, plus an independent review of the diff against its stated purpose. Every merge, not only milestone closures. | A red check or a blocking review finding; the integrator merges only a green, reviewed candidate | | Close | Did the milestone deliver its outcomes? | `check.sh` once under the floor toolchain pair (the current pair is already proved by CI on every change), `bash scripts/check-release.sh` once, the outcome-to-evidence map in the plan, an independent review of the candidate — all of it from the **tested implementation SHA**, once; the **administrative closure SHA** that records the decision re-runs nothing | The maintainer, who closes it or does not | -| Release | Is the published source the closed source? | The closure evidence, reused when the source is unchanged; the tag on the **administrative closure SHA**, whose diff from the tested SHA is verified to touch nothing outside `docs/`, plus the two documentation-scoped re-proofs that confinement makes sufficient — `check.sh --docs` on the tagged SHA, and a recomputed archive manifest matching the tested SHA's for every entry outside `docs/`. No suite and no release check run twice | The maintainer's separate release decision | +| Release | Is the published source the closed source? | The closure evidence, reused when the source is unchanged; the tag on the **administrative closure SHA**, whose diff from the tested SHA is verified to be confined to the four paths the milestone guide fixes (all under `docs/`), plus the two documentation-scoped re-proofs that confinement makes sufficient — `check.sh --docs` on the tagged SHA, and a recomputed archive manifest matching the tested SHA's for every entry outside `docs/`. No suite and no release check run twice | The maintainer's separate release decision | The fast check is the everyday gate. It is credential-free, needs no network, and is the same command locally and in CI, where it runs as diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 9b467f978..1c89e7c49 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -825,11 +825,14 @@ commit and tree are retained with the closure runs. The release itself is one annotated `v0.2.0` tag created on the maintainer's separate decision, and the commit it names is the **administrative closure SHA** — the one carrying the closure record, and therefore the tree a reader who fetches the tag gets. -Four things are verified at the tag, in this order: `git diff --stat -..` touches **nothing outside `docs/`**, which is what +Four things are verified at the tag, in this order: `git diff --name-only +..` reaches **only +[the four confined paths](../developer/milestones-technical.md#technical-milestones-confinement)** +— all under `docs/`, so nothing outside `docs/` moved, which is what makes everything below sufficient; `bash scripts/check.sh --docs` is green on the tagged SHA; the archive manifest recomputed from the tagged SHA equals the -one the tested SHA recorded **for every entry outside `docs/`**, the `docs/` +one recorded on the evidence page for the tested SHA **for every entry outside +`docs/`**, the `docs/` entries being expected to differ and therefore not compared — which catches an archive that includes or excludes differently from the tree, as `.gitattributes` can without showing in any diff; and the tag object is @@ -1787,10 +1790,9 @@ performs the call nor owns its lifetime. An earlier revision proposed an internal attach form taking a stable holder pid instead of the caller, which would have added a core surface no inventory carried and contradicted every caller-is-holder passage in this pair; it is withdrawn, and nothing needs it -once the connection process is the caller. - - An - earlier revision called it a read and left it out, which it is not: its +once the connection process is the caller. An + earlier revision called `session.attach` a read and left it out of the + ticketed set, which it is not: its second leg **mutates the dispatcher**. `Runtime.attach/3` calls `{:attach, …}` on the dispatcher (`runtime.ex:199-210`, `:538`), whose handler spawns a scan worker, monitors the caller and records a pending scan @@ -3893,8 +3895,11 @@ the next marker holder removes. **reader is the owner's `{:EXIT, pid, reason}` clause**, which matches the pid against the fixed set it holds, maps it to a component and classifies the reason; there is one place in the daemon where a class is decided, and this is it. The -set is closed: **one class per linked component**, so no linked process can -die without a name for it. +set is closed: **one class per linked component** — eleven components, twelve +non-startup rows, the Store carrying two — so no linked process can +die without a name for it. An earlier revision added the connection registry +to the process table, the class enumeration and the witness without adding it +here, which made exactly this sentence false. | Class | When | Wire reason | | --- | --- | --- | @@ -3915,7 +3920,8 @@ die without a name for it. | `capability_lost` | The tracing capability exited | `fatal:capability_lost` | | `runtime_lost` | The runtime root exited | `fatal:runtime_lost` | | `relay_lost` | The admission relay exited, taking every outstanding admission ticket with it | `fatal:relay_lost` | -| `listener_lost` | The listener exited | — the listener is what would have written it | +| `connections_lost` | The connection registry exited, taking every connection's slot, monitor and buffer control with it | — one of the two that reach no client: the record would have gone out **through** the interface that is gone | +| `listener_lost` | The listener exited | — one of the two that reach no client: the listener is what would have written it | **A lease owner's exit is the one that is not in this table**, and its absence is the rule rather than an omission. The owner's clause maps that pid to the diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 926ff7d9b..691788871 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -55,10 +55,14 @@ M5 answers the vision's durable-service question and carries the roadmap's v0.2 candidate rung. It reuses M4's protocol, interactions, transfers and observability unchanged and adds the daemon and its collaboration rule above the core. Core gains exactly six narrow things: support for several -independent attachments to one session — which is two halves of one change, +independent attachments to one session — which is three parts of one change, since it stops same-session supersession from removing an attachment and therefore has to add what removes one instead, a monitor on the attaching -process that releases its attachment when that process ends; one read-only +process that releases its attachment when that process ends, and has to scope +`Control`'s own attachment and repetition state by that same holder pid, +`Control` being single-attachment per session today and therefore the +component that would otherwise fail a controller's next command when an +observer attached; one read-only query that answers whether a session ID exists durably in the root; `Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion accepted ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, @@ -753,16 +757,19 @@ toolchain pair; `bash scripts/check-release.sh` runs once with the provider credential and pinned Node, which is where the attended two-process demonstration of Outcome 5, the fresh-source build and Outcome 6's real-provider lane are proved. Each run's revision, platform, toolchain, -result and measured duration is retained on `docs/evidence/M5-closure-runs.md` -with the security review of Outcome 6. An independent reviewer reads the +result and measured duration is recorded on `docs/evidence/M5-closure-runs.md` +with the security review of Outcome 6 — **by the administrative commit**, the +runs being of the tested one. An independent reviewer reads the candidate; the maintainer closes it. M5 closes on the two SHAs the [milestone guide](../developer/milestones.md#concept-milestones-close) now fixes, and its Closure row carries both: the **tested implementation SHA** every run above names and the reviewer read, and the **administrative closure -SHA** that records the decision and touches only the register row, this pair's -Closure row and the context map. The closure matrix runs **once**, from the +SHA** that records the decision and is confined to +[its four paths](../developer/milestones-technical.md#technical-milestones-confinement): +the register row, this pair's Closure row, the context-map entry and +`docs/evidence/M5-closure-runs.md`. The closure matrix runs **once**, from the first of those; the second re-runs nothing, because closure cannot depend on a tag that closure authorizes. The runs are retained immutably — held outside the repository with their digests recorded on the evidence page, since every @@ -780,11 +787,12 @@ makes the withdrawal of the derived sum an obligation rather than a gap. evidence because the source is unchanged, plus a verified source archive of the tagged commit. The tag names the **administrative closure SHA**, so the release first verifies that commit is confined — its diff from the tested -implementation SHA touches nothing outside `docs/` — and on that basis +implementation SHA reaching none of the four paths' neighbours, and therefore +nothing outside `docs/` — and on that basis re-proves documentation only: `bash scripts/check.sh --docs` on the tagged SHA and a recomputed archive manifest whose entries **outside `docs/`** match the -one the tested SHA recorded — the `docs/` entries are expected to differ, so -the whole manifest is never compared. No suite and no release check run a second time, and the two results +one recorded on the evidence page for the tested SHA — the `docs/` entries are +expected to differ, so the whole manifest is never compared. No suite and no release check run a second time, and the two results join the evidence page with the tag named. It publishes no Hex package, binary, installer or service unit, and freezes no public protocol or embedded API. @@ -1006,11 +1014,15 @@ corrected the count, and the approach is withdrawn — the pair states the order and the guarantee, the implementation measures the cost, and the operator page's figure becomes a closure item. **Closure names two commits**: the tested implementation SHA the matrix ran on, and the administrative -closure SHA that records the decision; the tag names the second, whose diff -from the first is verified to touch nothing outside `docs/`, and on that basis -the release re-proves documentation only rather than running any check twice. -The second change is to the milestone guide, `AGENTS.md` and the verification -guide, and is written into all three in the same change as this entry. +closure SHA that records the decision and is **confined to four paths** — the +register row, this pair's Closure row, the context-map entry and the evidence +page, which is where the runs of the tested SHA are written down because a +commit cannot carry runs of itself. The tag names the second, whose diff from +the first is verified against exactly those four, and on that basis the +release re-proves documentation only rather than running any check twice. +The second change is to the milestone guide, `AGENTS.md`, the verification +guide and the register's own capsule prose, and is written into all of them in +the same change as this entry. **Revision of 2026-09-14 (first).** On the independent review of `dc81212360327caa7e8b0ed371cb5ed531b960d9`, the maintainer narrowed this plan From adc2ac77ff9b27c43ef10ddd3dd19bd0495428ff Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:43:14 -0700 Subject: [PATCH 181/585] docs(M5): the skill states the rule the guide changed Adversarial pass. Class 42 over every phrase this round retired found three more places still speaking the old rule, and one of them is the enforcement path rather than prose. `close-milestone/SKILL.md` -- the executable procedure a client runs -- still said "record the candidate SHA in the plan" and had step 3 retaining runs against the candidate. It now names the tested implementation SHA, keeps the run output outside the repository with its digest, and makes step 5 the administrative commit confined to its four paths, with the Closure row naming both SHAs. A guide rule that the skill contradicts is a rule nothing follows. `milestones.md`'s own opening paragraph still said "From that exact commit ... retain the run identities on an evidence page", which is the circularity two paragraphs below it had just removed. And the context-map disposition still described the release check as `--stat` against "nothing outside `docs/`" and compared the manifest with "the one the tested SHA recorded". One count tightened while the map's was fixed: the fail-stop enumeration said twelve classes "one per linked component of the fixed set", which cannot both be true of eleven components. Eleven components, twelve classes, the Store carrying two -- the same sentence the map now carries. --- .agents/skills/close-milestone/SKILL.md | 15 +++++++++++---- docs/developer/agent-context-map.md | 10 ++++++---- docs/developer/milestones.md | 11 ++++++----- docs/plans/M5-technical.md | 4 ++-- 4 files changed, 25 insertions(+), 15 deletions(-) diff --git a/.agents/skills/close-milestone/SKILL.md b/.agents/skills/close-milestone/SKILL.md index f5f1e8294..9be08c58b 100644 --- a/.agents/skills/close-milestone/SKILL.md +++ b/.agents/skills/close-milestone/SKILL.md @@ -17,17 +17,24 @@ technical guidance. The process is the is open; say so. 2. Update the documentation the milestone changed: `CHANGELOG.md`, `README.md`, the affected `docs/` pages and indexes. -3. From the exact committed candidate, run the closure matrix in the +3. From the exact committed candidate — the **tested implementation SHA** — + run the closure matrix in the [verification guide](../../../docs/developer/verification.md#concept-verification-stages): `bash scripts/check.sh` under the floor toolchain pair and `bash scripts/check-release.sh` once. The current pair's fast check is the CI run the candidate already produced; count it rather than repeating it. - Retain each run's complete output with the candidate SHA, platform, and - toolchain. + Retain each run's complete output outside the repository, with its digest, + the tested implementation SHA, platform, and toolchain. It is written to + `docs/evidence/-closure-runs.md` in step 5, not here: the runs are of + the candidate, and the candidate cannot carry runs of itself. 4. Ask an independent reviewer to read the candidate for outcome compliance, correctness, test honesty, public impact, security, and rollback. 5. Present the packet to the maintainer: outcomes and their proof, check results, review findings, and what remains. The maintainer closes it; then - move the register row to `Closed` and record the candidate SHA in the plan. + make the **administrative closure commit**, which is + [confined to four paths](../../../docs/developer/milestones-technical.md#technical-milestones-confinement): + the register row moved to `Closed`, the plan's Closure row naming **both** + the tested implementation SHA and this commit, the context-map disposition, + and the evidence page with step 3's runs. Nothing else belongs in it. Tags, packages, and publication are separate maintainer decisions. diff --git a/docs/developer/agent-context-map.md b/docs/developer/agent-context-map.md index 0dafccd9d..d326ee8d4 100644 --- a/docs/developer/agent-context-map.md +++ b/docs/developer/agent-context-map.md @@ -5395,10 +5395,12 @@ covered" left that page with no home at all. The **tag names the administrative SHA**, because that is the tree a reader who fetches the tag gets. The release verifies that commit is confined — -`git diff --stat ..` touching nothing outside -`docs/` — and on that basis re-proves documentation only: `check.sh --docs` on -the tagged SHA and a recomputed archive manifest against the one the tested -SHA recorded. **No suite and no release check run twice**, and no provider +`git diff --name-only ..` reaching only the four paths +above, all of which are under `docs/`, so nothing outside `docs/` moved — and +on that basis re-proves documentation only: `check.sh --docs` on +the tagged SHA, and a recomputed archive manifest compared, for every entry +outside `docs/`, with the one recorded on the evidence page for the tested +SHA. **No suite and no release check run twice**, and no provider credential is spent again. Run evidence is immutable, held where it cannot be edited after the packet is read. diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index ac1f2f58e..c97367ea8 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -57,11 +57,12 @@ A closure candidate is one commit on `main` at which every outcome maps to tests, retained evidence or a demonstration, the documentation the milestone changed is updated, and the plan's progress table says Proved for each outcome. From that exact commit run the fast check under the floor toolchain -pair and the release check once; retain the run identities on an evidence -page; ask an independent reviewer to read the candidate; then present the -packet to the maintainer. The maintainer closes it; the register moves to -`Closed`, and the plan records the closing decision and the candidate. Use -the `close-milestone` skill. +pair and the release check once; ask an independent reviewer to read the +candidate; then present the packet to the maintainer. The maintainer closes +it; the register moves to `Closed`, the plan records the closing decision and +both SHAs, and the run identities are written to the milestone's evidence page +— by that closing commit, since the runs are of the candidate and the +candidate cannot carry runs of itself. Use the `close-milestone` skill. **Closure names two commits, because one cannot name itself.** The checks and the review are of a **tested implementation commit**; recording the closure is diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 1c89e7c49..c995579d9 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -3769,8 +3769,8 @@ information lost on the way. two store ones.** Store loss is the instance worth reading first because it is the one where the thing the daemon would otherwise stop is already gone; the other **ten** differ only in which component is missing by the time the owner -runs them. **Twelve classes reach this path**, one per linked component of the -fixed set: the two store classes, and `transfers_lost`, +runs them. **Twelve classes reach this path** — one per linked component of +the fixed set, eleven of them, with the Store carrying two: the two store classes, and `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `runtime_lost`, `relay_lost`, `connections_lost` and `listener_lost` — eleven in a From 2fcc9ab14a0c98754ca3b296f3bb0d804ca9007c Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:58:37 -0700 Subject: [PATCH 182/585] plan(M5): the row cannot name its own commit, nor the reader its holder MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two impossibilities, both mine, both one level below the one they replaced. The two-SHA rule was adopted because a commit cannot carry runs of itself. I then told the same commit to write a Closure row naming both SHAs -- including its own, which is that row's content. The Closure row names the TESTED implementation SHA and the digests, as M3's and M4's rows already do; the administrative SHA is LOCATED, by the register's `Closed` transition and by the tag that names it, and never written into the row it is the content of. The guide, AGENTS.md, the skill, the register capsule and its pinned test say the same thing, and the status test is green. `Control`'s per-holder attachment state was "keyed by the holder pid" -- and its one reader has no holder pid. `handle_call({:route_command, …}, _from, state)` discards `_from` at control.ex:336 and resolves by the handle at :343, and under a daemon that caller is a relay task rather than the connection that holds the attachment. A pid key would find nothing there. The contract is now stated as what each operation keys on: the pid owns the entry and its `DOWN` releases it, the `attachment_id` on the handle resolves it at the command path, and repetition is per holder entry. Which index an implementation keeps is left to it; at most 64 holders per session, so a scan is bounded either way. Beside them: the tag rule survived in two more carriers (M5's purpose and the verification companion's stage row, which also had no Release costs at all); the core-witness table had five rows for six changes, one of the five being half of change 4 and two changes carrying no core row -- six rows now, one per change, with core witnesses named for the detailed create/resume results and for the bounded listing; and `SessionDirectory.list_sessions/1` was cited from its @spec rather than its head. The provider module count gets a list instead of a fourth correction. ADR 0034's technical companion names the thirteen serial modules, marks the two that are serial for reasons the credential plane does not touch, and records the executed derivation -- 179 excluded, 164 from the non-recursive glob, the difference of 15 being `test/support/provider_entry_test.exs`. Every other carrier cites that list. A `test/*.exs` glob reports twelve and is wrong every time; that is what the three corrections have in common. --- .agents/skills/close-milestone/SKILL.md | 8 +-- AGENTS.md | 9 ++-- apps/loopex/lib/mix/tasks/status/register.ex | 4 +- apps/loopex/test/status_check_test.exs | 4 +- ...tachment-residency-and-replay-technical.md | 46 +++++++++++++---- ...andoff-over-bootstrap-channel-technical.md | 44 +++++++++++++++-- ...edential-handoff-over-bootstrap-channel.md | 12 ++--- docs/developer/milestones-technical.md | 20 +++++--- docs/developer/milestones.md | 3 +- docs/developer/verification-technical.md | 11 +++-- docs/plans/M5-technical.md | 33 ++++++++----- docs/plans/M5.md | 49 ++++++++++--------- 12 files changed, 167 insertions(+), 76 deletions(-) diff --git a/.agents/skills/close-milestone/SKILL.md b/.agents/skills/close-milestone/SKILL.md index 9be08c58b..8063b2332 100644 --- a/.agents/skills/close-milestone/SKILL.md +++ b/.agents/skills/close-milestone/SKILL.md @@ -33,8 +33,10 @@ technical guidance. The process is the results, review findings, and what remains. The maintainer closes it; then make the **administrative closure commit**, which is [confined to four paths](../../../docs/developer/milestones-technical.md#technical-milestones-confinement): - the register row moved to `Closed`, the plan's Closure row naming **both** - the tested implementation SHA and this commit, the context-map disposition, - and the evidence page with step 3's runs. Nothing else belongs in it. + the register row moved to `Closed`, the plan's Closure row naming the + **tested implementation SHA** and the content digests — not this commit, + which cannot contain its own hash and is located by the register transition + instead — the context-map disposition, and the evidence page with step 3's + runs. Nothing else belongs in it. Tags, packages, and publication are separate maintainer decisions. diff --git a/AGENTS.md b/AGENTS.md index 77be0ffc5..39e9306ac 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -171,9 +171,12 @@ A milestone runs in four steps; the reads the candidate; the maintainer closes it and the register moves to `Closed`. Closure names **two commits**: the *tested implementation SHA* the matrix ran on and the reviewer read, and the *administrative closure - SHA* that records the decision. One commit cannot name itself, and the runs - are of the first, so the second is what writes them down. It is confined to - four paths — register row, Closure row, context-map entry, evidence page — + SHA* that records the decision. One commit cannot name itself: the runs are + of the first, so the second writes them down, and the Closure row names the + first, because that row is the second's own content. The administrative SHA + is located by the register's `Closed` transition and by the tag. It is + confined to four paths — register row, Closure row, context-map entry, + evidence page — which the [milestone guide](docs/developer/milestones-technical.md#technical-milestones-confinement) states once. Run evidence is immutable — held where it cannot diff --git a/apps/loopex/lib/mix/tasks/status/register.ex b/apps/loopex/lib/mix/tasks/status/register.ex index 04e8cc581..609b1bf78 100644 --- a/apps/loopex/lib/mix/tasks/status/register.ex +++ b/apps/loopex/lib/mix/tasks/status/register.ex @@ -793,8 +793,8 @@ defmodule Loopex.Checks.Register do ) |> Map.put( "Next transition", - "Record the closure governance row, naming both the tested implementation SHA and " <> - "the administrative closure SHA, and move `#{name}` to Closed" + "Record the closure governance row, naming the tested implementation SHA, and move " <> + "`#{name}` to Closed" ) end diff --git a/apps/loopex/test/status_check_test.exs b/apps/loopex/test/status_check_test.exs index f40f66991..60d33a47e 100644 --- a/apps/loopex/test/status_check_test.exs +++ b/apps/loopex/test/status_check_test.exs @@ -1564,8 +1564,8 @@ defmodule Loopex.StatusCheckTest do "Next maintainer decision" => "Close `#{name}` or reject its closure candidate on the review findings", "Next transition" => - "Record the closure governance row, naming both the tested implementation " <> - "SHA and the administrative closure SHA, and move `#{name}` to Closed" + "Record the closure governance row, naming the tested implementation SHA, " <> + "and move `#{name}` to Closed" } "Closed" -> diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index d4ae39e36..d7af48497 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -185,14 +185,40 @@ overwrites the controller's slot, and the controller's **next command** fails — the daemon's central case, failing on the component nobody had looked at. **Core change 1 therefore includes `Control`'s attachment and repetition -state, keyed by a stable holder identity.** That identity is the **holder -pid** — the connection process the dispatcher already monitors for the release -half of this change — so the two components key on the same thing and a -`DOWN` drops the entry in both. `Control` keeps one attachment *per holder* -per session rather than one per session, validates a command against the -holder's own attachment, and keeps repetition state per holder. Nothing about -the single-attachment-per-connection rule changes: one holder still has one -attachment, which is why the key is the holder and not the attachment id. +state, held per holder rather than per session.** The **holder pid** — the +connection process the dispatcher already monitors for the release half of +this change — is what the entry belongs to, so the two components agree about +whose attachment is whose and one `DOWN` drops the entry in both. `Control` +keeps one attachment *per holder* per session rather than one per session, and +keeps repetition state per holder entry. Nothing about the +single-attachment-per-connection rule changes: one holder still has one +attachment. + +**But the holder pid cannot be the only key, because the reader has no holder +pid**, and an earlier revision said "keyed by the holder pid" without checking +that. The one reader is the command path: `handle_call({:route_command, token, +session_id, attachment_id, incarnation_id}, _from, state)` **discards `_from`** +(`control.ex:336`) and resolves the attachment from the handle's +`attachment_id` and `incarnation_id` (`:343`, `current_attachment?/3` at +`:1649-1657`). Under the daemon the caller is not the holder at all — the +holder is the connection process, and the command arrives from a **relay +task** — so a lookup by caller pid would find nothing, and a lookup by `_from` +would find the wrong entry. + +So the entries are **reachable both ways**, which is one change and not two: + +| Operation | Key | Why | +| --- | --- | --- | +| Insert, on a successful attach | Holder pid | It is what the attachment belongs to and what a `DOWN` will name | +| Release, on the holder's `DOWN` | Holder pid | The `DOWN` carries the pid and nothing else | +| Validate a command (`:343`) | **`attachment_id`** from the handle | The caller is a relay task; the handle is the only thing that identifies which attachment is speaking | +| Repetition (`attachment_repetition/4`, `:1312-1314`) | The holder entry the command resolved to | Repetition is per attachment, and the command has already found it | + +An implementation may keep a second index from `attachment_id` to holder pid, +or keep the id on the pid-keyed entry and resolve by scanning the session's +holders — at most 64 per session by the ceiling below, so either is bounded. +What is fixed here is the contract, not the data structure: **the id resolves +the entry, the pid owns it, and the `DOWN` releases it.** Its witness is the case that fails today: a controller attaches, an observer attaches to the same session, and **both remain usable** — the controller's @@ -1194,7 +1220,9 @@ make. **Enforcing it needs a bounded read, and core does not have one.** The listing the daemon builds its index from is core's: `Loopex.list_sessions/1` (`loopex.ex:452-453`) calls - `SessionDirectory.list_sessions/1` (`session_directory.ex:230-253`), which + `SessionDirectory.list_sessions/1` (`session_directory.ex:231-266`: the head +at `:231`, the full read and sort at `:238-247`, the answer at `:249`, and the +invalid-root clause at `:266`), which does `File.ls` and then reads **every** entry before sorting and returning. A root holding a hundred thousand entries is therefore read in full before the daemon can refuse at the four-thousand-and-ninety-seventh — a refusal diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 49916617b..62c655323 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -1007,10 +1007,46 @@ seeds, exactly as the M4 speed work converted the other twenty-one modules. The result is recorded against the baseline in the [verification companion](../developer/verification-technical.md#technical-verification-speed): that application was the fast check's critical path at M4 closure, with 96% of -its time in those thirteen modules -- eleven of which reference the credential -variable, the count measured by loading them rather than by globbing -`test/*.exs`. Any module that stays serial keeps its -reason recorded beside it. The measurement is evidence about the change, never +its time in those thirteen modules. Any module that stays serial keeps its +reason recorded beside it. + + +**The thirteen, by name, because the count has been wrong three times.** Every +one of those corrections came from reading a glob instead of running the +suite, so the list is written out once here and every other passage in this +repository cites it rather than recounting. + +| # | Module | Serial because | +| --- | --- | --- | +| 1 | `test/adapter_test.exs` | credential variable | +| 2 | `test/credential_plane_test.exs` | credential variable | +| 3 | `test/m0_child_environment_conformance_test.exs` | **not the credential variable** — it writes a process-wide environment sentinel of its own (`LOOPEX_M0_CHILDENV_PARENT_ONLY`) and mutates `PATH` | +| 4 | `test/provider_attempt_adapter_contract_test.exs` | credential variable | +| 5 | `test/provider_backpressure_observer_test.exs` | credential variable | +| 6 | `test/provider_backpressure_test.exs` | credential variable | +| 7 | `test/provider_bridge_test.exs` | credential variable | +| 8 | `test/provider_build_test.exs` | **not the credential variable** — it builds a shared artifact (the provider build identity `.beam`) against the application's own `mix.exs` | +| 9 | `test/provider_retainer_boundaries_test.exs` | credential variable | +| 10 | `test/provider_startup_boundaries_test.exs` | credential variable | +| 11 | `test/provider_test.exs` | credential variable | +| 12 | `test/real_model_lane_test.exs` | credential variable | +| 13 | `test/support/provider_entry_test.exs` | credential variable — and the module the count kept losing, for living under `test/support/` | + +**Eleven** reference the credential variable, directly or through +`Adapter.credential_variable()`; **two** do not and would stay serial whatever +this decision does. Removing the process-wide read therefore frees eleven, not +thirteen. + +**The derivation is executed, not globbed**, which is what row 13 costs when +it is skipped. `apps/loopex_llm_reqllm` sets no `test_paths`, no +`test_pattern` and no `elixirc_paths`, so Mix's default pattern applies +**recursively** under `test/`, and its `test_ignore_filters` name three +non-`_test` fixture and diagnostic files and nothing else +(`apps/loopex_llm_reqllm/mix.exs:16-22`). Measured in that application: +`mix test --only ` reports **179 excluded**; the twelve +`test/*_test.exs` files alone report **164**; the difference of **15** is +exactly what `mix test test/support/provider_entry_test.exs` runs. A +non-recursive `test/*.exs` glob reports twelve and is wrong every time. The measurement is evidence about the change, never a condition a test may be weakened to meet. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index 999adc77e..e5ced7f28 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -33,12 +33,12 @@ authority the runtime refuses everywhere else. And it forces serialisation: **eleven of the thirteen** heavy `loopex_llm_reqllm` test modules install their own canary in that slot, so two of *those* running at once would hand each other's canary to each other's child. The other two of the thirteen are -serial for reasons of their own, which this decision does not touch: one -writes a process-wide environment sentinel of its own -(`m0_child_environment_conformance_test.exs`) and one builds a shared artifact -(`provider_build_test.exs`). An earlier revision of this sentence said all -thirteen install a canary, which is the serial count rather than the sharing -one, and made this decision look like it frees two modules it does not. The +serial for reasons of their own, which this decision does not touch. The +thirteen are listed by name, with the two marked and the derivation executed +rather than globbed, in the +[technical companion](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-serial-modules); +every passage that states this count cites that list rather than recounting, +because recounting has been wrong three times. The [verification companion](../developer/verification-technical.md#technical-verification-speed) measured the result at M4 closure — that application is the critical path of the fast check, 96% of its time sits in those thirteen modules, and no further diff --git a/docs/developer/milestones-technical.md b/docs/developer/milestones-technical.md index e95b658d0..dccaaa1c9 100644 --- a/docs/developer/milestones-technical.md +++ b/docs/developer/milestones-technical.md @@ -113,11 +113,19 @@ At the **tested implementation commit**, which is the closure candidate: | What names it | Every run on the evidence page, and the review | The register, once `Closed` | | Its evidence | The runs of step 3, taken from it | None of its own; it is a record, not a claim | -The plan's **Closure row carries both**: the tested implementation SHA the -packet was assembled from, and the administrative SHA that closed it. A -reviewer checking the milestone reads the first; a reader tracing the decision -reads the second. Recording only one leaves either the evidence or the -decision unlocatable. +The plan's **Closure row names the tested implementation SHA** — the candidate +the packet was assembled from — with the content digests closure rows have +always carried. It does **not** name the administrative SHA, for the reason +the whole split exists: that row *is* the administrative commit's content, and +a commit cannot contain its own hash. An earlier revision asked the row to +name both, which is the same impossibility as asking one commit to carry runs +of itself, one level down. + +**The administrative SHA is located rather than written.** Two things point at +it and neither is inside it: the register's transition to `Closed`, whose +commit is that commit, and — once a release happens — the annotated tag, which +names it. A reader tracing the decision follows either; a reviewer checking +the evidence reads the tested SHA out of the Closure row, where it is. **The confinement, stated once and referenced everywhere else.** The @@ -126,7 +134,7 @@ administrative closure commit touches **exactly these four paths**: | Path | What it carries | | --- | --- | | `docs/plans/README.md` | The register row, moved to `Closed` | -| `docs/plans/.md` | The plan's Closure row, naming both SHAs | +| `docs/plans/.md` | The plan's Closure row, naming the tested implementation SHA and the content digests | | `docs/developer/agent-context-map.md` | The maintainer's closure disposition | | `docs/evidence/-closure-runs.md` | The run identities, results and measured durations of step 3, the archive manifest's digest, and the security review | diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index c97367ea8..4366c147f 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -60,7 +60,8 @@ outcome. From that exact commit run the fast check under the floor toolchain pair and the release check once; ask an independent reviewer to read the candidate; then present the packet to the maintainer. The maintainer closes it; the register moves to `Closed`, the plan records the closing decision and -both SHAs, and the run identities are written to the milestone's evidence page +the tested implementation SHA, and the run identities are written to the +milestone's evidence page — by that closing commit, since the runs are of the candidate and the candidate cannot carry runs of itself. Use the `close-milestone` skill. diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index fbd5d0017..21faf69f2 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -21,7 +21,7 @@ Concept: [Three stages](verification.md#concept-verification-stages). | Change, while editing | `mix test `, `mix format`, `mix compile --warnings-as-errors`; the client Stop hook runs format, the dependency budget and the adapter check | Seconds | | Change, before merge | `bash scripts/check.sh --select` in hosted CI on the branch; a read-only review of `git diff main..` | 12 min 54 s and 12 min 38 s on the hosted runner at the final M4 candidates; on the Mac 287 s at the final candidate `d738ec7` with a warm build and ten applications at once (346 s at `031554c`, before the bound and concurrency work), against 870 s Mac and 809 s Linux in the sequential shape it replaced; 18 s before the suite starts | | Close | `bash scripts/check.sh` under the floor pair (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`), `bash scripts/check-release.sh` once on the current pair | Release check: 149–163 s on Linux, 12 tests | -| Release | None new; the tag names the integrated closure commit | — | +| Release | The administrative commit's diff confined to its four paths; `check.sh --docs` on the tagged SHA; the archive manifest recomputed there and matched outside `docs/` | Seconds: a documentation-scoped check and a manifest comparison, no suite and no release check | `check.sh` step order and cost: warning-free compilation 1 s (warm), formatting 1 s, repository structure 11–14 s (`scripts/check-bootstrap.sh`: client @@ -126,9 +126,9 @@ applications only; the six light ones (62 s in sequence, 25 serial modules) were not read and are not claimed here. In the four examined, each module still serial carries one of: the one provider credential variable written into this VM's environment so the child inherits it (eleven of the -thirteen heavy `loopex_llm_reqllm` modules; the other two of the thirteen -carry a different one of these reasons each — a process-wide environment -sentinel of their own, and a shared build artifact — plus +thirteen heavy `loopex_llm_reqllm` modules, listed by name in +[ADR 0034's technical companion](../adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-serial-modules), +where the other two are marked with the different reason each carries — plus `cli`, `session_directory`, `coding_tools`, `executor`, `host_policy`); a global `:erlang.trace_pattern` (`cancellation`, `cancellation_observation_contract`, `context_admission`, `skill_context`, @@ -226,7 +226,8 @@ of its 209 s sits in the **thirteen** modules that run serially — **eleven** of which share the process-wide credential variable, so two of those running at once would hand each other's canary to each other's child, while the remaining two are serial on their own reasons and would stay serial either -way. Making those concurrent means passing the +way. The thirteen are named, and the split derived by execution, in +[ADR 0034's technical companion](../adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-serial-modules). Making those concurrent means passing the credential to the child per invocation instead of through the environment, which is a change to the credential plane and a maintainer decision, not a suite change; until then `loopex_llm_reqllm` pins the check near 210 s. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index c995579d9..a55abf4f4 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -47,7 +47,7 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes, with `Control`'s own attachment and repetition state scoped by the same holder pid**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from — a transient, core-internal drain context carrying the Store handle `Control` holds beside each entry's status, coordinator pid and owner, because `%Loopex.Runtime{}` carries a supervisor and a token and no store**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes, with `Control`'s own attachment and repetition state held per holder rather than per session — the holder pid owning the entry and releasing it on `DOWN`, the handle's `attachment_id` resolving it at the command path, which discards its caller because under the daemon that caller is a relay task and not the holder**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from — a transient, core-internal drain context carrying the Store handle `Control` holds beside each entry's status, coordinator pid and owner, because `%Loopex.Runtime{}` carries a supervisor and a token and no store**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | | `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | | `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | | `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | @@ -328,10 +328,13 @@ deliberately, and the derived checklist in Outcome 5's evidence row is what makes that auditable rather than asserted. -**Every core change has a core witness, named here to file, case and lane.** -Three of the five were witnessed only downstream — in the daemon's lifetime -suite and the adapter's credential suite — and three of their properties -cannot be reached from there at all: quiesce's `absent` branch needs a +**Every core change has a core witness, named here to file, case and lane — +six changes, six rows**, matching the surfaces table below one for one. An +earlier revision had five rows for six changes, with one of the five being +half of change 4 and two changes carrying no core row at all. + +A downstream witness is not a substitute, and three properties say why: +quiesce's `absent` branch needs a `Control` entry whose coordinator has already died (`control.ex:821-823`), `exclude_self/2`'s two fail-closed paths need the tracer mid-restart and `Control` mid-restart, and `Control` pruning an excluded sender needs that sender's `DOWN`. All three are @@ -339,11 +342,12 @@ core-internal states a daemon cannot construct through the socket. | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | -| Read-only existence query | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1`** | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split`; `the status census is bounded by one deadline, not one per session` — five hundred and twelve enumerated sessions whose coordinators never answer, asserted to be reported `unsettled` within one census deadline rather than within five hundred and twelve of them; `the enumeration carries the store handle the fence commits through`, asserted by a drain that fences with no store handle of its own | fast | -| **The two-phase abort-path split** | **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) | `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | -| **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | +| Concurrent attachment (core change 1) | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | +| Read-only existence query (core change 2) | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | +| **`quiesce/1` and the coordinator change it needs** (core change 4) | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) for the drain, and **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) for the coordinator half | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split`; `the status census is bounded by one deadline, not one per session` — five hundred and twelve enumerated sessions whose coordinators never answer, asserted to be reported `unsettled` within one census deadline rather than within five hundred and twelve of them; `the enumeration carries the store handle the fence commits through`, asserted by a drain that fences with no store handle of its own; and, in `cancellation_test.exs`, the coordinator half: `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | +| **`create_session_detailed/3` and `resume_session_detailed/3`** (core change 5) | **`apps/loopex/test/session_detailed_results_test.exs`** (new) | `a fresh create answers disposition created`; `a replayed create with the original command_id answers disposition replayed and starts no coordinator`; `a resume of a dormant session answers control_entry dormant`; `a resume of an already-active session answers control_entry active`; `create_session/3's own return is byte-identical to the released shape` — the case that makes the addition provably additive rather than a facade change; `resume_session/3's own return is byte-identical too` | fast | +| **`Loopex.list_sessions/2`** (core change 6) | **`apps/loopex/test/session_listing_test.exs`** (new) | `a bounded listing stops after the bound-plus-first valid entry`; `it reports that it stopped early`; `a root within the bound reports that it did not`; `the arity-one form is unchanged over the same root` — the pair that proves the addition is additive; `a bounded listing over a root past the bound reads fewer entries than the root holds`, asserted by counting the directory reads the call makes rather than by timing it | fast | +| **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** (core change 3) | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | The paused-transaction case in `runtime_quiesce_test.exs` pauses the transaction through core's own controllable store, not the shipped adapter: @@ -4690,9 +4694,12 @@ an attachment *unconditionally*, becoming conditional on ADR 0023's existing `replace` flag and scoped to the attaching process's own prior attachment, and the dispatcher monitors the attaching process, keeps that monitor and the attacher pid **on the installed attachment**, and removes -on its `DOWN`, releasing that attachment's transfers, and `Control` scopes -its own attachment and repetition state by that holder pid rather than -keeping one slot per session — because the first half +on its `DOWN`, releasing that attachment's transfers, and `Control` holds +its own attachment and repetition state **per holder** rather than +keeping one slot per session — owned by the holder pid, released by its +`DOWN`, and resolved at the command path by the `attachment_id` the handle +carries, because that path discards its caller (`control.ex:336`) and under a +daemon the caller is a relay task rather than the holder — because the first half alone would leave core with no release path at all, supersession being the only one there is today, and would leave the only caller of `release_transfers/2` with no replacement, which accepted diff --git a/docs/plans/M5.md b/docs/plans/M5.md index 691788871..aa84292c5 100644 --- a/docs/plans/M5.md +++ b/docs/plans/M5.md @@ -22,8 +22,8 @@ fresh extraction of the exact closure candidate an operator follows the documented setup, starts the daemon, and drives one session from two real client processes with their own inputs; a release-ready source archive of that candidate extracts, compiles and carries that same workflow. The release -itself — one annotated `v0.2.0` tag on the integrated closure commit — is the -maintainer's separate decision after closure, as the +itself — one annotated `v0.2.0` tag on the **administrative closure commit** — +is the maintainer's separate decision after closure, as the [milestone guide](../developer/milestones.md#concept-milestones-release) sets out. It is not a closure condition, because closure cannot wait on a tag that closure authorizes. @@ -38,17 +38,14 @@ their own reasons. Thirteen rather than twelve, and the difference is one file whose membership was settled by running it rather than by reading a glob: -`apps/loopex_llm_reqllm/test/support/provider_entry_test.exs`. It sits under -`test/support/`, which invites the assumption that it is a helper. It is not. -That application sets no `test_paths`, no `test_pattern` and no -`elixirc_paths`, so Mix's defaults apply and the default pattern is matched -**recursively** under `test/`; its `test_ignore_filters` name three -non-`_test` fixture and diagnostic files and nothing else -(`apps/loopex_llm_reqllm/mix.exs:16-22`). Measured: in that application -`mix test --only ` reports **179 excluded**, the twelve -`test/*_test.exs` files alone report **164**, and the difference of **15** is -exactly what `mix test test/support/provider_entry_test.exs` runs. An -ordinary `mix test` loads it. M5 moves that handoff onto the private per-invocation +`apps/loopex_llm_reqllm/test/support/provider_entry_test.exs`, which sits +under `test/support/` and is loaded by an ordinary `mix test` all the same. +The thirteen are listed by name, the two credential-independent ones marked, +and the executed derivation — 179 excluded, 164 from the non-recursive glob, +the difference of 15 being that one file — recorded once in +[ADR 0034's technical companion](../adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-serial-modules), +which this and every other carrier cites rather than recounting. M5 moves that +handoff onto the private per-invocation channel the launcher already opens. M5 answers the vision's durable-service question and carries the roadmap's @@ -58,8 +55,10 @@ the core. Core gains exactly six narrow things: support for several independent attachments to one session — which is three parts of one change, since it stops same-session supersession from removing an attachment and therefore has to add what removes one instead, a monitor on the attaching -process that releases its attachment when that process ends, and has to scope -`Control`'s own attachment and repetition state by that same holder pid, +process that releases its attachment when that process ends, and has to hold +`Control`'s own attachment and repetition state **per holder** — owned by that +same pid and released by the same `DOWN`, but resolved at the command path by +the attachment handle, since that path never sees the holder — `Control` being single-attachment per session today and therefore the component that would otherwise fail a controller's next command when an observer attached; one read-only @@ -94,7 +93,7 @@ second loop and no new durable command. | 1 | A daemon owns session lifetime for a state root, and an operator can run it: readiness is announced only once the marker is held and the socket is bound and permission-checked, `SIGTERM` — or a terminal `SIGINT` the launcher forwards as `SIGTERM` — begins an orderly shutdown that **closes admissions with one synchronous, acknowledged cut** before anything else — the relay closing admissions and **answering at once**, the tickets already inside core then awaited for a bound the implementation measures, after which **the stop proceeds** — so a request of any kind arriving after the cut is refused `daemon_stopping` with nothing admitted, and a ticket still running at the bound leaves its session classified and fenced rather than waited on — then **drains admitted work within a budget derived from core's own cancellation bounds** through `quiesce/1` — which durably admits, for every active session before cancelling anything, the same abort command a client's own `session.abort` writes — no new record, no new field, so a drained root is still a root the released surface opens — drives each session's in-flight work through the cancellation sequence that already exists under that session's own grace, and at the deadline **terminates every coordinator it enumerated — the settled as well as the unsettled — waiting for every one of them to be gone, and only then fences every one of those sessions**, in that order, so no fence races a live writer — so that work which settles carries its ordinary terminal facts in the journal and work which does not is left **claiming no terminal outcome**, its ambiguous mutation fenced as `commit_unknown` for the reconciliation that already exists; then one stop record attempted per client, every connection closed, the listener closed with the socket **pathname left in place** — no exit path unlinks, and the next daemon to prove it holds the marker removes it before binding — the runtime and the edges torn down, the Store stopped last and exit `0` — a client learns the reason from that record where the write succeeds and from the close where it does not; a fatal exit runs a fail-stop instead — no drain, the executor stopped, the Store stopped on every class where it is still alive, and a named reason class on `stderr` with a non-zero exit. An activated session's work runs to completion with every client detached, including across the idle deadline, because dormancy releases attachments and never a coordinator, an orderly stop and an abrupt death both leave only what the journal proves, a restarted daemon can activate every session the root records and names the ones it cannot, a second daemon on the same root loses at the store writer marker before touching the socket, a stale marker left by a dead daemon is recovered only where the marker's own holder is proved dead, losing the store closes the socket and every connection, reaching the local log's capacity is one such loss and the daemon says so as it closes, sessions are listed in bounded pages from a daemon index that claims only what it can keep true and says `index_full` when it cannot record more, a session the Store holds but the directory does not is still reached by ID, validated by core's read-only existence query without attaching or resuming, and reached by its create `command_id` when the client never saw the ID, and the 65th activation in one daemon lifetime refuses with the restart remedy — refused by a slot reserved **before** the call, since core starts a coordinator inside the call that would otherwise report it, so two concurrent activations at 63 yield exactly one coordinator, and after an orderly stop the foreground server and the CLI reopen the same root and sessions under the same placement identity | Process-lifetime and store fault injection on real local processes | `apps/loopex_daemon/test/session_lifetime_test.exs` | | 2 | Independent client processes reach the daemon over a Unix-domain socket with ADR 0023's framing, handshake, and admission, snapshot, event and progress records reused unchanged and its request records reused with the one added `writer_epoch` field, generation 2 negotiated under its own exact schema digest while generation 1's method inventory, record families, error codes and limits are proved unchanged and its one affected pin — the schema digest — re-pinned for the generation rename while the two manifest file digests stay, since those manifests already carry the new name, a client sending the old generation string refused `unsupported_generation`, the same durable identities as the facade and the foreground server, owner-only peer access and the same framing refusals | Protocol vectors and compatibility: differential conformance across facade, foreground server and socket, plus negative transport and independent-client tests | `apps/loopex_daemon/test/socket_transport_test.exs`, the generation-2 vectors in `apps/loopex_protocol/test/public_schema_conformance_test.exs` | | 3 | One controller drives while observers watch: the daemon validates durable session existence through core's read-only query before it grants a lease, so an unknown ID refuses with nothing created and nothing attached, and it checks connection ownership, held and unexpired lease state, and the current writer epoch before mutation; takeover after release or expiry mints a fresh epoch, a mutation already in flight at expiry settles under its own lease while the eligible takeover waits for it, a killed controller is fenced, a lease owner killed with a mutation in flight loses only that session's collaboration state — its controller closed with `control_owner_lost`, its observers kept, and the replacement's first grant waiting on the admission relay's retained ticket rather than the daemon going down or forgetting what a takeover waits on, a daemon restart leaves every session uncontrolled with every earlier epoch stale, and the current controller's abort cancels work dispatched under an earlier process with a truthful outcome | Negative tests for trust, on real killed processes, with the admission path read in review | `apps/loopex_daemon/test/collaboration_test.exs` | -| 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | +| 4 | Several core attachments coexist without replacement, and daemon attach, replay, residency and backpressure are race-free and bounded: core is the only replay owner and the daemon's resident window is a droppable cache that establishes no snapshot and no cursor, snapshot then contiguous at-least-once stream with no gap, slow-attachment detachment at the last emitted cursor, idle eviction with contiguous at-least-once reconnect and no gap, retained encoded-event bytes within the daemon-owned bounds reclaimed in a deterministic order, and progress that never delays a journal transaction | Delivery, residency and retained-byte-bound tests with observed process RSS, and a core witness per core change | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/runtime_quiesce_test.exs`, `apps/loopex/test/cancellation_test.exs`, `apps/loopex/test/trace_session_test.exs`, `apps/loopex/test/session_detailed_results_test.exs`, `apps/loopex/test/session_listing_test.exs`, `apps/loopex_daemon/test/replay_residency_test.exs` | | 5 | From a clean source extraction and operator-supplied inputs, two real client processes — the reference CLI and the independent Node client — drive one daemon-owned session through controller work, observer following, controller kill and takeover, with the daemon's workflows driving the accepted core telemetry spans end to end, and daemon internals proved by the daemon's own tests and logs rather than by new events or by a trace session ADR 0030's process scope does not reach; the operator and developer documentation states what M5 changed for its reader; and a release-ready `0.2.0` source archive of the exact candidate extracts, builds the reference CLI and its provider companion from an archive-carried, integrity-checked source identity rather than from `.git`, and carries that workflow | Real-provider demonstration, fresh-source proof and an operator setup smoke from the extracted tree, retained on the closure evidence page | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, the attended demonstration in `docs/evidence/M5-closure-runs.md` | | 6 | The provider adapter hands each provider child its credential per invocation over that child's private channel instead of resolving a process-wide environment variable inside the call, so no provider child can receive another invocation's credential and, from the moment a host has composed the runtime, the parent VM's environment carries no credential; the credential is named by an opaque token bound at composition, whose **resolution** is what happens per invocation, the host owns a routing registry that maps it to a custody process and holds routing only, the guardian enforces the resolution deadline, losing custody or the registry answers `:unavailable` and reconstructs nothing, and every refusal in that contract is proved; every existing credential-plane negative proof holds against the new handoff; the adapter's library tree is proved to read no environment variable **for a credential** by any route such a read can be written, with `provider_bridge` reading none at all; and the launcher keeps its launch-time enumeration, which is ADR 0019's first-image scrubbing and not part of the credential plane, with the proof showing that read is never consulted for a credential. The adapter's `req_llm` dependency moves to `~> 1.24.0` in the same workstream, as explicit M5 scope separate from ADR 0035, adding no M5 call path and carrying its own dependency review. The eleven provider test modules that serialise on that one variable today then become eligible to run concurrently; each is converted one at a time and kept only while its application's suite stays green, and a module that stays serial for another reason keeps that reason recorded beside it. The resulting measurement is evidence about the change, recorded beside the M4-closure baseline, not a threshold a test may be weakened to meet | Negative tests for trust, a recorded security review, and the real-provider lane in the release check | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, ADR 0034's host-owned-process cases at `apps/loopex_cli/test/`, `apps/loopex_app_server/test/` and `apps/loopex_daemon/test/`, the security review recorded in `docs/evidence/M5-closure-runs.md` | @@ -764,9 +763,11 @@ candidate; the maintainer closes it. M5 closes on the two SHAs the [milestone guide](../developer/milestones.md#concept-milestones-close) now -fixes, and its Closure row carries both: the **tested implementation SHA** -every run above names and the reviewer read, and the **administrative closure -SHA** that records the decision and is confined to +fixes: the **tested implementation SHA** every run above names and the +reviewer read, which is what this pair's Closure row records, and the +**administrative closure SHA** that carries that row — located by the +register's `Closed` transition and by the `v0.2.0` tag rather than written +into the row it is the content of — and confined to [its four paths](../developer/milestones-technical.md#technical-milestones-confinement): the register row, this pair's Closure row, the context-map entry and `docs/evidence/M5-closure-runs.md`. The closure matrix runs **once**, from the @@ -1121,11 +1122,15 @@ which the dispatcher keeps the attacher's pid and that monitor's reference **on the installed attachment**, which it records neither of today, and which both need: the `DOWN` handler to find the attachment to drop, and the narrowed replacement to know whose prior attachment it may supersede. And -**`Loopex.Runtime.Control` scopes its own attachment and repetition state by -that same holder pid**, because it is single-attachment too: it keeps one +**`Loopex.Runtime.Control` holds its own attachment and repetition state per +holder**, because it is single-attachment too: it keeps one `attachment` field per session, overwrites it on every attach and validates every command against it, so without this an observer attaching after a -controller makes the controller's next command fail. That is the daemon's +controller makes the controller's next command fail. The holder pid owns that +entry and its `DOWN` releases it, but the entry is **found by the attachment +handle**, not by the caller: the command path discards its caller, and under a +daemon that caller is a relay task rather than the connection that holds the +attachment. That is the daemon's central case, and it failed on the component two reviews of this plan never read. From 930d20ebf7140a249049c75f4bd4bb85901049a6 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 18:59:53 -0700 Subject: [PATCH 183/585] plan(M5): adversarial pass over the six rows and the release row Three findings against this round's own additions. The new core witness for the bounded listing asserted that it "reads fewer entries than the root holds", which is a comparative where the plan's own rule is an exact executed count. It asserts exactly bound-plus-one entry reads, by tracing `Loopex.SessionDirectory` and counting `read_entry`. The two new core witness files were named in the core-witness table and in the Concept's Outcome 4 cell but not in the technical evidence row that is supposed to be the mapping. Added there. The verification companion's Release row was filled in with "Seconds" as its cost, which is a projection dressed as a measurement. It carries the figure this session actually observed for `check.sh --docs` -- 12-13 s on the Mac, warm build -- and says the manifest comparison is the rest. --- docs/developer/verification-technical.md | 2 +- docs/plans/M5-technical.md | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index 21faf69f2..4ab6e3a66 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -21,7 +21,7 @@ Concept: [Three stages](verification.md#concept-verification-stages). | Change, while editing | `mix test `, `mix format`, `mix compile --warnings-as-errors`; the client Stop hook runs format, the dependency budget and the adapter check | Seconds | | Change, before merge | `bash scripts/check.sh --select` in hosted CI on the branch; a read-only review of `git diff main..` | 12 min 54 s and 12 min 38 s on the hosted runner at the final M4 candidates; on the Mac 287 s at the final candidate `d738ec7` with a warm build and ten applications at once (346 s at `031554c`, before the bound and concurrency work), against 870 s Mac and 809 s Linux in the sequential shape it replaced; 18 s before the suite starts | | Close | `bash scripts/check.sh` under the floor pair (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`), `bash scripts/check-release.sh` once on the current pair | Release check: 149–163 s on Linux, 12 tests | -| Release | The administrative commit's diff confined to its four paths; `check.sh --docs` on the tagged SHA; the archive manifest recomputed there and matched outside `docs/` | Seconds: a documentation-scoped check and a manifest comparison, no suite and no release check | +| Release | The administrative commit's diff confined to its four paths; `check.sh --docs` on the tagged SHA; the archive manifest recomputed there and matched outside `docs/` | The documentation-scoped check alone: 12–13 s on the Mac at this revision, warm build, plus a manifest comparison. No suite and no release check | `check.sh` step order and cost: warning-free compilation 1 s (warm), formatting 1 s, repository structure 11–14 s (`scripts/check-bootstrap.sh`: client diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index a55abf4f4..9aff34ee1 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -146,7 +146,7 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its three parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | | 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — eight where artifact transfers are enabled and seven where they are not, and **neither `listener_lost` nor `connections_lost`**, which have no vector for the same reason: the listener is what would have written the record and the connection registry owns the buffer-control interface it would have been written through, so no client ever receives either reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | | 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in arrival order, one at a time**, the second held in its lease owner until the first ticket resolves, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; and the ordering inside the ticket callback asserted on the surface that shows it: at the instant the acknowledgement arrives at the caller, the relay's own state is read in-VM and asserted to hold **both** the ticket row **and** a live task pid for that ticket, and the task is asserted to be monitored rather than linked, so a relay that died next would leave the call running rather than take it down. A relay that replied before spawning passes the first assertion and fails the second, which is the difference the case exists to make. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, **`apps/loopex/test/session_detailed_results_test.exs`**, **`apps/loopex/test/session_listing_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | | 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | | 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted, and it is proved at the **process boundary** rather than inside the body: what the bridge spawns holds no token, no registry handle and no credential — `set_on_spawn` traces a spawned closure's **entry call**, so a token in that closure is exposed before any line of it runs — and it receives the token by message only after its exclusion is established and confirmed. The tracer is asserted to receive **no raw trace message from that process carrying the token at any point**, entry included, while a non-excluded control process spawned with the same closure shape does produce one; `exclude_self/2` returns before the token is sent, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | @@ -346,7 +346,7 @@ core-internal states a daemon cannot construct through the socket. | Read-only existence query (core change 2) | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | | **`quiesce/1` and the coordinator change it needs** (core change 4) | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) for the drain, and **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) for the coordinator half | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split`; `the status census is bounded by one deadline, not one per session` — five hundred and twelve enumerated sessions whose coordinators never answer, asserted to be reported `unsettled` within one census deadline rather than within five hundred and twelve of them; `the enumeration carries the store handle the fence commits through`, asserted by a drain that fences with no store handle of its own; and, in `cancellation_test.exs`, the coordinator half: `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`create_session_detailed/3` and `resume_session_detailed/3`** (core change 5) | **`apps/loopex/test/session_detailed_results_test.exs`** (new) | `a fresh create answers disposition created`; `a replayed create with the original command_id answers disposition replayed and starts no coordinator`; `a resume of a dormant session answers control_entry dormant`; `a resume of an already-active session answers control_entry active`; `create_session/3's own return is byte-identical to the released shape` — the case that makes the addition provably additive rather than a facade change; `resume_session/3's own return is byte-identical too` | fast | -| **`Loopex.list_sessions/2`** (core change 6) | **`apps/loopex/test/session_listing_test.exs`** (new) | `a bounded listing stops after the bound-plus-first valid entry`; `it reports that it stopped early`; `a root within the bound reports that it did not`; `the arity-one form is unchanged over the same root` — the pair that proves the addition is additive; `a bounded listing over a root past the bound reads fewer entries than the root holds`, asserted by counting the directory reads the call makes rather than by timing it | fast | +| **`Loopex.list_sessions/2`** (core change 6) | **`apps/loopex/test/session_listing_test.exs`** (new) | `a bounded listing stops after the bound-plus-first valid entry`; `it reports that it stopped early`; `a root within the bound reports that it did not`; `the arity-one form is unchanged over the same root` — the pair that proves the addition is additive; `a bounded listing over a root past the bound performs exactly bound-plus-one entry reads`, asserted by tracing `Loopex.SessionDirectory` and counting `read_entry` calls over a root seeded with far more, never by timing it | fast | | **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** (core change 3) | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | The paused-transaction case in `runtime_quiesce_test.exs` pauses the From bccbef144dcd6d3d33d83719978b99e60257c638 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 19:06:08 -0700 Subject: [PATCH 184/585] adr(M5): the bounded listing answers in directory order, unsorted The bounded session listing is a new core result, and every other new core result in the set has an exact shape. Its early-stop answer had none: the arity-one form sorts only after reading everything, which is the cost the bound exists to avoid, so the bounded form cannot sort. The clause now says the entries come back in directory order, that the answer is the early-stop flag, and that the daemon reads nothing else. --- ...emon-attachment-residency-and-replay-technical.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index d7af48497..92c20b974 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -1229,10 +1229,14 @@ invalid-root clause at `:266`), which whose point is to avoid exactly that cost. So this milestone adds one further narrow read to core and counts it: **`Loopex.list_sessions/2` taking a bound and stopping after the bound-plus-first valid entry**, - answering what it read and whether it stopped early. It is read-only and - additive — the arity-one form keeps its exact meaning and its callers — and - it is the smallest thing that lets the bound be enforced rather than - discovered. + answering what it read and whether it stopped early. The entries it returns + when it stopped early are in directory order, not a sorted prefix: the + arity-one form sorts only after it has read everything, which is the cost + the bound exists to avoid, so the bounded form cannot sort and does not + claim to. Its answer is the early-stop flag; the daemon reads nothing else + from it. It is read-only and additive — the arity-one form keeps its exact + meaning and its callers — and it is the smallest thing that lets the bound + be enforced rather than discovered. - **Homogeneity.** One state root is one host composition for the daemon's process lifetime. The daemon is composed once, with one workspace, policy, provider configuration and set of project resources, and serves every From be1b8f2d7bad855d93cd08adb920e9c4c8c8c04b Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 19:13:12 -0700 Subject: [PATCH 185/585] plan(M5): the fixed set is eleven links in every sentence Two sentences still headed the start-order table and the link rule with ten processes, nine without transfers, after the connection registry became the eleventh link; the tables and the fail-stop enumeration beside them already said eleven. Both now agree. The archive's exclusion clause counts one rule over two roots rather than one root. --- docs/plans/M5-technical.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 9aff34ee1..953f76360 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -777,7 +777,7 @@ repository: before/after pair is what catches a build that writes into its own source tree. The first manifest is also compared with the inventory the closure evidence recorded, which is what ties the extraction to the commit; -- exactly **one** exclusion, named rather than implied: the build-output roots +- exactly **one** exclusion rule, named rather than implied: the two build-output roots `_build/` and `deps/`, which the build is supposed to create. Nothing else is excluded, and the list of exclusions is part of the retained evidence, so a later exclusion cannot quietly widen what "unchanged" means. @@ -1665,7 +1665,7 @@ So `apps/loopex_daemon` has one top-level process, `Loopex.Daemon.Owner`, a `GenServer` that traps exits and holds the links itself — the same pattern `RuntimeOwner` already uses, for the same reason. -**It links a fixed set of ten processes — nine without artifact +**It links a fixed set of eleven processes — ten without artifact transfers — and a bounded, dynamic population of lease owners beside them.** Earlier drafts said four, then seven, then nine, each time having counted the components the daemon *thinks* about rather than the processes that actually @@ -2042,7 +2042,7 @@ runs no dialyzer, and `RuntimeOwner` itself already destructures the field, at not, and the real argument is the simpler one above. **There is no restart strategy, because there are no restarts.** Every one of -the fixed ten — nine without transfers — is `start_link`ed by the owner, +the fixed eleven — ten without transfers — is `start_link`ed by the owner, as is each lease owner beside them, and the owner's `handle_info({:EXIT, pid, reason}, state)` clause is the failure rule. That clause is also the **reader** the fatal-class map needs — it matches the pid From 2fbda00b7d32e9f2b43a63794e216ae1942aa44c Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 19:21:31 -0700 Subject: [PATCH 186/585] plan(M5): witness the non-holder command, point the register at the rule Four items from the confirmation pass. The one that matters is a witness: Control's attachment entries are owned by the holder pid but resolved by the attachment id, because under the daemon a command arrives from a relay task and not the holder; no listed case sent a command from a non-holder, so a pid-keyed implementation passed the list. That case is named now. The plans register restated the administrative commit's confinement over three paths where the rule names four; it now points at the rule. Two words: the host owns all three of the credential processes, and the listing's malformed arguments refuse with invalid_request by name. --- ...0032-daemon-attachment-residency-and-replay-technical.md | 2 +- docs/plans/M5-technical.md | 6 +++--- docs/plans/README.md | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 92c20b974..6adf35b50 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -1135,7 +1135,7 @@ returned twice, because nothing deletes a row and no two rows share an ID. A client that needs a complete view pages again from the start; deduplication is unnecessary here, though a client that deduplicates by session ID loses nothing. A `limit` outside 1 to 256 or an `after_session_id` that is not -a well-formed session ID refuses with the existing invalid-argument reason; an +a well-formed session ID refuses with ADR 0023's existing `invalid_request`; an `after_session_id` naming an unknown session is admitted and pages from its byte position. diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 953f76360..6114136ac 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -342,7 +342,7 @@ core-internal states a daemon cannot construct through the socket. | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment (core change 1) | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | +| Concurrent attachment (core change 1) | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `a command sent from a process that is not the holder resolves by attachment_id and is admitted` — the case a pid-keyed `Control` fails, and the one that forced the dual key; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | | Read-only existence query (core change 2) | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | | **`quiesce/1` and the coordinator change it needs** (core change 4) | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) for the drain, and **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) for the coordinator half | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split`; `the status census is bounded by one deadline, not one per session` — five hundred and twelve enumerated sessions whose coordinators never answer, asserted to be reported `unsettled` within one census deadline rather than within five hundred and twelve of them; `the enumeration carries the store handle the fence commits through`, asserted by a drain that fences with no store handle of its own; and, in `cancellation_test.exs`, the coordinator half: `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | | **`create_session_detailed/3` and `resume_session_detailed/3`** (core change 5) | **`apps/loopex/test/session_detailed_results_test.exs`** (new) | `a fresh create answers disposition created`; `a replayed create with the original command_id answers disposition replayed and starts no coordinator`; `a resume of a dormant session answers control_entry dormant`; `a resume of an already-active session answers control_entry active`; `create_session/3's own return is byte-identical to the released shape` — the case that makes the addition provably additive rather than a facade change; `resume_session/3's own return is byte-identical too` | fast | @@ -1995,7 +1995,7 @@ and tying one to the other's number would have made the bound wrong the first time an operator took control of a dormant session. **The registry, the custody process and the tracing capability are first, and -that is forced rather than chosen.** ADR 0034 makes the *host* own both, and for a daemon the host +that is forced rather than chosen.** ADR 0034 makes the *host* own all three, and for a daemon the host is the daemon. The runtime's model configuration carries the registry handle and the token in `options`, so both processes must exist before the composition function builds that configuration — which means before the @@ -4070,7 +4070,7 @@ nothing proves. Each is named where it is used: | Surface | Created by | Read by | | --- | --- | --- | -| The dispatcher's release on `DOWN`, the attacher pid and monitor reference it keeps on the attachment to do it, the transfers it releases with it, **and `Control`'s per-holder attachment and repetition state** | Core change 1 | The concurrent-attachment cases, the ADR 0028 transfer case, the scoped-replacement case and the attach connection-loss case | +| The dispatcher's release on `DOWN`, the attacher pid and monitor reference it keeps on the attachment to do it, the transfers it releases with it, **and `Control`'s per-holder attachment and repetition state** | Core change 1 | The concurrent-attachment cases, the ADR 0028 transfer case, the scoped-replacement case, the attach connection-loss case, and the non-holder command case that resolves by `attachment_id` | | The existence query's five-result set | Core change 2 | `session_existence_query_test.exs`, one case per result, and Outcome 4's row | | `Control`'s excluded-pid set, and `Entry`'s redaction of a keyword pair under its own key | Core change 3 | The trace-exclusion cases, and the render pair that must differ | | `quiesce/1`'s three lists, `budget_ms`, `drain_id` and the per-session `fences` map | Core change 4 | The drain cases, the fence cases and the stop line | diff --git a/docs/plans/README.md b/docs/plans/README.md index 71a07f367..0919dbc47 100644 --- a/docs/plans/README.md +++ b/docs/plans/README.md @@ -215,8 +215,8 @@ maintainer or a recorded delegate, durable evidence of that authority's explicit disposition, and the accepted candidate SHA. Moving it to `Closed` requires the same for the reviewed closure candidate. An explicit decision may be recorded; it may not be supplied or inferred. An independent reviewer reads the exact -candidate before either transition, and the transition itself changes only the -governance row, the disposition it names, and the derived status blocks. +candidate before either transition, and the transition itself is confined to +[the four paths the milestone guide names](../developer/milestones-technical.md#technical-milestones-confinement). The sections a plan pair carries, and what each states, are defined once in the [milestone guide](../developer/milestones-technical.md#technical-milestones-agree); From 19df8e8c3a8af845a01a7998023f4c47d93f5b9a Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 20:21:35 -0700 Subject: [PATCH 187/585] docs(M5): correct closure and release evidence --- .agents/skills/close-milestone/SKILL.md | 32 +++++-- AGENTS.md | 29 +++--- apps/loopex/lib/mix/tasks/status/register.ex | 11 +-- apps/loopex/test/status_check_test.exs | 8 +- docs/developer/agent-context-map.md | 28 ++++++ docs/developer/milestones-technical.md | 95 ++++++++++++++------ docs/developer/milestones.md | 67 +++++++------- docs/developer/verification-technical.md | 21 +++-- docs/developer/verification.md | 4 +- 9 files changed, 197 insertions(+), 98 deletions(-) diff --git a/.agents/skills/close-milestone/SKILL.md b/.agents/skills/close-milestone/SKILL.md index 8063b2332..7d57a3688 100644 --- a/.agents/skills/close-milestone/SKILL.md +++ b/.agents/skills/close-milestone/SKILL.md @@ -16,19 +16,25 @@ technical guidance. The process is the retained evidence, or demonstration that proves it. An outcome with no proof is open; say so. 2. Update the documentation the milestone changed: `CHANGELOG.md`, `README.md`, - the affected `docs/` pages and indexes. + the affected `docs/` pages and indexes. Create + `docs/evidence/-closure-runs.md` as an unfilled scaffold with its final + headings and fields, mark its results pending, and index it in + `docs/evidence/README.md`. Both files belong to the tested candidate. 3. From the exact committed candidate — the **tested implementation SHA** — run the closure matrix in the [verification guide](../../../docs/developer/verification.md#concept-verification-stages): `bash scripts/check.sh` under the floor toolchain pair and `bash scripts/check-release.sh` once. The current pair's fast check is the CI run the candidate already produced; count it rather than repeating it. - Retain each run's complete output outside the repository, with its digest, - the tested implementation SHA, platform, and toolchain. It is written to - `docs/evidence/-closure-runs.md` in step 5, not here: the runs are of - the candidate, and the candidate cannot carry runs of itself. + Retain each run's complete output outside the repository, with its stable + retained-output reference, SHA-256 digest, tested implementation SHA, + platform, and toolchain. Step 5 writes those identities, references, and + digests into the existing evidence-page scaffold: the runs are of the + candidate, and the candidate cannot carry its own later results. 4. Ask an independent reviewer to read the candidate for outcome compliance, - correctness, test honesty, public impact, security, and rollback. + correctness, test honesty, public impact, security, and rollback. Retain the + complete review report outside the repository under a retained-output + reference with its SHA-256 digest. 5. Present the packet to the maintainer: outcomes and their proof, check results, review findings, and what remains. The maintainer closes it; then make the **administrative closure commit**, which is @@ -36,7 +42,15 @@ technical guidance. The process is the the register row moved to `Closed`, the plan's Closure row naming the **tested implementation SHA** and the content digests — not this commit, which cannot contain its own hash and is located by the register transition - instead — the context-map disposition, and the evidence page with step 3's - runs. Nothing else belongs in it. + instead — the context-map disposition, and the existing evidence page filled + with step 3's runs and step 4's review. Nothing else belongs in it; in particular, + `docs/evidence/README.md` does not change in the administrative commit. -Tags, packages, and publication are separate maintainer decisions. +Tags, packages, and publication are separate maintainer decisions. If the +maintainer later authorizes a tag, follow the milestone guide's release +sequence. Run the documentation check, the final semantic operator/developer +documentation gate, and the archive comparison on the administrative SHA +before creating the tag. Retain those outputs outside the repository and put +their results, retained-output references, and SHA-256 digests in the +annotation at creation. Do not amend the evidence page or create a third +commit. diff --git a/AGENTS.md b/AGENTS.md index 39e9306ac..04f78ba14 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -163,7 +163,8 @@ A milestone runs in four steps; the the first integrated workflow early, then add boundary and failure cases as implementation reaches them. 3. **Close.** Every outcome maps to tests, retained evidence, or a - demonstration. From the exact candidate run the closure matrix the + demonstration. The exact candidate already carries an indexed evidence-page + scaffold. From that candidate run the closure matrix the [verification guide](docs/developer/verification.md#concept-verification-stages) states once: `bash scripts/check.sh` under the floor toolchain pair and `bash scripts/check-release.sh` once, counting the current-pair CI run the @@ -171,24 +172,30 @@ A milestone runs in four steps; the reads the candidate; the maintainer closes it and the register moves to `Closed`. Closure names **two commits**: the *tested implementation SHA* the matrix ran on and the reviewer read, and the *administrative closure - SHA* that records the decision. One commit cannot name itself: the runs are + SHA* that records the decision as its direct child. One commit cannot name + itself: the runs are of the first, so the second writes them down, and the Closure row names the first, because that row is the second's own content. The administrative SHA is located by the register's `Closed` transition and by the tag. It is confined to four paths — register row, Closure row, context-map entry, - evidence page — + the existing evidence-page scaffold — which the [milestone guide](docs/developer/milestones-technical.md#technical-milestones-confinement) - states once. Run evidence is immutable — held where it cannot - be edited after the packet is read. + states once. Complete run outputs are immutable outside the repository; the + evidence page records each retained-output reference and SHA-256 digest. 4. **Release.** Publication, tags, and packages are separate maintainer decisions that reuse the closure evidence when the source is unchanged. The - tag names the **administrative** closure SHA, whose diff from the tested - SHA is verified to be confined to those four paths — all under `docs/`, so - nothing outside `docs/` moved; on that basis the release - re-proves documentation only — `bash scripts/check.sh --docs` on the tagged - SHA, and a recomputed archive manifest matching the tested SHA's for every - entry outside `docs/` — and re-runs no suite and no release check. + tag names the **administrative** closure SHA. Before creating it, verify that + the diff from the tested SHA is confined to those four paths. Then run + `bash scripts/check.sh --docs`, the final semantic review of the relevant + `docs/operator/` and `docs/developer/` pages, and the archive comparison on + the administrative SHA. Every non-documentation archive entry except + `SOURCE_IDENTITY` matches the tested archive; validate each archive's + `SOURCE_IDENTITY` against its own commit. Retain the complete outputs outside + the repository and put their results, retained-output references and + SHA-256 digests in the immutable annotated tag when it is created. Do not + amend the evidence page or create a third commit. No suite or release check + runs again. Historical milestones keep their plans, evidence logs, and dispositions as records of what was proved at the revisions they name. Current tests belong to diff --git a/apps/loopex/lib/mix/tasks/status/register.ex b/apps/loopex/lib/mix/tasks/status/register.ex index 609b1bf78..b6c5d946f 100644 --- a/apps/loopex/lib/mix/tasks/status/register.ex +++ b/apps/loopex/lib/mix/tasks/status/register.ex @@ -774,9 +774,10 @@ defmodule Loopex.Checks.Register do |> Map.put("Blockers", "None; `#{name}` is in progress against its accepted plan pair") |> Map.put( "Next transition", - "Map every outcome to evidence, run `bash scripts/check.sh` under the floor toolchain " <> - "pair and `bash scripts/check-release.sh` once from the tested implementation SHA, " <> - "then move `#{name}` to In review" + "Create and index `docs/evidence/#{name}-closure-runs.md` as a scaffold, map every " <> + "outcome to evidence, run `bash scripts/check.sh` under the floor toolchain pair " <> + "and `bash scripts/check-release.sh` once from the tested implementation SHA, then " <> + "move `#{name}` to In review" ) end @@ -793,8 +794,8 @@ defmodule Loopex.Checks.Register do ) |> Map.put( "Next transition", - "Record the closure governance row, naming the tested implementation SHA, and move " <> - "`#{name}` to Closed" + "Fill the existing `docs/evidence/#{name}-closure-runs.md` scaffold, record the closure " <> + "governance row naming the tested implementation SHA, and move `#{name}` to Closed" ) end diff --git a/apps/loopex/test/status_check_test.exs b/apps/loopex/test/status_check_test.exs index 60d33a47e..9bd5d5cbb 100644 --- a/apps/loopex/test/status_check_test.exs +++ b/apps/loopex/test/status_check_test.exs @@ -1552,7 +1552,8 @@ defmodule Loopex.StatusCheckTest do accepted | "Blockers" => "None; `#{name}` is in progress against its accepted plan pair", "Next transition" => - "Map every outcome to evidence, run `bash scripts/check.sh` under the floor " <> + "Create and index `docs/evidence/#{name}-closure-runs.md` as a scaffold, map " <> + "every outcome to evidence, run `bash scripts/check.sh` under the floor " <> "toolchain pair and `bash scripts/check-release.sh` once from the tested " <> "implementation SHA, then move `#{name}` to In review" } @@ -1564,8 +1565,9 @@ defmodule Loopex.StatusCheckTest do "Next maintainer decision" => "Close `#{name}` or reject its closure candidate on the review findings", "Next transition" => - "Record the closure governance row, naming the tested implementation SHA, " <> - "and move `#{name}` to Closed" + "Fill the existing `docs/evidence/#{name}-closure-runs.md` scaffold, record " <> + "the closure governance row naming the tested implementation SHA, and move " <> + "`#{name}` to Closed" } "Closed" -> diff --git a/docs/developer/agent-context-map.md b/docs/developer/agent-context-map.md index d326ee8d4..7df74ef96 100644 --- a/docs/developer/agent-context-map.md +++ b/docs/developer/agent-context-map.md @@ -5420,3 +5420,31 @@ together with `apps/loopex/test/status_check_test.exs`, which pins those exact strings and would otherwise be the thing that decides what the guide says. All of it in one change with this entry. It grants no tag, release or publication. + +### Closure and release evidence sequencing — 2026-09-20 + +The maintainer corrected the two-commit closure rule after external review. +The tested implementation commit now contains an indexed, unfilled +`docs/evidence/-closure-runs.md` scaffold. The administrative closure +commit is the tested commit's direct child and fills that existing page, so its +confinement remains exactly four paths and does not require an unlisted index +change. This entry supersedes the prior entry only where that entry said the +administrative commit creates the evidence page. + +Release proofs run on the administrative closure SHA before the tag exists. +They are `bash scripts/check.sh --docs`, the milestone's final semantic review +of the relevant `docs/operator/` and `docs/developer/` pages, and the archive +comparison. The archive comparison requires every non-documentation entry +except `SOURCE_IDENTITY` to match the tested archive. Each archive's +`SOURCE_IDENTITY` is validated against that archive's own commit and source +identity instead of being compared byte for byte. + +Complete closure outputs remain outside the repository; the administrative +commit records their retained-output references and SHA-256 digests on the +evidence page. Complete release proofs also remain outside the repository; +their results, retained-output references, and SHA-256 digests enter the +annotated tag when it is created. The evidence page does not change after the +administrative commit, and the tag does not name evidence produced after tag +creation. The sequence is the tested commit, the administrative commit, and +the tag. It adds no third commit and grants no closure, tag, release, or +publication by itself. diff --git a/docs/developer/milestones-technical.md b/docs/developer/milestones-technical.md index dccaaa1c9..f280b4498 100644 --- a/docs/developer/milestones-technical.md +++ b/docs/developer/milestones-technical.md @@ -81,27 +81,33 @@ At the **tested implementation commit**, which is the closure candidate: evidence or demonstration; an outcome the maintainer deferred says so and cites their decision. 2. Documentation the milestone changed is updated: `CHANGELOG.md`, `README.md`, - the affected `docs/` pages and their indexes. + the affected `docs/` pages and their indexes. The candidate also contains + `docs/evidence/NAME-closure-runs.md` as an unfilled closure scaffold, indexed + in `docs/evidence/README.md`. The scaffold has the final headings and fields, + marks results pending, and claims no run that has not happened. 3. The closure matrix, run **from** that commit: `bash scripts/check.sh` under the floor pair (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`, with its own `MIX_BUILD_ROOT`), and `bash scripts/check-release.sh` once on the current pair with the credential and pinned Node; CI already holds the current-pair fast check for the candidate. Each run's revision, platform, - toolchain, result and measured duration is **recorded on - `docs/evidence/NAME-closure-runs.md`** (indexed in - `docs/evidence/README.md`) **by the administrative commit, not by this - one** — the runs are *of* the tested commit, and a commit cannot carry runs - of itself. That page is one of the four paths below. + toolchain, result and measured duration is retained outside the repository + under a stable retained-output reference with a SHA-256 digest. The + administrative commit fills the existing + `docs/evidence/NAME-closure-runs.md` scaffold with those identities and + digests, including the tested archive manifest's retained-output reference + and SHA-256 digest. The runs are *of* the tested commit, and that commit + cannot carry its own later results. 4. An independent reviewer reads the candidate for outcome compliance, correctness, test honesty, public impact, security and rollback; blocking - findings are fixed first. + findings are fixed first. Retain the review report outside the repository + under a retained-output reference with its SHA-256 digest. 5. The packet to the maintainer: outcomes and their proof, the runs, the review, what remains. On their decision, the **administrative closure commit** moves the register row to `Closed`, fills the plan's Closure row, records the maintainer's words in - `docs/developer/agent-context-map.md`, and writes the evidence page with - the runs of step 3. `mix loopex.status` derives the + `docs/developer/agent-context-map.md`, and fills the evidence-page scaffold + with the runs of step 3 and the review of step 4. `mix loopex.status` derives the `Closed` capsule; run it and copy what it expects. **The two SHAs, and what each one carries.** @@ -113,6 +119,10 @@ At the **tested implementation commit**, which is the closure candidate: | What names it | Every run on the evidence page, and the review | The register, once `Closed` | | Its evidence | The runs of step 3, taken from it | None of its own; it is a record, not a claim | +The administrative closure commit has the tested implementation commit as its +sole parent. An intermediate or merge commit would add a third revision to the +closure and could hide changed-then-restored paths from an endpoint diff. + The plan's **Closure row names the tested implementation SHA** — the candidate the packet was assembled from — with the content digests closure rows have always carried. It does **not** name the administrative SHA, for the reason @@ -136,25 +146,28 @@ administrative closure commit touches **exactly these four paths**: | `docs/plans/README.md` | The register row, moved to `Closed` | | `docs/plans/.md` | The plan's Closure row, naming the tested implementation SHA and the content digests | | `docs/developer/agent-context-map.md` | The maintainer's closure disposition | -| `docs/evidence/-closure-runs.md` | The run identities, results and measured durations of step 3, the archive manifest's digest, and the security review | +| `docs/evidence/-closure-runs.md` | The existing scaffold, filled with the run identities, results, measured durations, retained-output references and SHA-256 digests of step 3; the tested archive manifest's retained-output reference and SHA-256 digest; and the independent review result, retained-output reference and SHA-256 digest | and **nothing else**. That is the whole rule; every other passage in this repository that bounds the administrative commit refers here rather than restating it, because three different formulations of it — "changes nothing the runs covered", "the register row, the Closure row and the context-map entry", "nothing outside `docs/`" — coexisted in five documents and disagreed -about whether the evidence page had a home. +about whether the evidence page had a home. The tested candidate creates and +indexes that page; the administrative commit only fills it. All four are under `docs/`, so "the administrative commit touches nothing outside `docs/`" is a **consequence** of this rule rather than a second rule, and that is how the release step states it. `git diff --name-only -..` against those four paths is the check; anything -else in that diff means the evidence no longer covers the tree, and the packet -is reassembled from a new implementation SHA. +..` against those four paths is the content check; +`git rev-list --parents -n 1 ` must show exactly +` `. Anything else in the parent line or the diff means +the evidence no longer covers the tree, and the packet is reassembled from a +new implementation SHA. **The closure matrix runs once, from the tested implementation SHA**, and the -administrative commit re-runs nothing. What the tag re-proves, and how it is -confined so that two documentation checks are enough, is in +administrative commit re-runs nothing. The pre-tag release proofs and their +retention are in [Tags](#technical-milestones-release) — it belongs to the release decision, which is what creates a tag at all, and an earlier revision of this section put it here and made closure depend on a tag that closure authorizes. @@ -166,23 +179,47 @@ Concept: [Release](milestones.md#concept-milestones-release). `COMMIT` is the **administrative closure SHA**, not the tested implementation SHA: it is the commit that carries the closure record, so it is the tree a -reader who fetches the tag gets. Before tagging: +reader who fetches the tag gets. Run every row below against `COMMIT` before +creating the tag: | Step | Command | What a failure means | | --- | --- | --- | -| Confine the administrative diff | `git diff --name-only ..`, against [the four paths](#technical-milestones-confinement) | Any other path means the tag would publish source the closure evidence does not cover; the release stops and the packet is reassembled from a new implementation SHA. Because all four are under `docs/`, a passing check also establishes that nothing outside `docs/` moved, which is what makes the two re-proofs below sufficient | -| Re-prove the documentation | `bash scripts/check.sh --docs` on the tagged SHA | The administrative commit's own documentation changes are not green; fix and re-tag | -| Re-prove the archive identity | Recompute the archive manifest from the tagged SHA and compare every entry **outside `docs/`** with the manifest recorded on the evidence page for the tested SHA | The published bytes are not the closed bytes outside `docs/`. The entries under `docs/` are expected to differ and are not compared; comparing the whole manifest would be a check that can never pass. What this catches beyond step 1 is an archive that includes or excludes differently from the tree — `.gitattributes` moves bytes into and out of an archive without appearing in a `git diff` | +| Confine the administrative commit | Require `git rev-list --parents -n 1 ` to return exactly ` `, then compare `git diff --name-only ..` with [the four paths](#technical-milestones-confinement) | An extra parent, an intermediate commit, a missing path or any other path means the tag would publish a tree outside the two-commit closure contract; the release stops and the packet is reassembled. Because all four paths are under `docs/`, a passing check also establishes that nothing outside `docs/` moved, which is what makes the three re-proofs below sufficient | +| Re-prove the documentation structure | `bash scripts/check.sh --docs` on `COMMIT` | The administrative commit's own documentation changes are not green; fix the candidate and assemble a replacement administrative commit | +| Re-prove documentation meaning | Run the milestone's final semantic documentation gate on the relevant `docs/operator/` and `docs/developer/` pages at `COMMIT` | The operator and developer accounts disagree with each other, the plan, the accepted ADRs, or the implemented behavior; fix the candidate and assemble a replacement administrative commit | +| Re-prove the archive identity | Recompute the archive manifest from `COMMIT`. Compare every entry outside `docs/`, except `SOURCE_IDENTITY`, with the manifest retained for the tested SHA. Require exactly one root `SOURCE_IDENTITY` in each archive and validate it against that archive's own commit and source identity | The published bytes are not the closed bytes outside `docs/`, or an archive identifies the wrong source. The entries under `docs/` and the two `SOURCE_IDENTITY` payloads are expected to differ. What this catches beyond step 1 is an archive that includes or excludes differently from the tree; `.gitattributes` can make that change without a path appearing in `git diff` | Nothing else is re-run. There is no second suite, no second release check and -no second provider credential: the tested tree and the tagged tree differ only -in documentation, which is exactly the property the first step establishes and -the reason two documentation-scoped checks suffice. The documentation gate's -scope is unchanged — `docs/operator` and `docs/developer`, as the verification -guide fixes it — and widening it to all of `docs/` was a claim an earlier -revision of the closure section made and nothing implements. - -`git tag -a vVERSION COMMIT -m "NAME closure"` and `git push -origin vVERSION`, on the maintainer's explicit decision. The source version +no second provider credential: the tested tree and the administrative tree +differ only in documentation, which is exactly the property the first step +establishes. The semantic gate reads `docs/operator` and `docs/developer`; the +structural check still covers the documentation paths that `check.sh --docs` +selects. + +The semantic gate starts with a complete file inventory of `docs/operator/` +and `docs/developer/`. It identifies every page affected by the milestone and +accounts for new, renamed and removed pages. For each relevant page, it checks +the administrative SHA against the implemented behavior, the plan, accepted +ADRs and the other relevant pages. The retained checklist names every file and +records either the comparison result or why the file is not relevant. + +Retain the complete output and the compared manifests from these release +proofs outside the repository in immutable, content-addressed storage. Create +the annotated tag only after every row passes. At creation, its annotation +names both SHAs and records each proof's result, retained-output reference, and +SHA-256 digest. It also records both archive-manifest retained-output references +and SHA-256 digests and both validated `SOURCE_IDENTITY` values. The evidence +page remains the closure record and is not amended with release proofs. This +sequence adds no third commit, and no proof named by the tag can postdate the +tag. + +A **retained-output reference** is the maintainer-controlled stable locator or +object name for one immutable complete output. Every retained-output reference +is paired with the SHA-256 digest of that object. The evidence page is the +reference carrier for closure outputs; the tag annotation is the reference +carrier for release outputs. + +Create `git tag -a vVERSION COMMIT` with that complete annotation, then push +the tag on the maintainer's explicit decision. The source version in `VERSION` changes in an ordinary reviewed commit before closure when the milestone's plan calls for it; every application reads it at compile time. diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index 4366c147f..af3d9de23 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -56,24 +56,26 @@ Technical depth: [Branches, worktrees and progress](milestones-technical.md#tech A closure candidate is one commit on `main` at which every outcome maps to tests, retained evidence or a demonstration, the documentation the milestone changed is updated, and the plan's progress table says Proved for each -outcome. From that exact commit run the fast check under the floor toolchain -pair and the release check once; ask an independent reviewer to read the -candidate; then present the packet to the maintainer. The maintainer closes -it; the register moves to `Closed`, the plan records the closing decision and -the tested implementation SHA, and the run identities are written to the -milestone's evidence page -— by that closing commit, since the runs are of the candidate and the -candidate cannot carry runs of itself. Use the `close-milestone` skill. +outcome. It also carries the indexed evidence-page scaffold that closure will +fill. From that exact commit run the fast check under the floor toolchain pair +and the release check once; ask an independent reviewer to read the candidate; +then present the packet to the maintainer. The maintainer closes it; the +register moves to `Closed`, the plan records the closing decision and the +tested implementation SHA, and the closing commit fills the existing evidence +page with the run and review identities, retained-output references, and +SHA-256 digests. Use the `close-milestone` skill. **Closure names two commits, because one cannot name itself.** The checks and the review are of a **tested implementation commit**; recording the closure is a further commit that necessarily comes after, and that the evidence therefore -cannot have been taken from — the runs are *of* the tested commit, so the -evidence page that holds them is written by the second, not the first. Earlier -wording asked for both from one SHA, which no sequence of commits can satisfy. +cannot have been taken from. The tested commit carries the indexed evidence-page +scaffold; the administrative commit fills it with runs *of* the tested commit. +Earlier wording created the page in the second commit, which also required its +index to change and broke the four-path confinement. So a closure carries the **tested implementation SHA**, which the runs and the review name, and the **administrative closure SHA**, which records the -decision. That second commit is **confined to four paths** — the register row, +decision as the tested commit's direct child. That second commit is +**confined to four paths** — the register row, the plan's Closure row, the context-map entry and the evidence page — which the [technical companion](milestones-technical.md#technical-milestones-confinement) states once and everything else refers to. A closure whose administrative @@ -105,26 +107,27 @@ closure evidence does not cover, and the release stops. All four are under `docs/`, so a passing check also establishes that nothing outside `docs/` moved; that is a consequence of the confinement, not a second rule. -**Two checks run at the tag, and neither is a second closure.** The tagged -tree differs from the tested one only in documentation, so what is re-proved -is documentation: `bash scripts/check.sh --docs` runs on the tagged SHA, and -the archive manifest is recomputed from the tagged SHA and compared with the -one recorded on the evidence page for the tested SHA, **entry by entry -outside `docs/`**, which must match exactly. It is not compared whole — the archive carries `docs/` too, so -a whole-manifest equality could never hold and would be a check that always -fails. Comparing the rest is what catches an archive that includes or excludes -differently from the tree the first step examined, which `.gitattributes` can -do without any diff showing it. No suite is re-run, no release check is -re-run, and no provider credential is spent again. Their results join the evidence -page with the tag named. - -**Run evidence is immutable.** A run's identity, platform, toolchain, result -and duration are retained where they cannot be edited after the packet is -read: attached to the annotated tag once it exists, or — for everything -produced before the tag, which is all of the closure matrix — held outside the -repository with its digest recorded on the evidence page. An evidence page -that can be rewritten after a reviewer read it is a record of what someone -later wished had happened. +**Three re-proofs run before the tag exists, and none is a second closure.** The +administrative tree differs from the tested one only in documentation, so +`bash scripts/check.sh --docs` runs on the administrative SHA. The final +semantic documentation gate then reads the relevant `docs/operator/` and +`docs/developer/` pages from that same SHA. The archive manifest is also +recomputed there. Every entry outside `docs/`, except `SOURCE_IDENTITY`, must +match the tested archive entry. Each archive's `SOURCE_IDENTITY` differs by +design and must name that archive's own commit and source identity correctly. +This comparison catches archive inclusion or exclusion changes that +`.gitattributes` can cause without a path appearing in the commit diff. No +suite is re-run, no release check is re-run, and no provider credential is +spent again. + +**Run evidence is immutable.** Complete closure-matrix outputs stay outside the +repository; the administrative commit records their retained-output references +and SHA-256 digests on the existing evidence page. Complete release-proof +outputs also stay outside the repository; the tag annotation records their +results, retained-output references, and SHA-256 digests when the tag is +created. The evidence page never changes after the administrative commit, and +the tag never predates evidence named by its annotation. This sequence needs +two commits and one tag, with no third commit. Technical depth: [Tags](milestones-technical.md#technical-milestones-release). ### The skills diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index 4ab6e3a66..284ca0c1d 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -20,8 +20,8 @@ Concept: [Three stages](verification.md#concept-verification-stages). | --- | --- | --- | | Change, while editing | `mix test `, `mix format`, `mix compile --warnings-as-errors`; the client Stop hook runs format, the dependency budget and the adapter check | Seconds | | Change, before merge | `bash scripts/check.sh --select` in hosted CI on the branch; a read-only review of `git diff main..` | 12 min 54 s and 12 min 38 s on the hosted runner at the final M4 candidates; on the Mac 287 s at the final candidate `d738ec7` with a warm build and ten applications at once (346 s at `031554c`, before the bound and concurrency work), against 870 s Mac and 809 s Linux in the sequential shape it replaced; 18 s before the suite starts | -| Close | `bash scripts/check.sh` under the floor pair (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`), `bash scripts/check-release.sh` once on the current pair | Release check: 149–163 s on Linux, 12 tests | -| Release | The administrative commit's diff confined to its four paths; `check.sh --docs` on the tagged SHA; the archive manifest recomputed there and matched outside `docs/` | The documentation-scoped check alone: 12–13 s on the Mac at this revision, warm build, plus a manifest comparison. No suite and no release check | +| Close | An indexed evidence-page scaffold at the tested SHA; `bash scripts/check.sh` under the floor pair (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`); `bash scripts/check-release.sh` once on the current pair | Release check: 149–163 s on Linux, 12 tests | +| Release | Before tag creation: confine the administrative commit's diff to its four paths; run `check.sh --docs` and the final semantic operator/developer documentation gate on that SHA; recompute its archive manifest; compare every non-documentation entry except `SOURCE_IDENTITY` with the tested manifest; validate both archive identities | The documentation-scoped check alone: 12–13 s on the Mac at this revision, warm build, plus the semantic review and manifest comparison. No suite and no release check | `check.sh` step order and cost: warning-free compilation 1 s (warm), formatting 1 s, repository structure 11–14 s (`scripts/check-bootstrap.sh`: client @@ -55,11 +55,18 @@ there took 38–59 s against 1 s warm on the Mac, and the same `loopex_cli` suite took 118 s at noon and 155 s in the evening. On the Mac the same knob costs about 210 s, which is why it is off by default. -Evidence retention: a closure keeps one page under `docs/evidence/` naming the -candidate, each run's platform, toolchain, result and measured duration, as -[M4 closure runs](../evidence/M4-closure-runs.md) does. Complete logs stay -with the maintainer outside the repository; the page records identities, not -output. +Evidence retention: the tested candidate carries an indexed scaffold under +`docs/evidence/`. The administrative closure commit fills that page with the +candidate, each closure run's platform, toolchain, result, measured duration, +retained-output reference, and SHA-256 digest. It also records the independent +review result, retained-output reference, and SHA-256 digest. The +[M4 closure-runs page](../evidence/M4-closure-runs.md) illustrates the identity +and result layout; new closures add the external reference and digest. Complete +logs stay with the maintainer outside the repository; the page records +identities, not output. Release proofs run later against the +administrative SHA. Their complete outputs stay outside the repository, and +the annotated tag records their results, retained-output references, and +SHA-256 digests when the tag is created. Neither lane needs a third commit. ### The selection table, mechanically diff --git a/docs/developer/verification.md b/docs/developer/verification.md index a8fec78d3..9f4eef954 100644 --- a/docs/developer/verification.md +++ b/docs/developer/verification.md @@ -32,8 +32,8 @@ Technical depth: [What each stage runs](verification-technical.md#technical-veri | Stage | Question | What runs | Who or what can stop it | | --- | --- | --- | --- | | Change | Is this change whole, and is it what it claims to be? | While editing: the focused tests for the changed boundary, `mix format`, a warning-free compile. Before merge to `main`: `bash scripts/check.sh` green in hosted CI on the branch, plus an independent review of the diff against its stated purpose. Every merge, not only milestone closures. | A red check or a blocking review finding; the integrator merges only a green, reviewed candidate | -| Close | Did the milestone deliver its outcomes? | `check.sh` once under the floor toolchain pair (the current pair is already proved by CI on every change), `bash scripts/check-release.sh` once, the outcome-to-evidence map in the plan, an independent review of the candidate — all of it from the **tested implementation SHA**, once; the **administrative closure SHA** that records the decision re-runs nothing | The maintainer, who closes it or does not | -| Release | Is the published source the closed source? | The closure evidence, reused when the source is unchanged; the tag on the **administrative closure SHA**, whose diff from the tested SHA is verified to be confined to the four paths the milestone guide fixes (all under `docs/`), plus the two documentation-scoped re-proofs that confinement makes sufficient — `check.sh --docs` on the tagged SHA, and a recomputed archive manifest matching the tested SHA's for every entry outside `docs/`. No suite and no release check run twice | The maintainer's separate release decision | +| Close | Did the milestone deliver its outcomes? | An indexed evidence-page scaffold in the candidate; `check.sh` once under the floor toolchain pair (the current pair is already proved by CI on every change); `bash scripts/check-release.sh` once; the outcome-to-evidence map in the plan; an independent review of the candidate. All checks and review use the **tested implementation SHA** once. The **administrative closure SHA** fills the scaffold and records the decision without re-running the matrix | The maintainer, who closes it or does not | +| Release | Is the source about to be tagged the closed source? | Reuse the closure evidence when the source is unchanged. On the **administrative closure SHA**, verify the four-path confinement, run `check.sh --docs`, run the final semantic gate over the relevant operator and developer documentation, and compare the archive with the tested archive outside `docs/`, except for separately validated `SOURCE_IDENTITY`. Retain these proofs outside the repository and put their results, retained-output references, and SHA-256 digests in the annotated tag at creation. No suite and no release check run twice | The maintainer's separate release decision | The fast check is the everyday gate. It is credential-free, needs no network, and is the same command locally and in CI, where it runs as From ba194d91abf23e491d99bb6536ec2427b6ffe932 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 20:22:05 -0700 Subject: [PATCH 188/585] adr(M5): align credential tracing lifecycle --- ...andoff-over-bootstrap-channel-technical.md | 266 ++++++++++-------- ...edential-handoff-over-bootstrap-channel.md | 69 ++++- 2 files changed, 210 insertions(+), 125 deletions(-) diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index 62c655323..be51eb4ef 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -47,8 +47,12 @@ earlier frame: 4. The child answers with a `ready` frame that must equal that payload exactly. Until this point the child has proved nothing, and no credential exists anywhere in the invocation. -5. Only then does the parent send the `credential` frame, from a process - spawned for that one send. +5. Only then does the guardian spawn the one-send process with a closure that + contains only the tracing capability and guardian pid. That process installs + its group-leader sink and both trace exclusions, then acknowledges the + completed exclusion. Only after that acknowledgement does the guardian send + it the token and registry handle in one message. The process resolves the + token and sends the `credential` frame. 6. The `invocation` frame follows, carrying the request, its canonical bytes and its staged digest. Possible delivery begins here, not before. @@ -58,7 +62,7 @@ booting — never reaches step 5. That is the property the two existing bootstrap-refusal cases assert, and it is why the credential is not carried by the step-3 frame. -### The token, the routing registry, and the custody process +### The token, routing registry, custody process and tracing capability **Where the token is bound, and what "per-invocation" qualifies.** The token is bound at **composition**, per runtime, and what happens per invocation is @@ -230,17 +234,17 @@ separate: kills it at the invocation deadline, reporting `:timeout`. One deadline, owned by one process, is the whole rule; a blocked registry is therefore a `:timeout` from the guardian and never a silent five-second refusal. -- **Its lifetime is the host supervisor's, and a restart invalidates the - handle.** The host starts the registry under its own supervisor when it - composes the runtime. **Exactly which supervisor, per host:** `RuntimeOwner` - for the reference CLI and for the app-server host, which is the process that - already owns their composed edges; the **daemon's owner process** for the - daemon, which links the registry and the custody process as fixed - components. In all three the normal path stops them with the rest of the - composition, a failed start unwinds them in the same reverse cleanup as any - other started edge, and the owner's own death takes them with it — they are - linked, so there is no path on which they outlive the host that composed - them. If the registry dies, the handle a composed runtime +- **Its lifetime is the host owner's, and a restart invalidates the + handle.** The host owner process starts the registry when it composes the + runtime. **Exactly which owner, per host:** the owner process spawned by + `LoopexComposition.RuntimeOwner` for the reference CLI and app-server host, + and the daemon's owner process for the daemon. `RuntimeOwner` creates an owner + process; it is not a supervisor. Each owner links the registry, custody + process and tracing capability as fixed components. In all three the normal path stops + them with the rest of the composition, a failed start unwinds them in the + same reverse cleanup as any other started edge, and the owner's own death + takes them with it, so there is no path on which they outlive the host that + composed them. If the registry dies, the handle a composed runtime holds is invalid and every resolution through it answers `:unavailable` **until the host recomposes** — the adapter does not re-look-up, does not wait and does not rebuild, because it has nothing to rebuild from. That is @@ -448,9 +452,11 @@ boundary, not an absolute: - **The capability is a host-owned process reference in model options**, the same class as the credential registry handle beside it and as the - executor's `reference:`. The host starts it before composition, as it - already starts the registry and the custody process, and hands it the - runtime reference as soon as the composition function returns one. It + executor's `reference:`. The host starts it before the runtime, as it + already starts the registry and custody process, and hands it the runtime + reference after runtime start but before the composition owner reports + success to its caller. A failed bind is a failed composition and unwinds + the runtime, capability, custody and registry in reverse order. It holds no membership and makes no decision; it exists because options are built before the runtime and something has to bridge that order. - **Membership lives in `Loopex.Runtime.Control`**, chosen by reading the @@ -466,9 +472,13 @@ boundary, not an absolute: excluded pid set, and a **ref-counted union of the excluded MFAs** — a count per identity, incremented when a sender installs it and decremented when that sender's `DOWN` arrives, so an identity is cleared for a new - session exactly while some live sender needs it. A set without counts - would either leak the identity forever or drop it while another sender - still relied on it. + session exactly while some live sender needs it. On the transition from one + owner to zero, `Control` restores that MFA in every live session to the + pattern selected by that session's own configuration; a session that did + not select it remains clear. It derives the restoration from the retained + session selection rather than from a stale captured pattern. A set without + counts would either leak the clear forever, restore while another sender + still relied on it, or overwrite a host's selected pattern. - **And starting a session is serialised against installing an exclusion.** Both are `Control` operations, so both run in its process, one at a time: a session cannot be created between a sender's flag going on and its MFA @@ -491,45 +501,35 @@ boundary, not an absolute: it skips every pid Control holds, the same place `excluded?/3` already excludes the tracer and the dispatcher by role (`trace.ex:411`), and a tracer that has just restarted asks Control rather than starting empty. - - **A `Control` restart is the one gap, and it is a runtime-wide event - rather than a tracing one.** `Control` is a `:permanent` child under + - **A `Control` restart is a runtime-wide event rather than a tracing + continuation.** `Control` is a `:permanent` child under `:rest_for_one` and is the **second** of the root's seven children (`runtime/supervisor.ex:64-90`, strategy at `:92`), so its restart clears the set — and also restarts **every child after it**: the worker task supervisor, the owner-group and session dynamic supervisors, the event dispatcher and, last, the tracer (`:73`, `:74-77`, `:78-81`, `:82-85`, `:86-89`). That ends every live trace session, and it also ends every - live **session coordinator**, which is the larger fact and the one an - earlier revision left out by naming only the tracer. A daemon meets it as - `runtime_lost` if the root does not survive, and otherwise as core's own - refusal on the next command for every session. What that means precisely: the **process flags already - installed on live sessions persist**, being state in the VM's trace - sessions rather than in `Control`; only sessions started **after** the - restart consult the set, and those find it empty. A sender that resolved - before the restart is therefore still excluded for the session it was - excluded from, and a sender that starts after it excludes itself again, as - every sender does. The remaining case is a sender whose `exclude_self/2` - call **finds `Control` unavailable** — mid-restart — and that one fails - closed like any other unconfirmed exclusion: it refuses the invocation - rather than resolving. So the absolute form — "no trace configuration can - name it back in" — holds for configuration, which is what it is about, and - the plan does not extend it to a supervision event that ends the sessions - anyway. - - **It fails closed.** `exclude_self/2` returns only once both exclusions are - installed, and it carries an **explicit** bound rather than inheriting a - `GenServer.call` default — a hidden five seconds here would be a silent - deadline inside the invocation's, exactly the fault the registry and custody - calls avoid by waiting deadline-free. Here a bound is correct where there it - was not, because the safe answer to "I cannot confirm the exclusion" is to - refuse rather than to wait. If the capability is present but the exclusion cannot be - installed — a tracer restarting in that instant — the sender **does not - resolve the credential**: the invocation refuses with `:unavailable`, the - atom the closed set already carries for "the arrangement needed to resolve - is not there", and the caller retries as it would for any other - `:unavailable`. The alternative, proceeding untraced-but-unexcluded, would - be the one case where a credential is resolved in a process a session may be - tracing. + live **session coordinator** and sender owner. Destroying each trace session + removes that session's process flags; they do not persist after session + destruction. The downstream restart also kills the senders those flags + protected, so no credential-bearing sender crosses the loss while + `Control`'s retained set is empty. A later sender excludes itself anew. A + sender whose `exclude_self/2` call finds the capability or `Control` + immediately unreachable fails `:unavailable` before it receives the token; + one whose call remains unanswered is killed by the guardian at the + invocation deadline and reports `:timeout`. + + **It fails closed under the guardian's one deadline.** `exclude_self/2` + returns only once both exclusions are installed. Its call has no independent + timeout and uses no hidden `GenServer.call/2` default: the guardian's existing + invocation deadline bounds bootstrap, exclusion, resolution and the frame + write together. If the capability or `Control` is immediately unreachable, + the sender refuses `:unavailable` before it receives the token. If exclusion + is merely slow or remains unanswered, the guardian kills the sender at the + invocation deadline and reports `:timeout`. A tracer restart destroys its + sessions; while the tracer is absent, `Control` can record the sender and MFA + set for the replacement session. The sender never proceeds on an unconfirmed + exclusion. **The capability is mandatory wherever a credential token is configured, and an absent one refuses.** An earlier revision of this pair let an @@ -547,13 +547,13 @@ boundary, not an absolute: So the rule is one rule, and there is no absent branch: **a model configuration that carries a `:credential_token` must carry a tracing - capability**, and one that is **missing, malformed, unbound, or present but - unreachable** fails the invocation with `:unavailable` **before the token is - routed** — before any lookup, before custody is reached, before a byte - exists in the parent. Missing and unreachable now differ only in when they - are caught: a missing or malformed capability is refused at **composition**, - where every other malformed option is, so an unbound one cannot reach a - call; an unreachable one is the per-invocation refusal above. This reverses + capability**. A missing, malformed or unbound capability is refused at + **composition**, where every other malformed option is, so it cannot reach a + call. A capability or `Control` found immediately unreachable during a call + produces `:unavailable` **before the token is routed** — before any lookup, + before custody is reached, before a byte exists in the parent. An exclusion + call that remains unanswered ends at the guardian's invocation deadline as + `:timeout`. This reverses the earlier decision, and the earlier decision is recorded here as what it was: a case in which the credential would have been resolved in a process a session may have been tracing. @@ -608,39 +608,59 @@ boundary, not an absolute: through `:application.get_key(application, :modules)` and `Loopex.LLM.ReqLLM.ProviderBridge` lives in `loopex_llm_reqllm`. - The third is the ordering: `exclude_self/2` is asserted to return **before** - the token is routed, and a session started concurrently with it is asserted - to produce no message from the sender either way round. + The third is the ordering: under inherited `set_on_spawn` tracing, the + sender's entry call proves its closure contains only the tracing capability + and guardian pid. `exclude_self/2` is asserted to return **before** the + guardian sends the one message carrying the token and registry handle, and a + session started concurrently with exclusion is asserted to produce no + credential-adjacent message from the sender in either order. - Three more cover what the capability is for, and each names the surface it + Four more cover what the capability is for, and each names the surface it reads and the two answers that must differ on it. - **A tracer restart keeps the exclusion.** Surface: the tracer's own message - stream. The tracer is killed, the supervisor restarts it, a new session - starts, and a long-lived sender that excluded itself before the restart is - asserted to produce **no** message under the new session while a + **A tracer restart reconstructs the exclusion for a new session.** Surface: + the tracer's own message stream and the old session's destruction. Killing + the tracer destroys its trace sessions and removes their process flags; the + test first proves the old session is gone. The supervisor restarts the + tracer, a new session starts, and a long-lived sender retained in `Control` + from before the restart is asserted to produce **no** message under the new + session while a non-excluded control process in the same session produces one. A design holding a tracer pid in options fails the first half; a case without the control process could pass by tracing nothing. - **The set returns to baseline.** Surface: `Control`'s excluded-pid set, read - **in-VM** — no wire method reports it and none is added. Asserted non-empty - while a sender is alive and empty after it exits, which is what separates - "the monitors work" from "the set was never populated". + **A `Control` restart destroys the old tracing state and its downstream + senders together.** Surface: process monitors and the tracer's session list. + The case holds a sender after exclusion but before giving it the token, kills + `Control`, and asserts that the old trace session and sender both terminate + and that no credential-bearing message was ever sent. After the runtime tree + recovers, a new trace session and new sender establish a fresh exclusion and + complete normally. The case does not assert that a destroyed session's + process flags persist. + + **The set returns to baseline and restores selected patterns.** Surface: + `Control`'s excluded-pid set and the live session's selected MFA pattern, read + **in-VM** — no wire method reports either and none is added. The set is + asserted non-empty while a sender is alive and empty after it exits. While + excluded, the named MFA produces no raw message; after the last owner exits, + the same live session again traces it according to its original selection. A + second sender keeps it excluded until that sender exits. Those observations + separate working monitors and reference counts from a set that was never + populated or a clear that permanently overwrote the host's trace pattern. **It fails closed, on every way the capability can be missing.** Surface: the invocation's own result, plus the child's record of what it received. With - the tracer made unavailable at the instant + the capability or `Control` made immediately unreachable when `exclude_self/2` is called, the invocation is asserted to refuse - `:unavailable` and the child is asserted to have received **no** credential - frame. With the capability **absent** from a configuration that carries a - token, and again with one **bound to a dead process**, the same two - assertions hold — the refusal and the empty child — where the earlier - revision asserted the opposite for the absent case. The two answers that - must differ are therefore the refusal and an ordinary success, and the - success case is a **complete** configuration, which is the only one there - is. A composition given a token and no capability is asserted to refuse at - **composition**, so no call reaches the per-invocation branch at all. + `:unavailable`; with the exclusion call held unanswered until the invocation + deadline, the guardian kills the sender and reports `:timeout`. In both cases + the child receives **no** credential frame. A composition given a token and + no capability is asserted to refuse at **composition**, so no call reaches + the per-invocation branch. A capability that dies after a successful bind is + asserted to refuse the later invocation as `:unavailable`. Each refusal is + paired with an ordinary success from a complete, live configuration, and + every path asserts that the child receives no credential before exclusion is + confirmed. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or @@ -686,8 +706,8 @@ produced, and nothing else is accepted. | `:missing` | A custody process | It has no credential for this token | | `:expired` | A custody process | It has one and considers it no longer valid | | `:oversized` | The sender | A successful reply whose bytes fall outside 1 to 65,536 | -| `:unavailable` | The registry or a custody process | A missing registry row, a gone registry, a dead custody process, a custody process that answers `:unavailable`, or **a successful reply that is malformed** — not `{:ok, %{credential: binary}}`, including a bare binary where the keyed map is required — because a reply the sender cannot read, or reads in a shape the redaction pass does not protect, is not a credential it can send | -| `:timeout` | The guardian | Resolution had not completed when the invocation deadline was reached | +| `:unavailable` | The tracing capability, registry or a custody process | A capability or `Control` that is immediately unreachable, a missing registry row, a gone registry, a dead custody process, a custody process that answers `:unavailable`, or **a successful reply that is malformed** — not `{:ok, %{credential: binary}}`, including a bare binary where the keyed map is required — because a reply the sender cannot read, or reads in a shape the redaction pass does not protect, is not a credential it can send | +| `:timeout` | The guardian | Exclusion or resolution had not completed when the invocation deadline was reached | An earlier draft left the first two unnamed and folded a malformed successful reply nowhere at all, which meant three real failures had no atom to carry. @@ -712,7 +732,8 @@ faults and ADR 0029's bounded status has to say which happened — and it can, because a refusal arrives as one of the six atoms produced below the guardian — `:no_token` and `:invalid_token` from the adapter, `:missing` and `:expired` from a custody process, `:oversized` from the sender, and -`:unavailable` from the registry or custody — while a silence is the +`:unavailable` from the tracing capability, registry or custody — while a +silence is the guardian's own `:timeout`, the seventh. The reported reason is never the resolved value, the token, or a host-authored string. @@ -723,6 +744,9 @@ leaves no retained copy of anything the resolver may have produced: | --- | --- | | No `:credential_token` in the configuration | `:no_token`, refused before the namespace is created and before any child is spawned | | Malformed token — anything that is not a `%CredentialToken{}` struct with a 16-byte `id`, a bare binary included | `:invalid_token`, refused before any lookup and before any child is spawned. The struct is what makes this decidable: a credential is a bare binary, and no content test separates one from a token | +| A token is configured without a well-formed capability bound to the returned runtime | Refused at composition; no invocation or child starts | +| The capability or `Control` is immediately unreachable when the sender asks for exclusion | `:unavailable`, before the guardian sends the token or registry handle and before custody is reached | +| Exclusion remains unanswered when the invocation deadline is reached | The guardian kills the sender and reports `{:error, :timeout}`, before sending the token or registry handle | | A successful custody reply that is malformed — not `{:ok, %{credential: binary}}`, a bare binary included | `:unavailable`; a bare binary is refused rather than accepted, because accepting it would carry bytes in a shape the redaction pass leaves verbatim below 65 bytes | | The registry holds no row for the token, the registry is gone, or the custody process is dead | `:unavailable`. The host recomposes; nothing is reconstructed, because the registry holds no bytes to reconstruct from | | Custody answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | @@ -736,14 +760,16 @@ coordinator's durable decision under ADR 0018, unchanged. ### Scrub points -- **In the sender.** The minimal credential sender keeps the shape it has - today: it is spawned for this one send, it installs its own group leader - sink so no IO request can carry anything out of it, it looks the token up in - the host's routing registry, calls the custody process it names, receives the - one permitted credential-bearing reply, validates the size bound, writes the - frame itself and reports `:ok` or `{:error, reason}` from the closed set to - the guardian — which is supervising it against the invocation deadline - throughout. Its closure holds the token, never the resolved value; in the +- **In the sender.** The sender is spawned with a token-free closure containing + only the tracing capability and the guardian pid. It installs its group + leader sink, calls `exclude_self/2`, and acknowledges the completed exclusion. + Only then does the guardian send it the token and registry handle in one + message. It looks the token up in that registry, calls the custody process it + names, receives the one permitted credential-bearing reply, validates the + size bound, writes the frame itself and reports `:ok` or `{:error, reason}` + from the closed set to the guardian, which supervises the entire sequence + against the invocation deadline. Neither the spawn closure nor any message + sent before exclusion holds the token, registry handle or credential. In the parent the value exists in the custody process and, for the duration of one send, in this process's own mailbox and stack, and nowhere else — no guardian state, no exit reason and no crash report can @@ -842,7 +868,7 @@ own custody, and the case has that invocation's custody process hold the 65,536-byte value rather than writing it into the VM. The ceiling it proves, and the refusal above the ceiling, are unchanged. -Three proofs are new: +Six proof groups are new: - **Parent environment**, stated as two checkable things rather than one unfalsifiable one. From the completion of composition onward — before, @@ -907,7 +933,9 @@ Three proofs are new: what lets an environment read return by a name the current expression does not match, which is the drift the case exists to catch. - **Resolution failures.** One case per row of the failure table above: - absent token, malformed token, a token with no registry row, a gone + absent token, malformed token, a token with no tracing capability, a failed + capability bind, an immediately unreachable capability or `Control`, an + exclusion held past the invocation deadline, a token with no registry row, a gone registry, a dead custody process, each of the four refusal atoms, a custody process returning a term outside the closed set (reported `:unavailable`), a custody process that blocks past the invocation deadline (the **guardian** @@ -920,7 +948,7 @@ Three proofs are new: exit reason and no crash report carries the resolved value. The two-resolutions-at-once case is a **success** case, not a refusal: both invocations complete with their own credentials. -- **Tracing, in two cases matching the two tiers above.** Under the +- **Tracing, in three cases matching the two tiers above.** Under the **default** trace configuration, a session at the `arguments` level over a real invocation produces no entry naming `route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, no raw trace @@ -943,13 +971,14 @@ Three proofs are new: | Host | File | Cases | Lane | | --- | --- | --- | --- | - | Reference CLI | `apps/loopex_cli/test/credential_custody_test.exs` | `reads the credential variable exactly once at composition`; `deletes the credential variable from the VM environment`; `custody state is redacted in a forced crash report`; `the tracing capability is composed and reaches the current tracer` | fast | - | App-server host | `apps/loopex_app_server/test/credential_custody_test.exs` | the same four | fast | - | Daemon | `apps/loopex_daemon/test/credential_custody_test.exs` | the same four, plus `registry, custody and capability are stopped with the daemon and on a failed start` | fast | + | Reference CLI | `apps/loopex_cli/test/credential_custody_test.exs` | `reads the credential variable exactly once at composition`; `deletes the credential variable from the VM environment`; `custody state is redacted in a forced crash report`; `starts the tracing capability before the runtime and binds it before reporting composition success`; `registry, custody and capability stop on normal stop, failed start and owner loss` | fast | + | App-server host | `apps/loopex_app_server/test/credential_custody_test.exs` | the same five | fast | + | Daemon | `apps/loopex_daemon/test/credential_custody_test.exs` | the same five | fast | Each proves that composition reads the variable exactly once, deletes it - from the VM's environment, and that the holding process's `format_status/1` - redacts its state under a forced crash report. The adapter's own tree keeps only what is the adapter's + from the VM's environment, that the holding process's `format_status/1` + redacts its state under a forced crash report, and that the capability's + start-bind-stop lifecycle follows its host owner. The adapter's own tree keeps only what is the adapter's to prove: that it reads no environment variable for a credential and that the token and resolution contract behaves. @@ -985,13 +1014,23 @@ The review is an acceptance point of M5 Outcome 6, read by someone other than the implementer, over the exact diff. It answers: that the token is opaque and carries no credential and no authority; that the routing registry holds routing only, with no bytes and no material a secret could be derived from; +that the spawned closure is token-free and receives the token and registry +handle only after synchronous exclusion; that the mandatory tracing capability +starts before the runtime, binds before composition reports success and stops +with its host owner on every exit path; that immediate capability loss refuses +`:unavailable` while a delayed exclusion ends only at the guardian's invocation +deadline as `:timeout`; that trace-session destruction removes its process +flags, a tracer restart reconstructs exclusions from `Control`, a `Control` +restart kills downstream senders with the destroyed sessions, and the last MFA +owner restores every live session's selected pattern; that the resolved value has no path into guardian state, a message other than the one permitted reply, an exit reason, a crash report, an IO request, a file or the environment; that every row of the failure table refuses without -retaining a copy; that the guardian's deadline bounds the whole resolution +retaining a copy; that the guardian's deadline bounds exclusion and resolution whatever a custody process does; that the cleanup and abandonment paths do not -resurrect a value; that loss of custody or registry answers `:unavailable` -rather than reconstructing anything; that a host supplying no token is refused +resurrect a value; that immediate loss of custody, registry or capability +answers `:unavailable` rather than reconstructing or bypassing anything; that a +host supplying no token is refused rather than falling back to an ambient read; and, on the host side of the boundary, that each reference implementation reads the operator's variable once, deletes it, redacts its custody process's state, and registers a token @@ -1062,8 +1101,12 @@ child built from the same manifest digest behaves identically; the build manifest is not revised by this decision. The one visible change is host composition: a host that starts a runtime with -this adapter passes a credential token with the call and owns both the -registry that routes it and the custody process that holds the bytes. The reference CLI, the app-server host, the M5 daemon and the +this adapter puts a credential token, registry handle and tracing capability in +the model options and owns the registry, custody process and capability behind +them. It starts those three before the runtime, binds the capability to the +runtime reference before reporting composition success, and stops them on +normal stop, failed start and owner loss. The reference CLI, app-server host, +M5 daemon and real-provider lane keep reading `LOOPEX_PROVIDER_API_KEY` where they compose, and delete it there, so an operator's setup is unchanged and the release check's credential frame is unchanged. An embedder that relied on the adapter reading @@ -1071,10 +1114,13 @@ the environment for it must pass a token instead; that is the refusal path, not a silent fallback, and it is stated in the operator and developer documentation the milestone updates. -Rollback is reverting the adapter change. Nothing durable, no root and no -protocol generation records which mechanism delivered a credential to a -process that has since exited, so a rollback needs no migration and leaves no -trace to repair. +Rollback is a coordinated code rollback of the adapter, the core +trace-exclusion support and the CLI, app-server and daemon composition changes. +Hosts resume supplying the credential by the pre-M5 mechanism in the same +change; no host may keep passing a token to an adapter that no longer resolves +one. Nothing durable, no root and no protocol generation records which +mechanism delivered a credential to a process that has since exited, so a +rollback needs no data migration and leaves no retained trace state to repair. Acceptance binds this complete pair at the exact candidate the maintainer names in the governance record. Its claims remain unproved until the tests the diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index e5ced7f28..fe7596bf5 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -53,10 +53,20 @@ resolution, not the token's arrival** — the token is bound once, per runtime, and resolved afresh on every call. There is nowhere else it could arrive: `complete/3` receives a request and the composition-time options and nothing per-call from the host, so a token "supplied with each call" would have no -seam to arrive through. Behind it the host owns two things the +seam to arrive through. Behind it the host owns three things the adapter does not: a **routing registry** that maps a token to a custody process and holds routing only — never bytes, never anything a secret could be -derived from — and the **custody process** that holds the bytes. The adapter +derived from — the **custody process** that holds the bytes, and a mandatory +**tracing capability** through which the sender excludes itself before it can +receive either the token or the registry handle. The host starts all three +before the runtime, puts the token, registry handle and tracing capability in +the model options, and binds the capability to the runtime reference after the +runtime starts but before composition reports success to its caller. A missing, +malformed or unbound capability refuses composition and unwinds the started +edges; an immediately unreachable capability refuses an +invocation before the token is routed. The capability holds no credential, +registry membership or policy. It only bridges composition order to the +runtime-owned exclusion state. The adapter resolves the token exactly once per invocation, inside the minimal sender process that writes the credential frame, and only after the child has proved its nonce, codec version and build manifest digest. The adapter reads no @@ -123,15 +133,35 @@ adapter's own functions are patterned. M5 proves both at the tracer rather than at the sink, in a case that names `:gen_tcp` on purpose. ADR 0030 is not edited: its prose is honoured once this lands. +The spawn ordering is part of that decision. The spawned closure contains only +the tracing capability and the guardian to acknowledge; it contains no token, +registry handle or credential. The process installs both exclusions and +acknowledges them synchronously. Only then does the guardian send the token and +registry handle to it. When the last sender using an excluded function exits, +core restores each live trace session's selected pattern for that function. +Destroying a trace session removes its process flags; `Control` retains live +sender membership and the ref-counted function set so a replacement trace +session reapplies the same exclusion. A `Control` restart destroys the trace +sessions and the downstream sender owners together, so no credential-bearing +sender crosses that loss with an unremembered exclusion. + +The guardian's existing invocation deadline is the only clock for this +sequence. A capability or `Control` that is immediately unreachable produces +`:unavailable`; an exclusion that has not completed when the deadline arrives +causes the guardian to kill the sender and report `:timeout`. There is no +separate exclusion timeout and no hidden `GenServer.call/2` timeout. + **Everywhere else the boundary is where the adapter's claims stop.** Inside it — the token, the sender, the frame, the child — the adapter proves what it says: the value is never in the child's environment, in argv, in the journal, in a public event, a snapshot, a progress item or a diagnostic, in adapter process state, in any message but that one, in an exit reason, a crash report or an IO request, and never written to a file. Outside it, custody belongs to the host and the adapter -proves nothing about it beyond the two structural rules it does impose: the -registry holds routing only, and losing custody or the registry answers -`:unavailable` rather than reconstructing anything. This pair therefore states +proves nothing about it beyond the structural rules it does impose: the +registry holds routing only; the mandatory capability confirms exclusion before +the sender receives the token or registry handle; and losing custody, the +registry or the capability answers `:unavailable` rather than reconstructing or +bypassing anything. This pair therefore states the reference implementations' custody as their own obligation rather than claiming a property of every host that might compose a registry. @@ -207,9 +237,16 @@ proved to refuse with one of the seven closed reason atoms and to leave no retai guardian's timeout proved distinguishable from every refusal and proved to bound the invocation whatever the custody process does; two resolutions in flight at once are proved to be independent successes rather than a refusal; -the one permitted credential-bearing reply, and the resolver call that +the token-free spawn entry, the post-exclusion token-and-registry message, the +one permitted credential-bearing reply, and the resolver call that carries it, are proved excluded from tracing under a trace session at the -`arguments` level; the adapter's library tree is proved to read +`arguments` level; the last owner restores every live session's selected MFA +pattern; trace-session and tracer restart cases prove that destroyed-session +flags are not treated as persistent and retained membership protects a +replacement session; capability loss before binding, immediate +unreachability and delayed exclusion distinguish composition refusal, +`:unavailable` and the guardian's `:timeout`; the adapter's library tree is +proved to read no environment variable for a credential by any route, with the launcher's ADR 0019 scrubbing read proved never to be consulted for one; and a named reviewer reads @@ -235,12 +272,13 @@ plane, and in no message but the one reply this pair permits. Two invocations in one VM become independent, so the **eleven** provider test modules serial for this reason can run concurrently and the fast check stops being pinned by that application. The other two stay serial on their own reasons, which is why the -claim is eleven rather than thirteen. Host -composition gains one explicit input and one explicit obligation: a host that -starts a runtime with this adapter passes a credential token with the call, -instead of relying on the VM's environment being right at call time, and it -owns both the registry that routes the token and the custody process the -bytes live in. A host that supplies no token gets the adapter's ordinary +claim is eleven rather than thirteen. Host composition gains three explicit +model inputs — the credential token, registry handle and tracing capability — +and owns the registry, custody process and capability behind them. It starts +those processes before the runtime, binds the capability after runtime start +but before reporting composition success, and stops all three on normal stop, +failed start and owner loss. A host that supplies no token gets the adapter's +ordinary refusal to dispatch, which is what a missing environment variable produces today. @@ -248,9 +286,10 @@ Nothing public changes. This is adapter-internal: no Model callback, no public event, snapshot, artifact, wire method or protocol generation, no durable record, and no change to what the child may receive, from whom, or when. The credential-size bound and the refusal behaviour ADR 0019 fixed stay as they -are. Rollback is reverting the adapter change; no data, root or protocol +are. Rollback reverts the adapter, trace-exclusion support and the CLI, +app-server and daemon composition changes together. No data, root or protocol depends on which mechanism delivered a credential to a process that has since -exited. +exited, so rollback needs no data migration or repair. Technical depth: [Compatibility mechanics](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-compatibility). From d369c3cebbd2947ee3329bc5b3df8a423a5b6ca0 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Sun, 20 Sep 2026 20:30:09 -0700 Subject: [PATCH 189/585] docs(M5): resolve daemon contract findings --- ...mon-grade-store-selection-and-migration.md | 12 +- ...tachment-residency-and-replay-technical.md | 989 +++++++----------- ...-daemon-attachment-residency-and-replay.md | 93 +- ...controller-lease-and-takeover-technical.md | 176 ++-- ...aboration-controller-lease-and-takeover.md | 33 +- 5 files changed, 579 insertions(+), 724 deletions(-) diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index a05d24b0b..730b5e8a1 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -33,7 +33,8 @@ be decided now is which store the daemon runs on and what the operator is owed about its limits. **Select the existing local adapter as the daemon's store for `0.2.0`.** The -daemon holds the local writer marker for its process's lifetime and inherits +Store process holds the local writer marker for the Store process's lifetime, +while the daemon owns and watches that process, and the daemon inherits the adapter's exact, documented limits: one append-only log per state root with a hard 256 MiB capacity, a 4 MiB frame ceiling, full-history retention with no compaction, full replay at open, and one writer per root. Reaching @@ -131,9 +132,12 @@ is a separate compatibility surface: adding an adapter later freezes no wire, artifact or embedded contract, and the exact private format stays experimental in 0.x. -M5 rollback is stopping the daemon: the foreground server and CLI reopen the -same root under the same placement identity. There is no forward migration to -roll back, because M5 introduces none. +M5 rollback is stopping the daemon in its ordered Store-last path, which lets +the Store process release the marker before the foreground server or CLI +reopens the same root under the same placement identity. A Store that exits on +its own releases the marker before the daemon can react; a kill or power loss +may instead leave a stale marker for the adapter's verified recovery. There is +no forward migration to roll back, because M5 introduces none. Technical depth: [Compatibility mechanics](0031-daemon-grade-store-selection-and-migration-technical.md#technical-adr-0031-compatibility). diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 6adf35b50..69e6c0fd7 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -125,10 +125,10 @@ condition to observe. Framing, the initialize handshake, admission records, snapshot, event and progress records, the frame ceiling, the strict UTF-8/LF rule and the unknown-field rule are reused from ADR 0023 unchanged. **Request records -are the one exception**, and they are reused with one addition rather than -unchanged: every existing-session mutation in generation 2 carries -`writer_epoch`. That is the addition, and it is the reason generation 2 needs -a schema digest of its own. +have one generation-2 addition**: every existing-session mutation carries +`writer_epoch`. Attach keeps ADR 0023's optional boolean `replace`; because +each protocol connection holds at most one attachment, the adapter can map +that boolean to core's exact replacement selector without ambiguity. **The addition, at the exactness a vector needs**, because "carries `writer_epoch`" is not a type, an optionality or a list: @@ -155,203 +155,106 @@ one attachment after `session.attach`; generation 2 permits a connection to hold at most one attachment at a time — **and at most one controller lease**, which ADR 0033 fixes for the same reason and which is what makes closing "the controller's connection" name exactly one session — and a client process to -hold as many connections as the residency limits admit. - -**An attachment never outlives the process that attached it, and M5 is what -makes that true.** The mechanism is a monitor, not a detach call. Today the -dispatcher monitors the attaching process only while its snapshot scan is in -flight and **demonitors it the moment the scan finishes** -(`event_dispatcher.ex:455`), after which nothing watches that process at all -and the installed attachment records neither its pid nor a monitor -(`:764-803`); -`disconnect/2` marks an attachment disconnected and empties its queue but -leaves the entry in place (`:879-886`); and the one path that actually removes -an entry is same-session **supersession** (`:812-823`) — which M5's -concurrent-attachment change removes, because coexisting attachments are the -point. - -**And there is a third place the change has to reach, which two reviews of -this pair missed: `Control` is single-attachment too.** The dispatcher is not -the only component holding attachment state. `Control`'s session entry has one -`attachment` field, `finish_attach/5` **overwrites** it on every successful -attach (`control.ex:1273-1283`), the command path validates against that one -field (`:343`, `current_attachment?/3` at `:1649-1657`, answering -`{:error, :stale_attachment}` for anything else), and `attachment_repetition/4` -keeps its repetition state for that same single attachment (`:1312-1314`). - -So with only the dispatcher changed, two coexisting attachments would still -break the session at `Control`: an observer attaching after a controller -overwrites the controller's slot, and the controller's **next command** fails -— the daemon's central case, failing on the component nobody had looked at. - -**Core change 1 therefore includes `Control`'s attachment and repetition -state, held per holder rather than per session.** The **holder pid** — the -connection process the dispatcher already monitors for the release half of -this change — is what the entry belongs to, so the two components agree about -whose attachment is whose and one `DOWN` drops the entry in both. `Control` -keeps one attachment *per holder* per session rather than one per session, and -keeps repetition state per holder entry. Nothing about the -single-attachment-per-connection rule changes: one holder still has one -attachment. - -**But the holder pid cannot be the only key, because the reader has no holder -pid**, and an earlier revision said "keyed by the holder pid" without checking -that. The one reader is the command path: `handle_call({:route_command, token, -session_id, attachment_id, incarnation_id}, _from, state)` **discards `_from`** -(`control.ex:336`) and resolves the attachment from the handle's -`attachment_id` and `incarnation_id` (`:343`, `current_attachment?/3` at -`:1649-1657`). Under the daemon the caller is not the holder at all — the -holder is the connection process, and the command arrives from a **relay -task** — so a lookup by caller pid would find nothing, and a lookup by `_from` -would find the wrong entry. - -So the entries are **reachable both ways**, which is one change and not two: - -| Operation | Key | Why | -| --- | --- | --- | -| Insert, on a successful attach | Holder pid | It is what the attachment belongs to and what a `DOWN` will name | -| Release, on the holder's `DOWN` | Holder pid | The `DOWN` carries the pid and nothing else | -| Validate a command (`:343`) | **`attachment_id`** from the handle | The caller is a relay task; the handle is the only thing that identifies which attachment is speaking | -| Repetition (`attachment_repetition/4`, `:1312-1314`) | The holder entry the command resolved to | Repetition is per attachment, and the command has already found it | - -An implementation may keep a second index from `attachment_id` to holder pid, -or keep the id on the pid-keyed entry and resolve by scanning the session's -holders — at most 64 per session by the ceiling below, so either is bounded. -What is fixed here is the contract, not the data structure: **the id resolves -the entry, the pid owns it, and the `DOWN` releases it.** - -Its witness is the case that fails today: a controller attaches, an observer -attaches to the same session, and **both remain usable** — the controller's -next command is admitted and the observer keeps receiving. - -So that change has three parts and this pair states all of them: supersession -stops removing attachments **unconditionally**, **the dispatcher keeps its -monitor after install and -removes the attachment on that process's `DOWN`**, and **`Control` scopes its -attachment and repetition state by holder**. Without the second half M5 -would leave core with no release path at all, and every attachment ever made -would live until the runtime stopped. - -**The `DOWN` removal must release the attachment's transfers, and saying so is -not optional.** The supersession block is the **sole** caller of -`release_transfers/2` — the call is at `event_dispatcher.ex:817`, inside the -block at `:812-818`, and the function is defined at `:1105` with no other call -site in the module. Removing the block without moving that call would leave -accepted **ADR 0028** unsatisfied, its technical companion requiring that -"detaching releases every transfer the attachment opened" -(`0028-…-technical.md:28-30`). So the dispatcher's `DOWN` handler calls -`release_transfers/2` for the attachment it drops, and the conditional -replacement path below calls it for the attachment it supersedes. ADR 0028 is -thereby satisfied on both of the two paths that end an attachment, where today -it is satisfied on one; its witness is a case in -`apps/loopex/test/concurrent_attachments_test.exs` asserting that an -attachment with an open transfer, released by its process exiting, leaves no -transfer behind. - -**And supersession becomes conditional rather than disappearing, because -today it *is* the implementation of `replace`.** That took checking rather -than assuming, and the answer is not what ADR 0032 said. ADR 0023 puts an -optional `replace` boolean on `session.attach` -(`0023-…-technical.md:165`) and requires that a second attach refuse "unless -it names explicit replacement, which detaches the first at its last completely -emitted cursor" (`:359`). **Core never sees that flag.** The app server reads -it (`mapping.ex:162`, `:458`) and uses it for one thing only — whether a -connection already holding an attachment may open a second -(`attachable/3`, `:466-470`) — and then builds core's options without it -(`attach_options/1`, `:450-456`); `Control.validate_attach_options/1` would -refuse it anyway, its `Keyword.validate/2` defaults naming only -`after_event_sequence`, `request_id`, `client_id` and `attachment_key` -(`control.ex:1293-1310`). What actually replaces the attachment is core's -**unconditional same-session** block, which reads no flag and supersedes -*every* attachment of that session. - -So the change is stated as what it is: **the same-session supersession becomes -conditional on `replace`, and narrows its scope to the attaching process's own -prior attachment** for that session. Core's attach options gain `replace`, the -app server passes the flag it already parses, and the block fires only when it -is set. - -**That scope needs an identity the installed attachment does not carry today, -and core change 1 adds it.** `install_attachment/3` builds the attachment map -from the scan's result — `id`, `incarnation_id`, `session_id`, cursors, queue, -capacity, status, metadata, transfers (`event_dispatcher.ex:764-803`) — and -**no attacher pid**; the supersession that follows splits `state.attachments` -on `session_id` alone (`:812-818`); and the monitor the dispatcher held during -the scan is **demonitored the moment the scan finishes** (`:455`). There is -therefore nothing on an installed attachment that says which process attached -it, so "the attaching process's own prior attachment" is not a set anything -could compute. - -Core change 1 therefore **retains the attacher's pid and its monitor reference -on the installed attachment**. That is not a third half: the change already -has to keep the monitor rather than dropping it at `:455`, because the `DOWN` -release is the whole of the second half — and a `DOWN` carries the monitor -reference and the pid, which is exactly what the handler needs to find the -attachment to drop. Holding both on the attachment makes the `DOWN` lookup a -map lookup rather than a scan, and makes the replacement scope a filter on a -field that exists. One addition, two uses. - -**A pid on an attachment crosses no boundary the vision fences.** The rule is -about durable and public or executor contracts; the dispatcher's -`state.attachments` is neither — it is runtime-local process state, exactly as -the `caller_monitor` it already holds on a pending scan is -(`event_dispatcher.ex:186-192`). Nothing about the attachment's pid is -journaled, sent on the wire, put in a snapshot or handed to an executor, and -the snapshot and `attached` records a client receives are unchanged. - -- **Generation 1 is behaviour-identical**, which is what ADR 0023 requires and - what this milestone promises for the foreground server: that host maps one - connection to one attachment, so its supersession only ever fired behind a - `replace: true` the app server had already admitted, and narrowing the scope - to the attaching process changes nothing where there is one attacher. -- **Generation 2 needs both halves of the change.** Without the condition, a - daemon's second connection would detach the first — the thing concurrent - attachment exists to stop. Without the narrowed scope, a `replace: true` - from one connection would detach *every other connection's* attachment to - that session, which is worse. -- **ADR 0023 stays unamended.** Its `replace` field is unchanged, its rule - that a second attachment refuses unless replacement is named is unchanged, - and what the foreground server does is unchanged. What changes is on which - side of the boundary the flag is honoured: the app server keeps its - connection-level check and now also passes the flag through, and core stops - superseding without being told to. No wire field moves, so no digest input - moves either. -- **"The named prior incarnation" is corrected.** An earlier revision of this - pair said explicit replacement "invalidates only the named prior - incarnation at its last emitted cursor". There is no name on the wire — - `replace` is a boolean — so what it invalidates is the attaching process's - own prior attachment for that session, at its last completely emitted - cursor, with `release_transfers/2` called for it. - -For the daemon this needs no API: it attaches from its **per-connection -process**, so a connection that closes — because the client went away, because -the daemon is stopping, or because the daemon gave up on a request that never -answered — ends that process, and the `DOWN` releases the attachment. That is -what makes a connection a sufficient handle on an attachment, and it is why a -daemon needs no attachment count from core to release what it reserved. - -An explicit `detach/1` on **core's** public API was the alternative and is -rejected: -it would add a call every caller must remember on every exit path, including -the paths where the caller is already gone, which is exactly the case a -monitor handles for free. That rejection is about the core API and about a -*caller* detaching itself. It is not a rule against the daemon ending an -attachment — the daemon does that four ways, listed with `control_owner_lost` -below, and every one of them is a record written to that connection and then -the close of that connection, which is the same monitor-driven release read -from the other side: the connection process ends, and its `DOWN` releases the -attachment with no call at all. - -The core EventDispatcher and Control retain multiple live attachment IDs and -incarnations for one session. A new distinct attachment does not implicitly -detach another session attachment or cancel its pending read. Repetition of -the same attachment request returns its live attachment; explicit replacement -— `replace: true` — invalidates the attaching process's own prior attachment -for that session at its last completely emitted cursor, and releases its -transfers. -Snapshot barriers, queued durable delivery, stale-handle checks and detach -remain core operations. The daemon neither copies the snapshot into a second -fan-out owner nor reads coordinator state to repair an attachment race. +hold as many connections as the residency limits admit. Its attach request +keeps optional `replace`: on either protocol generation `true` maps to that +connection's sole live attachment, while a second attach with `false` refuses +ADR 0023's existing `attachment_conflict`. Embedded callers are not subject to +the connection rule and use core's explicit `replace_attachment_id` option. + +**An attachment never outlives its holder, and M5 makes the holder explicit.** +Today `Runtime.attach/3` uses the process that calls it as the transient scan +caller, the dispatcher drops that monitor after installation, and `Control` +keeps only one attachment per session. Those three facts cannot implement +multiple attachments, and a daemon relay task cannot stand in for the +connection whose lifetime the attachment must follow. + +Core change 1 therefore has two entry paths with one implementation: + +- `Runtime.attach/3` remains the embedded entry and uses `self()` as the + holder; +- the daemon-only `Runtime.attach_for_holder/4` accepts the already-authorized + connection pid as the stable holder. The admission relay starts the + monitored attach task and passes that pid before acknowledging the ticket, + so the task may end without changing whose lifetime owns the result. + +Both EventDispatcher and Control install their **own** monitor of the stable +holder. A monitor is observed only by the process that creates it, so sharing +one reference or expecting Control to receive EventDispatcher's `DOWN` would +be an unrunnable design. Each component keeps a holder entry containing a set +of attachment IDs. EventDispatcher owns the cursor barriers, queues and open +transfers; Control owns command routing and repetition state. A holder may own +several attachments to the same session, and each ID resolves exactly one +entry in both components. On `DOWN`, EventDispatcher removes every attachment +in that holder set and calls `release_transfers/2` for each; Control removes +the same IDs and their repetition state. Each component demonitors only after +its set for that holder is empty. + +The monitors are installed before the snapshot scan starts. A holder `DOWN` +marks every pending attach for that holder cancelled in each serial owner; an +install step rechecks that mark and refuses rather than publishing an +attachment for a process already known dead. This covers death before, during +and immediately after the relay task's core call. + +**Replacement names one attachment.** Core attach options gain optional +`replace_attachment_id`; when present, the target must be a live attachment +owned by the same holder and session. Installation and removal are one serial +EventDispatcher transition: the named target is removed at its last emitted +cursor, its transfers are released, and the new attachment takes its place. +An absent, stale, foreign-holder or other-session target refuses +`:stale_attachment` in core, mapped to generation 2's inherited +`attachment_conflict`, and changes nothing. With no selector, a distinct request +installs another attachment even when that holder already owns one for the +session. Exact repetition of the same attach identity returns the same live +handle rather than installing a duplicate. + +ADR 0023's boolean remains the wire field on both protocol adapters. Each +adapter permits only one connection attachment, so on `replace: true` it maps +the sole handle it already holds to core's `replace_attachment_id`; on +`replace: false` it keeps ADR 0023's second-attach refusal. Embedded callers +use the core selector directly and are the case for which several candidates +can exist. + +**Holder cleanup and daemon ceiling release are one acknowledged sequence.** +The daemon registry owns connection and attachment reservations. When a +connection ends it marks that holder's installed and in-flight slots +`closing`; it does not release them merely because its own monitor fired. The +admission relay first accounts for every ticket from that holder. The registry +then calls the internal, idempotent `Runtime.release_holder/2`, which returns +only after EventDispatcher and Control contain no attachment for the holder; +a cleanup already caused by their monitors is success. Only that reply frees +the daemon slots. If core cannot confirm the cleanup, the slots remain charged +and the runtime failure follows the daemon's fatal path. A late attach cannot +appear after confirmation because the relay had already settled every holder +ticket. This ordering prevents the registry from admitting a replacement +while core still holds the old attachment and makes the 64-per-session and +512-per-daemon ceilings true at every instant rather than eventually. + +The same path handles an orderly daemon close and an abrupt peer loss. For an +embedded caller no daemon counter exists; the two core monitors still remove +the whole holder set. The runtime-local pids and monitor references cross no +durable, public or executor boundary. + +**Transfer cleanup remains mandatory.** `release_transfers/2` is currently +called only by unconditional same-session supersession. M5 moves that call to +each named-replacement removal and to every holder-set removal. The witness +opens transfers from two same-holder attachments, replaces one by ID and then +kills the holder: replacement releases only the target's transfers; holder +loss releases the survivor's; a different holder's attachments continue. + +A general public `detach/1` remains rejected. It would require every caller to +remember cleanup precisely when the caller may already be dead. The two +internal operations above have narrower purposes: `attach_for_holder/4` +separates the relay task from the lifetime owner, and `release_holder/2` lets +the daemon retain resource reservations until the automatic monitor cleanup is +confirmed. Neither gives a client authority to detach another holder. + +The core EventDispatcher and Control therefore retain multiple live attachment +IDs and incarnations for one session and multiple IDs for one holder. A new +distinct attachment does not implicitly detach another or cancel its pending +read. Snapshot barriers, queued durable delivery, stale-handle checks and +holder cleanup remain core operations. The daemon neither copies the snapshot +into a second fan-out owner nor reads coordinator state to repair an +attachment race. ### Queue ownership @@ -437,26 +340,35 @@ The rule is that **a reservation counts**: activation is one-way and the daemon has no way to know a coordinator died, which this pair says twice elsewhere. It differs from `activations_used` only by the reservations in flight; -- `attachments` counts installed attachments plus reserved attachment slots, - for the same reason `activations_used` does; +- `attachments` counts installed attachments plus reserved and + cleanup-pending attachment slots, for the same reason `activations_used` + does; a connection `DOWN` does not lower it before core confirms holder + cleanup; - `connections` counts accepted connections, reservation-free by nature. So `activations_used` may exceed `active_sessions` for as long as a call is in flight, and settles to it. Reporting the set alone would advertise headroom the very next call would refuse. -**At the attachment ceiling a `replace: true` is net-zero, and it reserves +**At the attachment ceiling a named replacement is net-zero, and it reserves that way.** A replacing attach ends one attachment and installs one, so it needs no free slot — but the daemon reserves before it calls core, and a naive reservation would refuse at 512 a request that leaves the count at 512. So a replacing attach takes an **atomic net-zero reservation**: in the daemon's -serial owner it claims the slot its own connection's prior attachment for that -session already holds rather than a free one, and it converts or releases that -claim through the same table every other reservation uses, so the count never -moves and no second caller can take the slot in between. A `replace: true` -from a connection that holds no prior attachment for that session is not -net-zero — core will install a second attachment rather than supersede one — -so it reserves ordinarily and is refused at the ceiling like any other attach. +serial owner it claims the slot held by the exact +attachment ID to which the connection's `replace: true` was mapped, and it converts or releases that claim through the +same table every other reservation uses, so the count never moves and no +second caller can take the slot in between. A stale, foreign-holder or +other-session core selector refuses and releases the claim; an ordinary +attach with no selector reserves a new slot and is refused at the ceiling. + +**Create reservations bind the request, not only the command identity.** The +reservation key retains `command_id` together with the canonical digest of all +creation inputs, including `session_options`. An exact retransmission may +coalesce behind the first ticket. Reusing the command ID with different input +refuses as a command conflict and never receives the first request's success. +The binding is retained until the relay has the real core result, so a caller +disconnect cannot free the slot while its create is still executing. **`session.acquire_control`** @@ -487,7 +399,6 @@ opaque. | --- | --- | --- | --- | | `daemon.stopping` | `reason` | one of the closed set below | required | | | `message` | bounded non-secret string | required | -| | `retry_after_ms` | `u64` | present **only** for `operator_stop` | | `daemon.notice` | `code` | closed set, today `"index_write_failed"` | required | | | `session_id` | binary identity | required | | | `message` | bounded non-secret string | required | @@ -501,7 +412,7 @@ errors answering one request: each carries that request's `request_id`, no | Code | Answers | Carries beyond the envelope | | --- | --- | --- | | `control_held` | `session.acquire_control` | **Nothing.** It does *not* carry the current epoch: an epoch is authority-shaped, and handing one to a client that was just refused is exactly the value it must not have. An earlier revision of ADR 0033 said it named the current epoch; that is withdrawn | -| `control_not_held` | `session.release_control` from a non-holder, **and every lease-authorized existing-session mutation whose combined admission gate fails** — any of the **five** conditions ADR 0033 lists: wrong connection, wrong epoch, a lease that is not `held`, a deadline already passed, or an attachment without controller capability. A request missing `writer_epoch` altogether is `invalid_request` instead, being malformed before the gate | **Nothing**, deliberately: the five conditions are indistinguishable on the wire, because saying which one failed would make the refusal an epoch and lease oracle. ADR 0033 fixes the gate; this is the one answer it has | +| `control_not_held` | `session.release_control` from a non-holder, **and every lease-authorized existing-session mutation whose combined admission gate fails** — any of the **five** conditions ADR 0033 lists: wrong connection, wrong epoch, a lease that is not `held`, a deadline already passed, or no live attachment for the pinned session. A request missing `writer_epoch` altogether is `invalid_request` instead, being malformed before the gate | **Nothing**, deliberately: the five conditions are indistinguishable on the wire, because saying which one failed would make the refusal an epoch and lease oracle. ADR 0033 fixes the gate; this is the one answer it has | | `control_pending` | `session.acquire_control` that waited out its deadline | nothing | | `control_capacity_reached` | any lease operation beyond the 512 concurrent-owner cap | nothing | | `session_dormant` | `session.attach` | nothing | @@ -530,27 +441,33 @@ added keys are enumerated so the digest covers them: ADR 0023's own framing and input ceilings are unchanged; these are additions beside them, and **all five** digest inputs therefore change in generation 2. -**A connection is pinned to one session, and both paths pin it.** The first -`session.attach` or `session.acquire_control` a connection completes fixes -which session that connection is about; every later call on it naming a -different session is refused with ADR 0023's existing **`invalid_request`** -(`0023-…-technical.md:304-307`) — the request is well-formed bytes but names a -session this connection is not about, which is an argument fault rather than a -lease or attachment one, so it is answered before any gate and never with -`control_not_held` or `not_attached`, neither of which would be true — and -the daemon's per-connection state is keyed by that one session rather than by -whatever the last frame said. Without the rule a connection could hold a lease -on one session and an attachment on another, and `control_owner_lost` — whose -close ends *the connection* — would take down an attachment belonging to a -session that had nothing to do with the lost owner. +**A connection reserves its one session before asynchronous work begins.** +Its state is `unbound`, `reserving(session_id, request_id, request_digest)` or +`bound(session_id)`. The first well-formed `session.attach` or +`session.acquire_control` changes `unbound` to `reserving` atomically in the +connection process **before** it asks the relay, existence query or core to do +anything. An exact retransmission with the same request ID and canonical +digest coalesces on that result. Any different request while reservation is in +flight, and every later request naming another session after binding, refuses +with ADR 0023's existing `invalid_request` before any gate or side effect. + +Success converts the reservation to `bound`. A definite refusal that created +neither attachment nor lease clears it back to `unbound`; an admitted relay +ticket keeps it reserved until the real result arrives, and an unaccounted +task makes the relay fatal rather than guessing. This closes the pipeline race +in which attach for one session and acquire for another could both pass while +the connection still appeared unpinned. Without the rule a connection could +hold a lease on one session and an attachment on another, and +`control_owner_lost` — whose close ends *the connection* — would take down an +attachment belonging to a session that had nothing to do with the lost owner. **`control_owner_lost` therefore carries `event_cursor` exactly when there was -an attachment to carry one for.** A connection that acquired and never -attached has no emitted cursor, and inventing one would be a lie about what it -received; the field is **absent** in that case and present otherwise, which -is an optional-field rule the DTO tables already have vocabulary for. Both -shapes are generation-2 vectors — one with the cursor, one without — because a -client parsing the record has to know that absence is legal. +an attachment to carry one for.** It is an ADR 0023 `error` record with +required `code`, bounded non-secret `message` and `session_id`. A connection +that acquired and never attached has no emitted cursor, and inventing one +would be a lie about what it received; `event_cursor` is **absent** in that +case and present otherwise. Both shapes are generation-2 vectors — one with +the cursor, one without — because a client parser must accept both. **Connections are bounded, and an earlier revision said they were bounded by the attachment ceiling, which they are not.** A client may connect, @@ -636,9 +553,12 @@ carry. | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for the remaining classes the plan's fatal-class map names, one per linked component: `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost` — eight in a daemon with artifact transfers and seven without. **`fatal:listener_lost` and `fatal:connections_lost` are not among them**: the listener is what would have written the record, and the connection registry owns the buffer-control interface it would have been written *through*, so no client can be told either reason. The plan's own class table says both, this set contradicted the first, and a later revision added `fatal:connections_lost` here without noticing it had the same defect. A lease owner's death is not among them: it closes one session's controller connection with `control_owner_lost` and ends no daemon. The startup classes carry no reason, because no socket exists when they occur, and neither does `owner_lost`, where the process that would write it is the one that is gone | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for a live-registry fatal class. The set includes `fatal:listener_lost`: listener loss stops new accepts but leaves the connection registry and existing sockets available, so the registry can make the bounded write and close them. The set excludes `fatal:connections_lost`: once that registry is gone there is no live inventory or buffer-control interface through which to write. On that class the owner closes the listener, synchronously cuts relay admission, stops the remaining components and halts; existing sockets close with the VM. The ordinary component reasons remain `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, and `fatal:relay_lost`. A lease owner's death is session-scoped and uses `control_owner_lost`. Startup classes have no socket, and `owner_lost` has no owner to write a record | | `message` | A bounded non-secret sentence for an operator to read | -| `retry_after_ms` | Present only for `operator_stop`, where a restart is expected; absent for every fatal reason, because the daemon does not know when the cause will be fixed | + +There is no `retry_after_ms`. Even on `operator_stop` the daemon does not know +when an external service manager or operator will start a successor, so any +numeric retry promise would be invented. **Its delivery is bounded best-effort, and the bound is one the daemon already has.** The daemon makes exactly **one** write attempt of the record into the @@ -666,7 +586,7 @@ limits — five inputs, and generation 2 changes **all five**: | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` and `daemon.notice` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, which is a startup exit class and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 keeps for the two **attachment** ceilings — `attachments_per_session` and `attachments_per_daemon`, the "stable reason when exhausted" the attachment-lifecycle list names — and no longer for the connection ceiling, which is enforced at `accept` and therefore reaches no `initialize` | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, `session_index_corrupt` or `session_index_upgrade_required`, which are startup exit classes and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 keeps for the two **attachment** ceilings — `attachments_per_session` and `attachments_per_daemon`, the "stable reason when exhausted" the attachment-lifecycle list names — and no longer for the connection ceiling, which is enforced at `accept` and therefore reaches no `initialize` | | **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `connections_per_daemon`, `initialize_deadline_ms`, `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | **`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 @@ -727,8 +647,8 @@ the whole of what was missing. `session.release_control` from a connection that is not the current holder or whose `writer_epoch` does not match, **and** every lease-authorized existing-session mutation that fails ADR 0033's combined check on holder -connection, epoch, `held` state, unexpired deadline or controller-capable -attachment. One code for all of them, carrying nothing beyond the envelope: +connection, epoch, `held` state, unexpired deadline or a live attachment for +the pinned session. One code for all of them, carrying nothing beyond the envelope: the refusals a client can provoke must not tell it whether a lease exists, whether its epoch was right or whether it was merely late, because that is an oracle for the value the gate protects. It is distinct from `control_held`, @@ -760,9 +680,11 @@ uncorrelated `error`**, with | Field | Value | | --- | --- | +| `type` | `error` | | `code` | `control_owner_lost` | +| `message` | bounded non-secret explanation | | `session_id` | the session whose lease owner died | -| `event_cursor` | the last completely emitted durable cursor for that attachment, exactly as `detached` carries it | +| `event_cursor` | optional; present exactly when this connection held an attachment, carrying that attachment's last completely emitted durable cursor exactly as `detached` does | It is uncorrelated because no request caused it. **Close behaviour:** it is one instance of the daemon-initiated detach rule below — the daemon writes the @@ -785,7 +707,7 @@ client in a state neither side had defined. So: | Occasion | Record written first | Then | | --- | --- | --- | -| The controller's lease owner died | `error`, `control_owner_lost`, with `session_id` and `event_cursor` | close that connection | +| The controller's lease owner died | `error`, `control_owner_lost`, with required `message` and `session_id`, plus `event_cursor` exactly when the connection held an attachment | close that connection | | Output-buffer or core-queue overflow | `error`, ADR 0023's `detached`, with `session_id` and `event_cursor` | close that connection | | Aggregate byte pressure chose this attachment | the same `detached` | close that connection | | Idle eviction at ten minutes | the same `detached` | close that connection | @@ -799,10 +721,11 @@ record — same code, same fields, same uncorrelated shape — and generation 1' use of it is untouched, so the foreground server's behaviour does not move and the ordered error list gains nothing for it. -**`event_cursor` is the same quantity in all four**: the **last completely -emitted durable cursor** for that attachment — the highest event sequence the -daemon finished writing to that socket, never one it had only encoded or -buffered. That is the position the client reconnects at, and delivery from it +**Where `event_cursor` is present, it is the same quantity in all four**: the +**last completely emitted durable cursor** for that attachment — the highest +event sequence the daemon finished writing to that socket, never one it had +only encoded or buffered. A controller connection that never attached omits +it. The cursor is the position the client reconnects at, and delivery from it is contiguous and at least once, so a duplicate at the seam is expected and a gap is a defect. @@ -824,42 +747,38 @@ are identical, which is deliberate, because why the daemon detached is an operator fact in its logs and not authority-shaped information a client acts on differently. -**`daemon_stopping`, the refusal after the admission cut.** An orderly stop -begins with a synchronous, acknowledged cut: the daemon's owner calls the -admission relay, the relay closes admissions and answers only once every -ticket it holds has **settled** — not merely been recorded, a recorded ticket -being a call still running — and nothing enters core through -the daemon after that answer. A connection that is still open — and every -connection is, because the cut precedes the closes — may still send a frame. -**Every** method is refused after it, whatever it would have done — the eight -lease-authorized mutations, `session.create`, `session.attach`, the queries, -and ADR 0023's three artifact-transfer methods alike — because the refusal is -about the daemon's state rather than about the request's effect. It is -answered with a **correlated** `daemon_stopping` carrying that request's -`request_id` and nothing else: no `event_cursor`, no session state, and it -closes nothing on its own. The connection is closed a moment later by step 3 -of the stop sequence, which is where a client is told the reason it is going -away; `daemon_stopping` answers the one request that arrived in between. - -The instant it names is the relay's acknowledgement, not the signal, and it -is an **admission instant and nothing more**. A command whose relay ticket was -recorded **before** the acknowledgement was admitted and is carried; one that -arrives after it is refused. The acknowledgement says nothing about whether an -admitted command has *finished*: the daemon waits for that separately, for a -bounded time, and its stop proceeds at that bound with anything still running -classified and fenced. An earlier revision of this passage said an admitted -command "has settled by the time it returns", which was the design the bounded -wait replaced and which a resume paging a long history defeats. Those are -the two witnesses, and they must give different answers on the same surface — -the connection's own reply stream. - -**`session_index_too_large` is not a wire code**, and an earlier revision -listed it as one. It is a **startup** refusal: the daemon exits non-zero with -that class before any socket exists, so no client can be holding a connection -to be told. It is removed from the generation-2 error inventory and stays in -the daemon's exit classes, where it belongs. - -**A failed directory write is a notification, not an error.** Generation 2 +**`daemon_stopping`, the refusal after the admission cut.** Every +post-initialize method request takes a linearized permit from the admission relay. For the ten +state-changing calls ADR 0033 names, the relay records a ticket and starts the +monitored core task before returning the permit. For queries and artifact +transfer calls it returns an unticketed permit; those calls grant no lease and +change neither Control nor the journal, but using the same gate removes a +connection-layer check/use race. + +An orderly stop sends `cut` to that relay. When the relay handles the message +it switches to closed and acknowledges immediately. The mailbox order is the +linearization order: a request admitted before the cut may enter or remain in +core and is allowed to finish; a request processed after the cut refuses with +the correlated `daemon_stopping` carrying its `request_id` and nothing else. +The acknowledgement means **no later request can be admitted**. It does not +mean admitted work has settled or that no pre-cut task will enter core after +the acknowledgement. The drain waits separately, to its absolute bound, for +the tickets that the cut returned as outstanding. + +The connection stays open until the later close phase, so a post-cut frame can +still receive its correlated refusal. That refusal closes nothing by itself; +`daemon.stopping` is the subsequent uncorrelated best-effort notice that names +why the connection is closing. The two witnesses deliberately differ: a +pre-cut request completes on its own terms, while the same request admitted +after the cut receives `daemon_stopping` and never invokes its facade. + +**Index startup failures are not wire codes.** `session_index_too_large`, +`session_index_corrupt` and `session_index_upgrade_required` all stop startup +before a socket exists, so no client can be holding a negotiated connection to +be told. They stay in the daemon's exit classes and out of generation 2's +ordered error inventory. + +**A failed discoverability-index write is a notification, not an error.** Generation 2 adds a **second notification record family**, `daemon.notice`, beside `daemon.stopping`: @@ -878,8 +797,9 @@ reachable regardless, and the daemon's own `stderr` keeps the operator's copy. It is never broadcast; other connections did not ask. The activation it follows **succeeded**: the session is usable and reachable -by ID, and only its directory entry and index row are missing, to be written -by the retry the plan already describes. Reporting that as an `error` would +by ID, and its persistent index row is missing, to be written by the retry the +plan already describes. The legacy directory entry is an independent rollback +artifact and its failure is logged separately. Reporting the index failure as an `error` would tell a client its command failed when it did not, and saying nothing would leave a session absent from `session.list` with no explanation. The family enters the digest's record-families input beside `daemon.stopping`. @@ -909,235 +829,137 @@ two refuse identically in effect — nothing created, nothing attached, no lease ### The session index, and what it may claim -`session.list` reads a daemon-owned index, never the session directory or the -store on the request path. What the index *is* follows from what it is built -from. `Loopex.SessionDirectory` holds plain files beside the log and states -that neither is Store durable truth; a host records an entry after -`create_session/3` commits, and that write can fail on its own — the reference -CLI reports exactly that failure to the operator. So there is a real crash cut -between a committed session and its directory entry, and a daemon rebuilt from -the directory can be missing a session the Store holds. - -The index therefore claims only what it can keep true, and each field is one -the daemon itself owns or reads once: - -- `session_id` and the recorded placement identity, read from the directory - entry at daemon start, or written when the daemon first activates a session - the directory does not hold; -- `residency`, a daemon fact meaning *this daemon activated this session in - this lifetime*, set to `active` at activation and never set back, because - activation is one-way. It is not a claim about a live coordinator; -- `controlled`, a daemon fact, updated on every lease grant, release and - expiry by the same lease owner ADR 0033 gives those transitions — **and on - that owner's death**, which is a fourth way a lease stops being held and - which an earlier revision left out. The daemon's owner process, which - observes the exit, clears `controlled` for that session as it closes the - controller attachment; a listing that still said `controlled: true` would be - naming a holder that no longer exists. - -**`residency` says what the daemon knows, not what core is doing.** Its two -values mean exactly: - -- `active` — **this daemon activated this session during this lifetime**; -- `dormant` — it has not. - -That is a daemon-owned fact, recorded by the daemon at the moment it acted, -and it is **true by construction**: nothing else has to hold for it to stay -accurate, and no other process has to tell the daemon anything. - -An earlier draft defined `active` as "the daemon holds a live coordinator", -which is a claim about core's state that the daemon has no way to keep -current, and then paid for it with a rule that took the whole daemon down when -a coordinator died. Both are withdrawn. The reason the first was untenable is -in the code: a coordinator is a `restart: :temporary` child of core's -`DynamicSupervisor`, and when one goes down `Loopex.Runtime.Control` consumes -the `DOWN`, releases the dispatcher fence and returns without altering the -session entry. No notification leaves core, and none is owed — that is core -minding its own supervision. - -**So a dead coordinator is surfaced by core's own refusal, not by the index.** -A client that sends the next command for that session gets core's existing -refusal, and the daemon forwards it unchanged, adding nothing and interpreting -nothing. The client learns at the moment it matters, from the component that -knows, and the listing never claimed otherwise: `residency: active` said this -daemon activated the session, which remains true. The activation ceiling still -counts activations per daemon lifetime, for the same reason — it counts what -the daemon did. - -Two alternatives were rejected, and both would be **a further core change** -beyond the six this milestone makes. A lifecycle notification from core to the daemon -would be a new core-to-host signal, with its own delivery and ordering -questions, added for a listing field. A monitorable coordinator handle handed -out to the daemon would export core's supervision topology across the boundary -and invite the daemon to reason about it. M5's core changes stay at six, and -neither of these is among them — the bounded listing this section adds is one -of the six, and a notification or a handle would be a seventh. - -ADR 0033's lease-owner rule is untouched by this and stays — and it is a -**session-scoped** rule, not a fatal one; this sentence said "fatal" from the -revision before that decision was taken. The -difference is ownership: a lease owner is a **daemon** process holding -daemon-only state that nothing can reconstruct, so losing it is the daemon's -failure to handle; a coordinator is core's, supervised by core, and its loss -is core's to report. - -Lineage, lifecycle state and last committed sequence are deliberately absent. -A daemon index cannot keep them current without reading the Store on the -request path or subscribing to every session it is not holding, and a field -that is silently stale is worse than an absent one; a client that needs them -attaches, and the snapshot carries them at a committed sequence. - -**The recovery procedure for the crash cut**, in four parts, needing no new -durable record and no Store read by the daemon: - -1. **Durable existence is learned from core, through a query that asks only - that.** The daemon never reads Store internals and never enumerates the log - to decide whether a session exists. It calls core's read-only - session-existence query on the ID — no attach, no resume, no side effect, - a plain-data answer — and treats core's answer as the proof. - - An earlier draft had the daemon learn existence from `attach` or `resume` - themselves. The maintainer rejected that on 2026-09-20 and admitted the - query instead. Asking a question by performing the operation is not a - question: `attach` establishes a cursor barrier and an attachment - incarnation, `resume` is a durable mutation under ADR 0008's placement - rules, and a daemon that had to run one of them to discover that a session - does not exist would be taking a side effect to learn a fact — worst of all - at `acquire_control`, which must validate existence *before* granting a - lease and must be safe to call on an ID that turns out to be unknown. - - **The query's result set is closed, and only one member is a yes.** "A - plain-data answer" is not a contract on its own — a caller has to know what - it may receive and what each result obliges it to do, especially a caller - about to grant authority on the strength of it. The query answers exactly - one of: - - | Result | Means | What the daemon does | - | --- | --- | --- | - | `present` | The root holds this session durably | Proceed: acquire may be granted, activation may follow | - | `absent` | The root does not hold it, and core is certain of that | Refuse, naming the session as unknown | - | `invalid_id` | The argument is not a well-formed session identifier | Refuse as an invalid argument, before anything is looked up | - | `store_unavailable` | Core could not read the root to decide | Refuse, naming the store as unavailable — **not** as an unknown session, because those are different facts and an operator acts on them differently | - | `unexpected` | Anything else, including a result shape the daemon does not recognise | Refuse, the same way as `store_unavailable`, because an answer that cannot be interpreted is not a yes | - - **Control acquisition proceeds only on `present`.** Every other result - fails closed and identically in what it leaves behind: no attachment, no - lease, no activation, no index row, nothing created. What differs is only - what the client is told, and the client is always told which — a refusal - that said "unknown session" when the store was unreadable would send an - operator looking for a session that exists. - - Nothing about the index is consulted to decide existence, which is why an - index that is incomplete is not a correctness problem, and the daemon still - reads no Store internals. - - Each of the five results is a witness: `present` granting, `absent`, - `invalid_id`, `store_unavailable` injected through the suite's controllable - fault store rather than by making the root unreadable — `Loopex.Store.Local` - answers `ownership_head` from memory, so an unreadable root does not produce - that result — - and `unexpected` injected by a stub that answers outside the set. All five - assert the same absence afterwards — no attachment, no lease, no activation - — and assert that the four refusals name distinct reasons. -2. **A client that never saw the session ID recovers by command identity, and - the sequence is written out here rather than left as a gesture.** At the - cut where the Store committed the creation and the process died before the - reply, the client holds no session ID at all — only the `command_id` it - chose for its own `session.create`. Every step below uses something the - client already has or something already durable: - - | Step | Who acts | What happens | - | --- | --- | --- | - | 1 | Client | Reconnects to the daemon and re-presents `session.create` with **the same `command_id`** it used before. It knows no session ID, so it cannot ask for one | - | 2 | Daemon | Forwards it as an ordinary create. It does not consult the index, which by construction may not hold this session | - | 3 | Core | Recognises the command identity as already resolved and returns the **historical result** — the same session ID it committed before — rather than creating a second session. This is the command idempotency the resume path already relies on, not a new mechanism | - | 4 | Client | Now holds the session ID for the first time. **No coordinator is running for it** — see below | - | 5 | Daemon | Validates durable existence with the read-only existence query on that ID, which answers `present` because the Store committed it in the first place | - | 6 | Daemon | Repairs what is missing: writes the directory entry and adds the index row, so every later `session.list` shows the session. If that write fails, step 3 of this procedure applies | - | 7 | Client | Acquires control, receiving the writer epoch | - | 8 | Client | Sends `session.resume` with a **fresh resume `command_id`** and that writer epoch. This is the step that activates the session: it is a new command, not a replay, because the create's identity is spent | - | 9 | Daemon | Activates the session — a live coordinator now exists — and counts it against the activation ceiling | - | 10 | Client | Attaches and drives | - - **Step 8 is the one an earlier draft left out, and without it the recovery - ends with nothing running.** Replaying a completed create does not start a - coordinator: `Loopex.Runtime.Control.create_session/4` resolves the - transaction, sees the command was already resolved, and replies `{:ok, - session_id}` on the `not fresh?` branch *without* calling `start_owner`. - That is correct — a replay must not create a second owner — but it means - steps 1 to 4 return an identity and nothing more. The session is durable - and idle. `session.resume`, with its own fresh command identity and under - the lease acquired at step 7, is what brings it back, and the sequence is - only a recovery once it reaches there. - - Steps 5 and 6 turn the recovery into a repair: the session is not merely - reachable once, it stops being missing. A client that *does* still hold the - session ID skips steps 1 to 4 and enters at step 5. - - **Its witness.** One case injects the exact cut — Store commit of the - create followed by process death before the directory write and before the - reply — then, from a client that never received the session ID, replays - `session.create` with the original `command_id` and runs the sequence to - the end. It asserts: exactly one session exists in the root; the returned - ID equals the committed one; the replay itself started no coordinator; the - existence query answers `present`; the directory entry and index row are - present afterwards and the session appears in `session.list`; the resume - under the granted epoch activates it, so a **live coordinator exists** and - the activation count has risen by one; and a prompt sent afterwards lands - on that session and produces its events, rather than on a second session or - on nothing at all. -3. **Recording can fail, and says so.** If writing the directory entry fails - during activation, the failure is reported to the client that triggered it, - as an explicit warning that this session will not appear in `session.list` - — the reference CLI already reports exactly that failure today. The - activation itself succeeds, the session is fully usable, and the daemon - **retries while it still holds the ID**, which is the only time it can: - - - immediately after activation, once; - - on each later command for that session, since the daemon has the ID in - hand at that moment anyway and the retry costs one file write it already - knows how to make; - - and when any later client reaches the session by ID, or replays its - create command, since both paths put the ID back in the daemon's hands. - - The retry stops as soon as it succeeds. Two earlier answers were wrong and - both are withdrawn. "At the next activation of that session" cannot happen: - activation is one-way, so within a lifetime there is no second one. "At the - next daemon start" cannot happen either, and for a sharper reason — a - restarted daemon builds its index *from the directory*, so a session the - directory does not hold is a session the new daemon has never heard of. It - has no ID to retry with. Only a live daemon that still holds the ID can - repair the gap, which is why the retry is bound to the moments it does. - - Until it succeeds, the session is reachable by ID and absent from - `session.list`, which is exactly what the client was told. -4. **A full index still activates.** If the index already holds 4,096 entries - and a client reaches an unrecorded session by ID, the session is activated - and is **not** recorded. Reachability never depends on the ceiling. What - changes is the listing's honesty: `session.list` then carries `index_full`, - so an operator is told the listing is incomplete rather than reading a - silent omission as an absence. - -`session.list` is documented as *the sessions this root records*, not *the -sessions this root contains*, and the operator documentation states all four -parts, because an operator who lost a terminal mid-creation is exactly who -meets them. - -A page is consistent with the index at the moment it is read, and no -consistency is promised across pages. What that can actually produce is -narrower than an earlier draft claimed, because the index is append-only -within a daemon's lifetime and keyed by unique session ID: rows are added, -never removed and never renumbered, and ordering is by session ID bytes. So a -session recorded between two page reads may be **missed** — if its ID sorts -before the cursor the client has already passed — and that is the only -anomaly paging can show. A row cannot vanish between pages and cannot be -returned twice, because nothing deletes a row and no two rows share an ID. A -client that needs a complete view pages again from the start; deduplication is -unnecessary here, though a client that deduplicates by session ID loses -nothing. A `limit` outside 1 to 256 or an `after_session_id` that is not -a well-formed session ID refuses with ADR 0023's existing `invalid_request`; an -`after_session_id` naming an unknown session is admitted and pages from its -byte position. +`session.list` reads a daemon-owned persistent discoverability index loaded at +startup. It never enumerates `sessions/` and never reads the Store on either +the startup or request path. This is a **maintained index**, chosen because the +supported OTP file API exposes `File.ls/1` as a complete list and supplies no +portable incremental directory iterator: wrapping that call in a function +which stops after 4,097 valid rows would still materialize every filename and +could inspect arbitrarily many malformed rows before reaching the bound. + +The file is `/daemon/session-index-v1`. It contains only durable +discoverability inputs: `session_id` and `placement_identity`. `residency` and +`controlled` are live daemon overlays and are rebuilt as `dormant` and `false` +at each start. The index is **not Store truth**. It neither proves existence nor +participates in create, resume, admission, replay or recovery. Core's read-only +existence query is the only yes/no authority the daemon uses for an exact ID. + +**The persisted format is bounded before parsing.** The file is canonical +UTF-8 JSON Lines with one version header, zero to 4,096 rows sorted by session +ID bytes, and one SHA-256 trailer over the exact header-and-row bytes. Header, +row and trailer keys and their order are fixed; unknown keys, duplicate or +out-of-order IDs, invalid identity alphabets and bad digests are corruption. +Each line is at most 1,024 bytes and the complete file is at most 4 MiB. The +daemon opens without following a symbolic link, checks the regular-file +identity and byte size before reading, reads no more than 4 MiB plus the +single byte needed to prove overflow, and checks the identity again after the +read. Oversize refuses `session_index_too_large`; malformed content refuses +`session_index_corrupt`. Both occur before socket bind. + +**Updates are atomic snapshots, not an append protocol.** The marker-holding +daemon serializes index changes, writes the complete next canonical image to a +mode-`0600` sibling created with exclusive creation, syncs that file, renames +it over `session-index-v1`, and syncs the `daemon/` directory before it reports +success. A crash before rename leaves the prior image; a crash after the +directory sync leaves the next one. Only a daemon that has acquired the Store +marker may remove an abandoned temporary. This adds no journal record and +changes no local Store byte. At 4,096 rows a new exact-ID session remains +usable but is not added; `session.list` reports `index_full: true` rather than +pretending completeness. + +A successful activation or exact-ID recovery adds the row after durable +existence is established. The row becomes visible in memory only after the +snapshot is durable. A failed index write does not reverse the session +operation; the causing connection receives `daemon.notice` with +`index_write_failed`, the daemon logs it, and later commands carrying that ID +retry the same idempotent write. A retry with the same placement is idempotent; +a different placement conflicts. The independent legacy +`SessionDirectory.record_session/3` write remains for foreground rollback and +may succeed or fail separately. + +**Upgrade is explicit so startup stays bounded.** A new root whose `sessions/` +directory does not exist gets an empty canonical index before bind. If +`sessions/` exists but the index does not, daemon startup performs only the +bounded `stat` needed to learn those two facts and refuses +`session_index_upgrade_required`; it never calls `File.ls/1`. The operator runs +`loopex daemon prepare-index` while no daemon or foreground server owns the +root. That offline command acquires the local Store marker, uses the legacy +session-directory enumeration, validates every non-temporary row, refuses +rather than truncates above 4,096 valid rows, writes the atomic index, and +releases the marker. Its scan is explicitly **not** a bounded service-start +operation: the command warns that legacy `File.ls/1` materializes the directory +and may need operator repair of a corrupt or oversized legacy directory. This +one-time cost is kept outside daemon availability rather than mislabeled as a +bound. + +Rollback needs no reverse migration. The M4 foreground server ignores +`daemon/session-index-v1` and continues using `sessions/`; the index may remain. +A later daemon reuses and validates it, but `session.list` never claims that a +row absent from this advisory index is absent from Store truth. If a foreground +server created sessions while the daemon was absent, the operator reruns the +offline import before relying on a complete discoverability view; exact-ID +access works regardless. Deleting the index is not a repair: on a root with +`sessions/` it restores the upgrade refusal and requires another explicit +import. + +The in-memory projection claims only facts its owners can keep true: + +- `session_id` and `placement_identity` come from the validated persisted row + or from an exact-ID operation after core answered `present`; +- `residency: active` means this daemon activated that session in this + lifetime; `dormant` means it has not. It never claims a coordinator is live; +- `controlled` is updated by the one lease owner on grant, release, expiry and + owner death. It names no durable controller. + +Lineage, lifecycle state and committed sequence are deliberately absent. A +client that needs them attaches and reads the snapshot anchored by core. + +**Recovery of an omitted row uses identity the client already owns.** Core's +existence query answers exactly `present`, `absent`, `invalid_id`, +`store_unavailable` or `unexpected`; only `present` permits an index write, +lease grant or later activation. The other four leave no attachment, lease, +activation or row and map to their distinct generation-2 refusals. + +A client that lost the create reply and therefore lacks a session ID recovers +in this exact sequence: + +1. Re-present `session.create` with the original `command_id` and byte-identical + creation inputs. +2. The daemon reservation verifies the canonical request digest and forwards + the replay without consulting the index. +3. Core returns the historical session ID; a changed request under that ID is + a conflict, not a coalesced success. +4. Replayed create starts no coordinator. +5. The daemon asks core's read-only existence query for the returned ID and + proceeds only on `present`. +6. It idempotently repairs the legacy directory entry and the daemon index row; + either write may report its own failure without changing Store truth. +7. The client acquires control and receives a writer epoch. +8. It sends `session.resume` with a fresh resume `command_id` and that epoch. +9. The daemon activates the session and charges the lifetime ceiling. +10. The client attaches and drives it. + +A client that already knows the session ID begins at step 5. If the index is +full, step 6 reports `index_full` and omits the row while steps 7 through 10 +remain available. The witness injects the Store-commit/before-reply crash cut, +runs all ten steps, and proves one durable session, no coordinator from the +create replay, a repaired row, one charged activation and a subsequent prompt +on the recovered session. + +A page is consistent with the in-memory index at the moment it is read and is +ordered by session ID bytes. Rows are added but never removed during one daemon +lifetime, so insertion before a page cursor can make a later page miss the new +row; rows do not vanish or repeat. A client that needs a refreshed view pages +again from the start. `limit` outside 1 to 256 and a malformed +`after_session_id` refuse `invalid_request`; an unknown but well-formed cursor +pages from its byte position. + +The startup witness places more than 4,096 valid legacy entries and an +arbitrarily large population of malformed names beside a valid bounded index, +and proves that daemon start reads only the index bytes and performs no +`File.ls/1` call. Separate cases prove oversize, digest failure, duplicate ID, +interrupted snapshot replacement, missing-index upgrade refusal, successful +offline import and foreground rollback with the extra file present. ### Session residency: active, dormant, and their bounds @@ -1155,7 +977,7 @@ durable distinguishes active from dormant, and neither is a claim about a live coordinator: both are daemon facts, recorded when the daemon acted. A dormant session costs less than an active one, but not nothing, and the -plan should not pretend otherwise. It holds one index row against the +plan should not pretend otherwise. If indexed, it holds one row against the 4,096-entry ceiling, and its history sits in the root's single append-only log against the 256 MiB capacity that every session in the root shares — so a dormant session still consumes the two resources whose exhaustion stops the @@ -1176,10 +998,10 @@ awaiting an answer, a recovery in progress, an unresolved `commit_unknown`, or an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and -none of M5's six core changes (concurrent attachment, the read-only existence -query, the trace exclusion, `quiesce/1`, the `disposition` and -`control_entry` fields on the detailed create and resume functions, and the -bounded session listing) stops a coordinator, +none of M5's five core changes (the complete concurrent-attachment lifecycle, +the read-only existence query, the trace exclusion, `quiesce/1`, and the +`disposition` and `control_entry` fields on the detailed create and resume +functions) stops a coordinator, so a deactivation call would be a further core change this milestone does not make. @@ -1210,33 +1032,15 @@ make. is the honest cost of leaving coordinator lifetime alone in M5. Lifting it needs a core deactivation operation that can tell "quiescent" from "idle", which is a decision of its own. -- **Index bound.** The index holds at most 4,096 **recorded** entries. A root - whose session directory holds more refuses at daemon start with a stable - reason naming the bound and pointing at root retirement, in the same posture - as `store_log_too_large`: refuse rather than serve a truncated view of what - the root records. The ceiling is on recorded entries only, and it never - makes a session unreachable — see the crash cut below. - - **Enforcing it needs a bounded read, and core does not have one.** The - listing the daemon builds its index from is core's: - `Loopex.list_sessions/1` (`loopex.ex:452-453`) calls - `SessionDirectory.list_sessions/1` (`session_directory.ex:231-266`: the head -at `:231`, the full read and sort at `:238-247`, the answer at `:249`, and the -invalid-root clause at `:266`), which - does `File.ls` and then reads **every** entry before sorting and returning. - A root holding a hundred thousand entries is therefore read in full before - the daemon can refuse at the four-thousand-and-ninety-seventh — a refusal - whose point is to avoid exactly that cost. So this milestone adds one - further narrow read to core and counts it: **`Loopex.list_sessions/2` - taking a bound and stopping after the bound-plus-first valid entry**, - answering what it read and whether it stopped early. The entries it returns - when it stopped early are in directory order, not a sorted prefix: the - arity-one form sorts only after it has read everything, which is the cost - the bound exists to avoid, so the bounded form cannot sort and does not - claim to. Its answer is the early-stop flag; the daemon reads nothing else - from it. It is read-only and additive — the arity-one form keeps its exact - meaning and its callers — and it is the smallest thing that lets the bound - be enforced rather than discovered. +- **Index bound.** The maintained index holds at most 4,096 recorded entries + and its complete persisted image is at most 4 MiB. Startup refuses an + oversize or corrupt index before bind; runtime discovery of an additional + exact-ID session sets `index_full` and leaves the session usable. The daemon + never scans the legacy session directory. A root that predates the index is + prepared explicitly by the offline import described above, which refuses + above 4,096 rather than writing a truncated image. This mechanism belongs to + the daemon adapter and removes the proposed `Loopex.list_sessions/2` change + from core. - **Homogeneity.** One state root is one host composition for the daemon's process lifetime. The daemon is composed once, with one workspace, policy, provider configuration and set of project resources, and serves every @@ -1395,54 +1199,41 @@ sequence and event ID. ### Evidence -Tests prove: two core attachments to one session keep independent live handles, -snapshots and cursors with no implicit replacement; an explicit `replace: true` -invalidates only the attaching process's own prior attachment for that session, -releasing its transfers, while every other connection's attachment to it -continues; an attachment released by its process exiting leaves no transfer -behind, which is accepted ADR 0028's requirement on the path that replaces the -only caller `release_transfers/2` has today; snapshot-then-contiguous at-least-once -delivery with no gap across the window boundary; the same delivery cases run -again with the resident window disabled, byte for byte identical, and with the -window dropped mid-stream, proving the cache establishes nothing; deterministic -reclamation in the fixed order above, including the case where zero-attachment -windows alone consume the aggregate ceiling and are released before any -attachment is detached; a slow observer detached at -its last emitted cursor — its `detached` record written best-effort and its -connection closed — while the controller and other attachments on their own -connections continue; -the per-session and per-daemon limits refusing independently; idle eviction, its close, and reconnect on a -fresh connection with no missing durable event and any duplicate deduplicated -by session ID, sequence and event ID; the three encoded-byte ceilings at maximum -attachment count and payload pressure enforced in the daemon-owned stages, -with process RSS observed and reported separately; a generation-1-only -initialize refused with `unsupported_generation` and nothing created; -simultaneous daemon starts on one root leaving exactly one listener with the -loser never touching the socket; Store-child failure closing the listener and -every connection before exit; `session.list` pages of at most 256 entries in -session-ID order with an exact continuation cursor, carrying only the four -fields above; a session committed to the Store whose directory entry was never -written — injected at exactly that cut — absent from the listing, still -reachable by ID, and present in every listing after the activation that -records it; a restarted daemon activating nothing until a client reaches for a -session; a detached long-running command and a pending admission each crossing -the idle deadline with every client gone and running to completion, so -dormancy is proved to release attachments and never a coordinator; the -activation ceiling refusing the 65th activation of a daemon lifetime with its -stable reason and restart remedy; a root whose directory holds more than the -recorded-entry bound refusing at start with its stable reason; at that bound a -session reached by ID activated, not recorded, and the listing carrying -`index_full`; a client that never saw a session ID recovering it through the -create command's durable `command_id`; a directory write failing at activation -reported to that client, the session still usable, and the record written by -the retry the next time the live daemon holds that ID — right after -activation, on a later command for the session, or when a client reaches it by -ID; a -recorded session the current composition cannot serve refused at activation by -name while every other session in the root activates; progress coalescing under -pressure with counted drops and no journal delay; peer-credential refusal; a -socket path beyond the bound refused at start; frame, fragment and -malformed-input refusals identical to the foreground server's. +Tests prove: two attachments from one embedded holder and attachments from two +holders keep independent handles, snapshots and cursors; named replacement +removes only its exact same-holder target and releases only that target's +transfers; a foreign, stale or other-session selector changes nothing; holder +death removes its complete attachment set in EventDispatcher and Control and +releases every transfer while another holder continues; the daemon retains +closing slots until relay settlement and `release_holder/2` acknowledgement, +so a replacement attach never crosses either count ceiling. + +The protocol suite proves the inherited boolean replacement remains byte- and +behavior-compatible in both generations and each adapter maps it to core's +exact target, a +pipelined attach and acquire cannot bind one connection to different sessions, +`control_owner_lost` vectors cover both optional-cursor shapes with the +required message, `fatal:listener_lost` reaches existing clients and +`fatal:connections_lost` does not claim a record, and the synchronous cut +admits pre-cut work while refusing every post-cut request. + +Replay evidence proves snapshot-then-contiguous at-least-once delivery with no +gap across enabled, disabled and mid-stream-dropped resident windows; bounded +reclamation, slow-client detach, idle eviction and reconnect leave other +attachments progressing; all count and byte ceilings refuse independently +with process RSS recorded; and progress is coalesced or dropped without a +journal delay. + +Index evidence proves startup reads at most the 4 MiB index image and never +enumerates `sessions/`, including with more than 4,096 valid legacy files and +arbitrarily many malformed names; oversize, corrupt, duplicate and interrupted +images fail or recover as specified; a missing legacy-root index requires the +offline import; foreground rollback ignores a valid index; paging carries only +the four fields and exact cursor; full-index exact-ID activation succeeds with +`index_full`; and command-ID recovery repairs an omitted row without creating +a second session. The transport cases also cover simultaneous starts, Store +loss, generation negotiation, peer authorization, socket-path bounds and ADR +0023 framing refusals. ### Alternatives @@ -1451,7 +1242,9 @@ check and invites remote exposure by misconfiguration; WebSocket and HTTP remain later transports under vision §18.8. An unbounded per-attachment queue was rejected because it lets one client grow coordinator-adjacent memory without bound. Keeping the M4 one-attachment-per-process rule was rejected -because a daemon's clients are processes by definition. A daemon-owned proxy +because a daemon's clients are processes by definition. Keeping one +attachment per holder was also rejected: an embedded holder may need several, +and a boolean replacement cannot identify one of them. A daemon-owned proxy fan-out was rejected because it would duplicate core cursor and queue ownership and need a second replay boundary to preserve the subscribe/snapshot race. Serving generation 1 on the daemon was rejected: its @@ -1463,7 +1256,12 @@ at-least-once with client deduplication, and a stronger daemon promise would create an expectation no other surface honors. Removing `session.list` was rejected on the same day because an observer without filesystem access to the root would have no way to discover sessions; the bounded page contract -above is the cost of keeping it. +above is the cost of keeping it. A bounded wrapper around `File.ls/1` was +rejected because the complete name list has already been materialized before +the wrapper can stop. A daemon-maintained index was selected instead of a +native directory iterator because OTP exposes no portable streaming iterator +on the supported platforms and the index changes neither Store ports nor +journal bytes. ### Compatibility and Rollback Mechanics @@ -1477,8 +1275,11 @@ server still serves generation 1 with one attachment in its process. The residency limits are server-enforced ceilings advertised at initialize under the existing `limits` member. Removing the daemon leaves the foreground server unchanged; existing embedded callers retain their behavior, and the core -supports independent same-session attachments. No durable record depends on -residency state or on the session index. +supports independent same-session and same-holder attachments. The new index +is a bounded daemon discoverability file only: no journal record, Store port, +session event or snapshot depends on it. Foreground rollback ignores it, while +an M5 daemon validates and reuses it. A legacy root is upgraded explicitly by +the marker-protected offline import; there is no reverse migration. Acceptance binds this complete pair at the exact candidate the maintainer names in the governance record. Its evidence and compatibility claims remain diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index 4b169db90..e2ee49ea8 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -41,7 +41,7 @@ control methods, the writer-epoch field ADR 0033 names, and **two** notification record families: `daemon.stopping`, carrying the reason a daemon is going away, and `daemon.notice`, carrying a bounded code for something an operator should know about a session whose command nonetheless succeeded — -today, an activation whose directory write failed. +today, an activation whose persistent discoverability-index write failed. The milestone that brings this ADR also renames the released generation-1 string to `loopex.experimental/1`, so the two generations are named on one scheme and @@ -57,10 +57,11 @@ connection closes whatever happened, so a client may learn of a shutdown only by its socket closing. It adds no durable method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core -has no durable stop command, and M5's six core changes — concurrent -attachment, a read-only existence query, the trace exclusion, the bounded -`quiesce/1`, the create and resume results' two new fields and a bounded -session listing — are none of them durable commands. Ending a client's involvement is releasing control and +has no durable stop command, and M5's five core changes — the complete +concurrent-attachment lifecycle, a read-only existence query, the trace +exclusion, bounded `quiesce/1`, and the create and resume results' two new +fields — are none of them durable commands. The daemon's bounded maintained +index is adapter state, not a sixth core change. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by acquiring control and attaching. @@ -70,17 +71,25 @@ ADR 0023's existing no-common-generation rule and nothing durable is created; generation-1 clients keep the M4 foreground server, whose wire, one-attachment rule and behavior do not change. A narrow core change lets distinct attachments to the same session coexist without replacing one -another: the same-session supersession that replaces them today becomes -**conditional on ADR 0023's existing `replace` flag** and narrows to the -attaching process's own prior attachment, and the dispatcher's release on that -process's exit takes over releasing the attachment's open transfers, which -accepted ADR 0028 requires of every detach and which that supersession is the -only caller of today. **ADR 0023 is unamended by this**: its `replace` field, -its refusal of an unnamed second attachment and the foreground server's -behaviour are all exactly what they were, one connection there holding one -attachment; the core continues to own their independent cursor barriers and -event-count queues, while the daemon owns per-connection socket output -buffers, the resident window and the residency ceilings. The socket path is +another, including several attachments owned by one embedded holder. Every +attachment has its own identity. Replacement therefore names the exact +`replace_attachment_id`; the target must belong to that holder and session, +and no boolean can choose among several candidates. The daemon still binds a +connection to at most one attachment, while embedded callers may hold a set. +The first attach or acquire tentatively reserves that connection's session +before asynchronous work begins, coalesces only an exact repeated request, and +rolls the reservation back only on a definite refusal. When a connection +ends, its attachment slots stay charged until the relay has accounted for its +tasks and core has acknowledged complete holder cleanup. +The foreground generation-1 and daemon generation-2 adapters translate their +existing per-connection `replace: true` onto the only attachment that each +connection may hold, so the wire remains unambiguous and ADR 0023 stays +unchanged. Core monitors the stable holder, removes all +of its attachments when it dies, and releases every transfer they opened as +ADR 0028 requires. The core continues to own each attachment's independent +cursor barrier and event-count queue, while the daemon owns per-connection +socket output buffers, the resident window and the residency ceilings. The +socket path is `daemon.sock` inside a `0700` daemon-owned subdirectory of the state root unless the operator names another, and a path beyond the platform bound is refused at start rather than truncated. The subdirectory exists so the daemon @@ -127,7 +136,11 @@ untouched. A connection holds one attachment, so there is nothing for it to do afterwards, and the close is what releases the attachment in core. Concurrent connections are themselves bounded, at 512, because a client that never attaches is bounded by no attachment ceiling. Transient progress is coalesced or dropped first and -never delays a journal transaction. +never delays a journal transaction. Listener loss leaves the connection +registry alive, so existing clients receive best-effort +`fatal:listener_lost` before close. Connection-registry loss leaves no live +socket inventory or writer, so the daemon closes the listener, cuts admission +and halts without claiming it delivered `fatal:connections_lost`. A session is *active* when **this daemon activated it in this lifetime** and *dormant* when the root holds it durably and this daemon has not — whether or @@ -156,12 +169,18 @@ next command for that session, which the daemon forwards unchanged. Lazy recovery is what a daemon can honestly promise on a store whose session directory is not Store truth and whose every open replays a full log. -`session.list` returns bounded pages, with an exact continuation -cursor, over a daemon-owned index of what the root *records* — identity, -recorded placement identity, active or dormant, controlled or not — and never -over what the Store contains, because no index built from the session -directory can claim that. Lineage, lifecycle state and committed sequence are -not list fields: a client that needs them attaches and reads the snapshot. +`session.list` returns bounded pages, with an exact continuation cursor, over +a bounded, daemon-owned persistent discoverability index — identity, recorded +placement identity, active or dormant, controlled or not — and never over what +the Store contains. Daemon startup reads only that size-capped index and never +enumerates the legacy session directory, so malformed or arbitrarily numerous +directory names cannot defeat the startup bound. An existing root without the +index requires an explicit offline import before the daemon serves it; the +import's legacy directory scan is intentionally outside the service-start +bound. The index is not Store truth and can omit a session committed across a +crash cut; exact-ID and command-ID recovery repair such an omission. Lineage, +lifecycle state and committed sequence are not list fields: a client that +needs them attaches and reads the snapshot. The proposed limits are exact and are bound at acceptance: 512 concurrent connections per daemon, thirty seconds for an accepted connection to complete `initialize` @@ -184,7 +203,10 @@ invites remote exposure by misconfiguration. Serving generation 1 from the daemon would need a second fencing path with no wire epoch, and its one exclusive connection per session is what the foreground server already provides. Keeping M4's one-attachment-per-process rule contradicts what a -daemon is for. An unbounded per-attachment queue lets one slow client grow +daemon is for. Limiting one holder to one attachment was rejected after the +maintainer selected embedded same-holder concurrency on 2026-09-20; a boolean +replacement flag cannot identify one member of that set. An unbounded +per-attachment queue lets one slow client grow coordinator-adjacent memory without bound. A daemon-owned proxy fan-out would duplicate core's cursor and queue ownership and need a second replay boundary to preserve the subscribe/snapshot race. Promising exactly-once replay was @@ -210,11 +232,14 @@ its generation are a protocol claim, so they need vectors and a compatibility proof: a generation-2 negotiation vector, refusal of a generation-1-only initialize, and an independent client over the socket. The residency rules are a durability and resource claim, so they need process fault injection and -bounded-resource negatives on real processes: simultaneous daemon starts, loss -of the store under a live listener, a slow observer detached at its last -emitted cursor, idle eviction and reconnect with no missing durable event, and -each count and byte ceiling refusing independently with observed process RSS -recorded beside it. +bounded-resource negatives on real processes: simultaneous daemon starts, +loss of the store under a live listener, two attachments from one embedded +holder remaining independent, an explicit replacement removing only its named +target, holder death releasing the holder's complete attachment and transfer +set, a slow observer detached at its last emitted cursor, idle eviction and +reconnect with no missing durable event, bounded-index startup independent of +legacy directory population, and each count and byte ceiling refusing +independently with observed process RSS recorded beside it. Technical depth: [Contract and evidence](0032-daemon-attachment-residency-and-replay-technical.md#technical-adr-0032-decision). @@ -231,10 +256,12 @@ at initialize that this daemon does not serve it, and the foreground server still does. The public protocol remains experimental with exact-generation agreement and no mixed-generation stream promise. -Rollback is the M4 foreground server on the same local store: the daemon -carries no residency state, so removing it loses nothing durable. The numbers -are safety ceilings the M5 tests must show are enforced, not measured service -promises. +Rollback is the M4 foreground server on the same local store: it ignores the +daemon's bounded discoverability index, and no Store record, event or snapshot +depends on that file. Removing the daemon loses only live residency and lease +state. An existing root enters M5 through the explicit marker-protected +offline index import; no reverse migration is needed. The numbers are safety +ceilings the M5 tests must show are enforced, not measured service promises. Technical depth: [Compatibility mechanics](0032-daemon-attachment-residency-and-replay-technical.md#technical-adr-0032-compatibility). diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 36793f3c8..60a9ade58 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -41,23 +41,23 @@ epoch does, which is which client may drive. One owner process per session serializes every lease read, grant, renewal, release and expiry transition with that session's mutation-admission handoff, so a takeover cannot pass a mutation whose holder check has already started -but whose core admission is unresolved; that admission first resolves, or the -daemon's own holder-and-epoch check refuses it before it ever reaches core. +but whose relay ticket is unresolved; the relay accounts for that admission +first, or the daemon's own holder-and-epoch check refuses it before it ever +reaches core. A revision of 2026-09-20 proposed collapsing these into one process for the daemon holding a record per session. The maintainer rejected that on -2026-09-20 and kept the process per session: the process *is* the -serialization boundary and the holder of that session's in-flight admission -set, and collapsing it would put every session's lease transitions behind one -mailbox. The plan's companion states the population and its bound. +2026-09-20 and kept the process per session: the process *is* the lease +serialization boundary and failure-isolation unit, while the fixed relay owns +the cross-owner ticket ledger. Collapsing the lease owners would put every +session's lease transitions behind one mailbox. The plan's companion states +the population and its bound. **A lease owner's failure ends that session's collaboration state, not the -daemon**, on the maintainer's decision of 2026-09-20. The owner holds the -session's in-flight admission set in its own memory, and that set is the basis -of the expiry rule below: a takeover is granted only when it is empty. An -owner that dies takes the set with it, so no successor owner can inherit it — -and none tries to. What happens instead is exactly what happens when a lease -is gone by any other route: +daemon**, on the maintainer's decision of 2026-09-20. The owner loses its +transient lease record, but it does not take admitted work with it: the fixed +relay retains the session's ticket set and a successor queries that set before +grant. What happens is: - the daemon writes `control_owner_lost` to that session's **controller** connection and closes it with its attachment, under the daemon-initiated @@ -66,55 +66,61 @@ is gone by any other route: holds no lease, is on a connection of its own and loses nothing; - the lease itself is gone, held by nobody; - the next `session.acquire_control` for that session starts a **fresh** - owner, holding no lease and no admission set, and mints a **fresh epoch** — - the same takeover mechanics this ADR already defines for a lease that has - been released. + owner holding no lease, waits until the relay reports no unresolved mutation + ticket for the session, and then mints a **fresh epoch**. -The fresh epoch alone is **not** what makes the lost set harmless, and an +The fresh epoch alone is **not** what orders the old and new tenures, and an earlier revision of this section said it was. It stops a *later* command from -the old tenure, which is a different thing from ordering: a successor's first -call could still reach a coordinator ahead of an older call that was already -on its way, because core orders what it receives rather than what is in -flight, and core never sees the writer epoch at all. +the old tenure, which is different from accounting for a call already on its +way. The relay's retained ticket is what keeps a successor's first call from +overtaking that older call; core orders what it receives and never sees the +writer epoch. **The daemon closes that window with one fixed process, the admission relay**, -added on the maintainer's decision of 2026-09-20. Every **lease-authorized -existing-session mutation** — the set this pair lists below, each carrying -`writer_epoch` and admitted only from the recorded holder — is routed through -it, and so are two calls that carry no epoch: `session.create`, whose ticket -the connection process takes because no lease owner exists for a session that -does not exist yet, and `session.attach`, whose second leg mutates the -runtime's dispatcher. Ten in all. Nothing else is: reads are not ticketed, -since a read grants nothing, orders nothing, and a -blocking read would otherwise hold a takeover -for as long as an observer sat on it — and neither are ADR 0023's three -artifact-transfer methods, which do write per-attachment dispatcher state but -touch neither `Control` nor the journal, so they cannot disturb what a drain -enumerates. The plan's companion states that boundary and what becomes of a -transfer in flight at the cut. Neither the create ticket nor the attach -ticket blocks a grant — the first names no session yet, the second grants -nothing a successor could overtake — and both exist so that the -daemon's orderly stop can close admissions with an acknowledgement covering -**every** call that changes core state, which a relay they bypassed could not -give. The plan's companion owns that cut. - -The lease owner — or, for a create, the connection process — **calls** the -relay and waits for the acknowledgement before -the core call is made, so no mutation exists that the relay has not recorded; -the relay **monitors** every lease owner, so the BEAM's per-sender message -ordering puts every ticket an owner sent ahead of that owner's `DOWN`; it -survives lease-owner death, being fixed rather than per-session; and **a -replacement owner's first grant for a session blocks until that session's -outstanding tickets have settled**. - -A ticket settles **only** when the relay has the call's real outcome — its -task returning core's answer, refusal included. A task that dies **without** -one settles nothing and keeps its ticket: a delivered call completes whether -or not its caller lives, so a dead task says nothing about whether core -received the mutation, and the relay exits `relay_lost` rather than admit a -successor over a mutation it can no longer account for. A connection -disappearing settles nothing either, because the call it made is still -running. +added on the maintainer's decision of 2026-09-20. Every post-initialize method +request takes an admission permit from it, which gives orderly stop one linearization point. +Ten calls also take retained tickets: the eight lease-authorized core mutations +that carry `writer_epoch`, `session.create`, and `session.attach`. Reads and the +three artifact-transfer methods take unticketed permits: they grant no lease, +touch neither Control nor the journal, and cannot disturb the session census, +but sharing the permit gate prevents them from slipping past a connection-side +check while the relay cuts admission. + +For a lease-authorized call, the per-session lease owner validates the combined +gate and sends the complete core-call descriptor to the relay. For create, the +connection sends the descriptor and its request-bound activation reservation. +For attach, the connection sends its stable holder pid and reserved attachment +slot; the relay task invokes `Runtime.attach_for_holder/4`, so the task that +executes the call never becomes the lifetime holder. In every ticketed case the +relay performs this sequence before its caller receives an admission reply: + +1. allocate and retain the ticket row, including session where one exists, + request identity and canonical request digest; +2. start and monitor the task that will make the core call; +3. only then answer `admitted` with the ticket identity. + +The task can begin or even finish before the acknowledgement is delivered; +what cannot happen is an acknowledged mutation with no retained ticket or no +started, monitored executor. That is the maintainer's selected order. A +connection or lease owner that dies after acknowledgement does not cancel the +core call. The relay keeps the ticket until the task returns the real core +result, refusal included, and routes the result to the connection only if it +still exists. + +A task that dies without a result settles nothing. The relay cannot infer +whether core received the call, so it exits `relay_lost` and makes the daemon +fail-stop rather than delete the ticket or grant a successor over it. The relay +monitors every lease owner; signal ordering puts a ticket request an owner sent +before the corresponding owner `DOWN`. A replacement owner's first grant for +a session waits until that session's mutation tickets settle. Create names no +existing session and attach grants no control, so neither blocks an unrelated +lease grant; both remain visible to the drain. + +The relay's `cut` changes it to closed and acknowledges immediately. Requests +linearized before the cut retain their permits and may enter or remain in core; +requests processed after it refuse. Ticket settlement is a separate bounded +drain step. This is an admission cut, not a claim that every admitted call has +finished or that no pre-cut task can enter core after the acknowledgement. So the ordering claim rests on the relay, and the session-scoped rule gives the rest: the successor is granted a fresh epoch, the dead controller's @@ -126,7 +132,7 @@ nothing of it is still unaccounted for. An earlier draft had the daemon restart the owner and carry on with its sockets intact, and a 2026-09-20 revision made the failure fatal to the whole daemon instance. Both are superseded: the restart was wrong because a -restarted owner would claim an admission set it cannot know, and daemon-fatal +restarted owner would claim the lease record it cannot know, and daemon-fatal was the smaller design the maintainer declined on 2026-09-20 — it ends every other session's work for one session's fault, where the relay ends none of it. @@ -150,13 +156,12 @@ lease is free, no acquisition is waiting, and the relay holds no outstanding ticket for that session — all three, since any one alone would retire an owner something still depends on. -Retaining the in-flight set in a survivor was the alternative and was -rejected: whichever process held it would then be the process whose failure -loses it, so the window moves up one level rather than closing, and a daemon -that cannot lose the set is a daemon that has made the set durable — a durable -lease record by another name, which this decision rejects for its own -reasons. The relay is not that: it holds no lease and no authority, only the -fact that a call it made has not yet been accounted for. +Retaining the **lease** in a survivor was rejected: it would make a replacement +process claim collaboration state it cannot reconstruct. The relay retains +only tickets for calls it itself started, holds no lease or authority, and is +not restarted. Its own failure is daemon-fatal, which is the fail-closed edge +that lets its volatile accounting be sufficient without turning it into a +durable lease record. **One lease per connection.** A connection holds at most one controller lease at a time, so a client that wants to drive two sessions opens two connections. @@ -250,7 +255,7 @@ the local store's writer marker, unchanged. not reached, because there is nothing well-formed to put through it. The daemon admits it only if the sending connection is the recorded holder, the epoch matches, the lease state is `held`, the deadline is later than the live daemon's monotonic admission time, and the - connection holds a controller-capable attachment, except that a verified + connection holds a live attachment for its pinned session, except that a verified dormant session's `session.resume` may precede attach under that connection's held lease. The check and core handoff are serialized against lease transitions for the session. @@ -258,7 +263,7 @@ the local store's writer marker, unchanged. **Every way that gate can fail answers one code, `control_not_held`, and it says nothing about which condition failed.** The gate has five conditions — holder connection, epoch equality, `held` state, unexpired deadline, - controller-capable attachment — and an earlier revision required each of + live attachment for the pinned session — and an earlier revision required each of them without naming the result any of them produces, which left the one refusal a client actually meets undefined and ADR 0032's error table incomplete. It is deliberately **non-oracular**: a stale epoch, a copied @@ -270,7 +275,8 @@ the local store's writer marker, unchanged. must not be. It refuses before core admission and before any session write, carries the request's `request_id` and nothing else, and changes nothing about the current holder's lease, epoch or deadline. Queries and attach - carry no epoch and pass no gate. + carry no epoch and pass no **lease** gate; they still take the relay permit, + and attach takes a relay ticket under the rule above. **Five conditions, six cases**, and the mapping is written out so the two numbers stop reading as a disagreement: @@ -282,7 +288,7 @@ the local store's writer marker, unchanged. | A mutation from a connection that never acquired | holder connection | | A mutation after `session.release_control` | `held` state | | A mutation after the term elapsed | unexpired deadline | - | A mutation from a connection with an observer-only attachment | controller-capable attachment | + | A mutation from the holder connection after its attachment ended, or before it attached | live attachment | The witnesses assert each case separately in the daemon's own state — which condition it constructed — and assert that all six produce the @@ -297,7 +303,7 @@ the local store's writer marker, unchanged. constraint is on the first mutation, not on the two calls that precede it, and that mutation refuses unless the sending connection is the holder, the epoch matches and the connection - holds a controller-capable attachment. + holds a live attachment for its pinned session. - **Only an explicit release releases early.** A successful `session.release_control` from the holder frees the lease at once. Every other way a connection ends — an orderly close, an EOF, a killed client, a @@ -315,21 +321,21 @@ the local store's writer marker, unchanged. ### Expiry against an in-flight admission Two rules above meet at the deadline and their order has to be stated, not -left to the implementation. The lease owner serializes a lease -transition against a mutation whose holder check has already started, so a -takeover cannot pass an admission core has not yet resolved; and takeover is -admitted at expiry with no grace. The linearization rule is: - -1. A mutation whose holder, epoch, state and deadline check *completed* while - the deadline was still in the future is **in flight** and settles under - that lease, even if the deadline passes while core's admission is - unresolved. It completes or fails on its own terms; it is neither retried - nor fenced by the expiry. +left to the implementation. The lease owner serializes the gate and relay +ticket handoff against lease transitions; the relay then retains the admitted +call until its real result. Takeover is admitted at expiry with no grace. The +linearization rule is: + +1. A mutation whose holder, epoch, state, deadline and attachment check + completed while the deadline was still in the future, and whose relay + ticket was admitted, is **in flight** and settles under that lease even if + the deadline passes while core is unresolved. It completes or fails on its + own terms; it is neither retried nor fenced by the expiry. 2. At the deadline the lease state becomes `expired` and the holder gains nothing further: every mutation whose check begins at or after the deadline refuses, including one from the holder, and renewal no longer extends it. 3. A takeover becomes **eligible** at the deadline and is **granted** only - once every in-flight mutation for that session has resolved. Until then the + once the relay reports every mutation ticket for that session settled. Until then the acquire waits, bounded by the acquiring request's own deadline; a wait that exceeds it refuses with **`control_pending`**, the stable reason ADR 0032's generation-2 error inventory carries for exactly this case, and the client @@ -379,9 +385,13 @@ is itself command authority. Tests prove: exactly one controller with observers within the ADR 0032 bounds; a stale epoch, copied current epoch, non-holder connection, released state -and expired state each refused before core admission with the current +expired state and a holder lacking a live attachment each refused before core admission with the current controller unaffected; a lease transition racing command admission preserves -this order; the expiry linearization above, with a mutation blocked inside +this order; every ticketed call has both its retained row and monitored task +before the sender receives `admitted`; attach's task uses the connection as +stable holder; killing that task before a result makes the relay and daemon +fail-stop; a cut answers immediately, carries pre-cut calls to their real +results, and refuses every post-cut permit; the expiry linearization above, with a mutation blocked inside core across the deadline settling under its own lease while the eligible takeover waits and is granted only after it resolves, the holder's next mutation refused at the deadline, the acquiring request refusing with diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index 8cda27f03..d46a3447f 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -29,7 +29,9 @@ record. Every other attachment is an observer: it receives the same snapshot and events and may not admit a command. For an existing session, the daemon admits a mutation only when the sending connection is the current holder, its supplied writer epoch matches, the lease is held and unexpired, and the -attachment has command capability. The daemon checks those facts together +connection has a live attachment for its pinned session. Attachments carry no +controller capability: the lease is the only controller role, and any live +attachment satisfies the liveness condition. The daemon checks those facts together before core admission and serializes that handoff with lease changes; an observer cannot reuse an epoch it learned from a result or status. `session.create` is the one exception because no session lease exists yet: @@ -43,7 +45,7 @@ attaches to that session; what is fixed is that no existing-session mutation is admitted until the lease is held by the sending connection, its epoch matches, and — with the single exception of `session.resume` on a verified dormant session — that connection holds a -controller-capable attachment. So a newly created session is driven by +live attachment for the pinned session. So a newly created session is driven by attaching and acquiring in either order and then sending the first command with the granted epoch, and a known dormant session is driven by acquiring by ID, resuming with the granted epoch and attaching. A @@ -84,6 +86,19 @@ have resolved. That adds no grace, because the expired holder can only finish what it had already begun. Writer exclusion between two daemons on one state root stays the local store's writer marker, unchanged. +One fixed admission relay makes that ordering survive a lease owner's death +and gives shutdown one cut. Every post-initialize method request linearizes +there. The eight +lease-authorized core mutations, `session.create` and `session.attach` also +take retained tickets: the relay records the ticket and starts its monitored +core task **before** it answers that the request was admitted. Attach's task +uses the connection pid as an explicit stable holder, so relay execution does +not transfer attachment lifetime to the task. A relay cut acknowledges as +soon as it closes admission; calls admitted before it may finish, calls after +it refuse, and ticket settlement is the drain's separate bounded wait. Relay +loss is daemon-fatal because no process may guess what its missing ticket set +contained. + **Alternatives rejected.** Putting the lease in core was rejected because the vision keeps collaboration policy above core and another host may choose a different rule. Last-writer-wins without an epoch was rejected because a @@ -95,18 +110,16 @@ requires the holder connection, so durability could only preserve a counter nothing needs. A counter-based epoch scoped to the daemon incarnation was rejected on 2026-09-14 because a lease-owner restart under the same incarnation would mint values already issued. Restarting a failed lease owner -beneath live sockets was rejected on 2026-09-20, on an independent review's -finding: the owner holds the session's -in-flight admission set, a takeover waits on that set being empty, and a -restarted owner cannot know what it has forgotten. Retaining the set in a -survivor moves the same window one process up; making it survivable at all -would mean making it durable, which is the durable lease record this decision -already rejects. +beneath live sockets was rejected on 2026-09-20 because it would claim a lease +record it cannot reconstruct. The fixed admission relay retains only the +tickets for calls it started, never the lease; its loss is daemon-fatal rather +than reconstructed, so the ticket ledger needs no durable record. **Implementation and milestone-closure evidence.** This is a trust claim, so its class is negative tests on real processes plus a security reading of the admission path: every refusal — stale epoch, copied current epoch, non-holder -connection, released lease, expired lease, observer abort — proved before core +connection, released lease, expired lease, holder without a live attachment, +observer abort — proved before core admission and before any session write, a controller killed mid-run fenced after takeover, a lease owner killed while a mutation is in flight taking neither the daemon nor any other session down — its controller's connection sent From f89e9c97b723e0e3333ad7c6cb2ffff38adb6955 Mon Sep 17 00:00:00 2001 From: Sandeep Puri Date: Mon, 21 Sep 2026 08:24:28 -0700 Subject: [PATCH 190/585] docs(M5): checkpoint audit corrections --- .agents/skills/adr/SKILL.md | 8 +- .agents/skills/close-milestone/SKILL.md | 24 +- .agents/skills/open-milestone/SKILL.md | 7 +- AGENTS.md | 21 +- CHANGELOG.md | 4 +- DEVELOPMENT.md | 8 +- README.md | 22 +- docs/README.md | 2 +- ...store-selection-and-migration-technical.md | 256 +- ...mon-grade-store-selection-and-migration.md | 109 +- ...tachment-residency-and-replay-technical.md | 1945 ++++++- ...-daemon-attachment-residency-and-replay.md | 183 +- ...controller-lease-and-takeover-technical.md | 1000 +++- ...aboration-controller-lease-and-takeover.md | 100 +- ...andoff-over-bootstrap-channel-technical.md | 1463 ++++- ...edential-handoff-over-bootstrap-channel.md | 310 +- docs/adr/README.md | 3 +- docs/developer/README.md | 3 +- docs/developer/agent-context-map.md | 72 +- docs/developer/milestones-technical.md | 78 +- docs/developer/milestones.md | 35 +- docs/developer/verification-technical.md | 8 +- docs/developer/verification.md | 6 +- docs/plans/M5-technical.md | 5116 ++++++++++++----- docs/plans/M5.md | 1146 ++-- docs/plans/README.md | 33 +- docs/roadmap-technical.md | 2 +- 27 files changed, 9214 insertions(+), 2750 deletions(-) diff --git a/.agents/skills/adr/SKILL.md b/.agents/skills/adr/SKILL.md index 91f7ff12a..b608e9805 100644 --- a/.agents/skills/adr/SKILL.md +++ b/.agents/skills/adr/SKILL.md @@ -56,9 +56,11 @@ ownership, anchors, reciprocal links, and review form. the exact candidate/concept-digest/technical-digest form defined in `docs/plans/README.md`. The digests bind both historical Proposed files. Do not change decision or technical bytes in that transition. Within the pair, - only Status and the empty row change; the same commit updates the plans - index's derived Current Status capsule when the ADR is a blocker, and it is - reviewed before merge like every other change. + only Status and the empty row change; the same commit updates that ADR's + status cell and every directly superseded ADR's supersession annotation in + `docs/adr/README.md`, and the plans index's derived Current Status capsule + when the ADR is a blocker. The transition is reviewed before merge like + every other change. 6. Dropping a required check or a real-path test, deferring scope, or reversing a vision boundary requires the maintainer's explicit approval under `AGENTS.md`; an ADR cannot grant that authority. diff --git a/.agents/skills/close-milestone/SKILL.md b/.agents/skills/close-milestone/SKILL.md index 7d57a3688..8553c6905 100644 --- a/.agents/skills/close-milestone/SKILL.md +++ b/.agents/skills/close-milestone/SKILL.md @@ -29,8 +29,10 @@ technical guidance. The process is the Retain each run's complete output outside the repository, with its stable retained-output reference, SHA-256 digest, tested implementation SHA, platform, and toolchain. Step 5 writes those identities, references, and - digests into the existing evidence-page scaffold: the runs are of the - candidate, and the candidate cannot carry its own later results. + digests into the existing evidence-page scaffold, together with every + plan-required outcome field or placeholder that scaffold predeclared: the + runs are of the candidate, and the candidate cannot carry its own later + results. 4. Ask an independent reviewer to read the candidate for outcome compliance, correctness, test honesty, public impact, security, and rollback. Retain the complete review report outside the repository under a retained-output @@ -38,17 +40,25 @@ technical guidance. The process is the 5. Present the packet to the maintainer: outcomes and their proof, check results, review findings, and what remains. The maintainer closes it; then make the **administrative closure commit**, which is - [confined to four paths](../../../docs/developer/milestones-technical.md#technical-milestones-confinement): + [confined to five paths and the exact allowed region in each](../../../docs/developer/milestones-technical.md#technical-milestones-confinement): the register row moved to `Closed`, the plan's Closure row naming the **tested implementation SHA** and the content digests — not this commit, which cannot contain its own hash and is located by the register transition - instead — the context-map disposition, and the existing evidence page filled - with step 3's runs and step 4's review. Nothing else belongs in it; in particular, - `docs/evidence/README.md` does not change in the administrative commit. + instead — the context-map disposition, the existing evidence page filled + with step 3's runs, step 4's review and every predeclared plan-required + outcome value, and the root `README.md` updated only + between its status markers to the exact canonical `Closed` block constructed + from the register under the status contract. Run `mix loopex.status` to + validate that block; the task reports pass or failure rather than printing + replacement bytes. Retain and inspect the complete patch, mapping every + changed byte to the guide's allowed-region table. Nothing + else belongs in it; in particular, `docs/evidence/README.md` does not change + in the administrative commit. Tags, packages, and publication are separate maintainer decisions. If the maintainer later authorizes a tag, follow the milestone guide's release -sequence. Run the documentation check, the final semantic operator/developer +sequence. Re-prove the five-path and allowed-region confinement, then run +the documentation check, the final semantic operator/developer documentation gate, and the archive comparison on the administrative SHA before creating the tag. Retain those outputs outside the repository and put their results, retained-output references, and SHA-256 digests in the diff --git a/.agents/skills/open-milestone/SKILL.md b/.agents/skills/open-milestone/SKILL.md index 3fd264df6..0a8c1f928 100644 --- a/.agents/skills/open-milestone/SKILL.md +++ b/.agents/skills/open-milestone/SKILL.md @@ -32,9 +32,10 @@ technical guidance. The process is the 4. Add the row to the register in `docs/plans/README.md` as `Open`, with the pair's links and `—` in the Gate column. That row is the pair's index; nothing else lists it. Every Progress and Evidence row reads `Open`. -5. Run `mix loopex.status`: it derives the Current Status capsule and the root - `README.md` summary sentence from the register and prints the exact values - it expects. Update both in the same change. +5. Construct the Current Status capsule and root `README.md` summary from the + register under the status contract, then run `mix loopex.status` to validate + them. The task reports pass or failure rather than printing replacement + bytes. Update both in the same change. 6. Run `bash scripts/check.sh --docs`. 7. Present the plan to the maintainer with every decision it needs. Acceptance is theirs; record it by moving the row to `Accepted`. diff --git a/AGENTS.md b/AGENTS.md index 04f78ba14..e6e971f80 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -177,8 +177,10 @@ A milestone runs in four steps; the of the first, so the second writes them down, and the Closure row names the first, because that row is the second's own content. The administrative SHA is located by the register's `Closed` transition and by the tag. It is - confined to four paths — register row, Closure row, context-map entry, - the existing evidence-page scaffold — + confined to five paths and to the exact administrative region in each — + register row and generated status block, Closure row, appended context-map + disposition, designated evidence-scaffold placeholders, and the root + README's marked derived-status block — which the [milestone guide](docs/developer/milestones-technical.md#technical-milestones-confinement) states once. Complete run outputs are immutable outside the repository; the @@ -186,12 +188,15 @@ A milestone runs in four steps; the 4. **Release.** Publication, tags, and packages are separate maintainer decisions that reuse the closure evidence when the source is unchanged. The tag names the **administrative** closure SHA. Before creating it, verify that - the diff from the tested SHA is confined to those four paths. Then run + the diff from the tested SHA is confined to those five paths and allowed + regions by retaining and reviewing its complete patch. Then run `bash scripts/check.sh --docs`, the final semantic review of the relevant `docs/operator/` and `docs/developer/` pages, and the archive comparison on - the administrative SHA. Every non-documentation archive entry except - `SOURCE_IDENTITY` matches the tested archive; validate each archive's - `SOURCE_IDENTITY` against its own commit. Retain the complete outputs outside + the administrative SHA. Every non-documentation archive entry except the + root `README.md` and `SOURCE_IDENTITY` matches the tested archive; the root + README is validated as an exact marked-block replacement by the content- + confinement proof and by the documentation/status gate, and + each archive's `SOURCE_IDENTITY` is validated against its own commit. Retain the complete outputs outside the repository and put their results, retained-output references and SHA-256 digests in the immutable annotated tag when it is created. Do not amend the evidence page or create a third commit. No suite or release check @@ -246,7 +251,9 @@ repository's checks are two commands, described in workflows, the independent Node client, the fresh-source archive build, and the long-duration bound proofs the fast check excludes. It needs a provider credential in `LOOPEX_PROVIDER_API_KEY`, pinned Node and a clean tree, two of - its tests are attended, and it runs before closure and release. + its tests are attended, and it runs only once for the candidate before + closure. An unchanged-source release reuses that evidence and runs only the + pre-tag administrative-SHA proofs. Both run locally from a clean checkout with the toolchain in [DEVELOPMENT.md](DEVELOPMENT.md): Git, shell and POSIX tools, and the accepted diff --git a/CHANGELOG.md b/CHANGELOG.md index 7733cc8c8..0ec7d8fe6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -25,8 +25,8 @@ Nothing since the `0.1.0` source version. ## [0.1.0] — 2026-09-19 M4's closed product baseline: the first numbered source version. It is a source -version only, not a package, a publication or a compatibility freeze; the -`v0.1.0` tag follows under its own release decision. +version only, not a package, a publication or a compatibility freeze. The +separately authorized annotated `v0.1.0` tag identifies that source. No package or compatibility-labelled surface is pending. diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 689ad7455..0f36cc909 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -76,8 +76,8 @@ coding-agent client, and runs once per integration candidate: hosted CI runs `bash scripts/check.sh --select` on every push to `main` and every pull request and does not define it. -Before closing a milestone or releasing, once from the exact committed -candidate, on a machine with the pinned Node and a provider credential: +Before closing a milestone, once from the exact committed candidate, on a +machine with the pinned Node and a provider credential: ```bash LOOPEX_PROVIDER_API_KEY=... bash scripts/check-release.sh @@ -96,6 +96,10 @@ fixture, or retained evidence. Two of the real-provider tests are attended: they prompt on the controlling terminal for the operator's trust decisions (`Type yes and press Enter.`), so run the command from a terminal. +An unchanged-source release reuses this closure evidence. It runs only the +pre-tag administrative-SHA proofs described by the milestone and verification +guides; it does not run `scripts/check-release.sh` again. + The individual commands can also be run directly: ```bash diff --git a/README.md b/README.md index cc57e0e72..b71e9e8fe 100644 --- a/README.md +++ b/README.md @@ -30,8 +30,8 @@ while the session lives; a session "brain" can coordinate local or remote [Canonical milestone status and plan records](docs/plans/) -M0 through M4 are closed and integrated, and `M5` is open and not yet -accepted, as the capsule above records. M1 delivered the durability kernel: +M0 through M4 are closed and integrated. The capsule above, derived from the +canonical register, carries the current M5 state. M1 delivered the durability kernel: an explicit embedded runtime, durable local Store, canonical model boundary, trusted-local executor, thin reference client, durable events, and receipt reconciliation across a real runtime-process crash. What it deliberately did not deliver is a @@ -131,9 +131,9 @@ supervision on Darwin and Linux; raw commands still use `/bin/sh`. See the [runtime prerequisite](docs/operator/tools-and-policy.md#operator-local-supervision-shell) before using the reference stack. Core and custom executors are unaffected. -### What Comes Next +### M5 Durable Service -`M5` is the next milestone, and it is the durable-service rung: a local daemon +`M5` defines the durable-service rung: a local daemon that owns session lifetime for a state root, so sessions keep running while no client is connected; several independent client processes reaching one session over a Unix-domain socket; one of them driving while the others watch, with an @@ -143,14 +143,14 @@ store adapter within that adapter's documented limits. Read the [technical companion](docs/plans/M5-technical.md#technical-depth) for the purpose, outcomes and how each one is to be proved. -Nothing in it is settled yet. The plan pair is open and not accepted, and its -four prerequisite decisions — ADRs [0031](docs/adr/0031-daemon-grade-store-selection-and-migration.md#concept), +Its four prerequisite decisions are ADRs +[0031](docs/adr/0031-daemon-grade-store-selection-and-migration.md#concept), [0032](docs/adr/0032-daemon-attachment-residency-and-replay.md#concept), [0033](docs/adr/0033-collaboration-controller-lease-and-takeover.md#concept) and [0034](docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) -— are proposed, not accepted. The status capsule above and the -[canonical register](docs/plans/README.md) carry the milestone state; this -paragraph only says what the work is for. +. The status capsule above and the [canonical register](docs/plans/README.md) +carry the milestone and decision state; this paragraph only says what the work +is for. The [roadmap](docs/roadmap.md#concept) is non-normative capability guidance; [CHANGELOG.md](CHANGELOG.md) records what changed. @@ -265,7 +265,9 @@ across the applications, and the credential-free suite with one application per VM. It runs once per integration candidate. `scripts/check-release.sh` is the slow one: the real-provider workflows, the independent Node client, the fresh-source archive build and the long-duration bound proofs; it needs a -provider credential and the pinned Node, and runs before closure and release. +provider credential and the pinned Node, and runs once before closure. An +unchanged-source release reuses that evidence and runs only its pre-tag +administrative-SHA proofs. Hosted CI — `.github/workflows/agent-bootstrap.yml` — runs `bash scripts/check.sh --select` on every push to `main` and every pull diff --git a/docs/README.md b/docs/README.md index 7c9e86f55..cd5a755bf 100644 --- a/docs/README.md +++ b/docs/README.md @@ -93,7 +93,7 @@ whose path or explicit fragment does not resolve. - [M3 foundations](plans/M3.md#concept) and [technical plan](plans/M3-technical.md#technical-depth) — project skills and core repairs; Closed with retained evidence in the plan. - [M4 headless external consumption](plans/M4.md#concept) and [technical plan](plans/M4-technical.md#technical-depth) — durable interactions, artifact transfers, the floor refresh, observability, and the experimental session protocol driven by an independent Node consumer in plain JavaScript; Closed, with its runs in [M4 closure runs](evidence/M4-closure-runs.md). -- [M5 durable service](plans/M5.md#concept) and [technical plan](plans/M5-technical.md#technical-depth) — daemon-owned session lifetime on the ADR-selected local store within its documented limits, generation-2-only Unix-domain-socket transport, in-memory controller lease with observers and takeover, and at-least-once replay with residency limits over M4. The [plans register](plans/README.md) carries its state, which is `Open`. +- [M5 durable service](plans/M5.md#concept) and [technical plan](plans/M5-technical.md#technical-depth) — daemon-owned session lifetime on the ADR-selected local store within its documented limits, generation-2-only Unix-domain-socket transport, in-memory controller lease with observers and takeover, and at-least-once replay with residency limits over M4. The [plans register](plans/README.md) carries its current state. - [Development contract](../AGENTS.md) — canonical tool-neutral authority, autonomy, documentation, milestone, and enforcement rules. diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md index 5a1c3af7c..194e08e02 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration-technical.md @@ -15,55 +15,129 @@ the foreground server does. **The marker invariant, stated as it actually works.** The daemon does not hold the marker itself and cannot release it itself: `Loopex.Store.Local` -takes it at start and releases it in its own `terminate/2`. What the daemon -owns is the Store *process*. It starts it before the socket is bound and, in a -**daemon-initiated** shutdown, stops it last — after the listener is closed, -every connection is closed and the runtime is stopped — so the marker is held -for as long as any operation **the daemon can end** could still need it, and -is released by that `terminate/2` at the moment the daemon stops the Store. -That ordering is the whole mechanism; it is fixed in the M5 plan's lifecycle -section. +takes it at start and invokes `WriterLock.release/1` from its own +`terminate/2`. What the daemon owns is the Store *process*. It starts it before +the socket is bound. In an **orderly** shutdown it stops the Store last — after +the listener is closed, every connection is closed and the runtime is stopped +— so the marker is claimed for as long as any operation **the daemon can end** +could still need it. Failed-start reverse cleanup likewise stops a returned +Store pid after every edge that start acquired. A fatal fail-stop is a separate +bounded tail: it stops the executor and then the still-live Store under the +35-second watchdog, while the remaining VM-local components end at +`System.halt/1`; Store-last is not claimed on that path. Those orderings are +fixed in the M5 plan's lifecycle section. + +Release is best effort, not a proof of removal. `WriterLock.release/1` first +compares the path's bytes with the exact marker for this acquisition. On a +match it calls `File.rm/1` and syncs the parent, ignores both results and always +returns `:ok`; an unreadable, absent or foreign path also returns `:ok` +(`writer_lock.ex:103-115`). A completed Store `terminate/2` therefore proves +only that this release path was invoked. The healthy-path evidence separately +asserts marker absence and an immediate reopen without recovery. An ignored +unlink failure can leave a complete residual, and an ignored parent-sync +failure means the callback cannot classify the durable removal outcome. + +**Acquisition can fail after the marker file is exclusively created but before +there is a Store pid or returned lock handle.** `WriterLock.write_marker/2` +creates the path first and returns an error on a later marker write, file sync, +close or parent-directory sync without unlinking it +(`writer_lock.ex:200-225`). `Local.init/1` then returns `{:stop, reason}` before +its state contains `writer_lock`, so `terminate/2` has no handle to release +(`local.ex:152-168`), and the daemon receives no Store pid it could stop. This +is an existing local-adapter limit, not a cleanup action M5 can perform. A +complete residual marker is handled by the adapter's verified stale-writer +recovery after its recorded Store process or OS process is dead. An empty or +partial marker is undecodable and correctly refuses automatic recovery as +`store_writer_unverifiable`; the operator runbook requires inspection and +explicit removal while no holder is live. The daemon keeps placement through +its failed-start cleanup, reports `store_writer_acquisition_failed`, touches no +socket and makes no claim that reverse cleanup removed this residual. The qualification is deliberate and is the strongest true form. Where the runtime does not stop within its grace the daemon kills its supervisor, and a *trapping* descendant — an owner group, or a trapping worker beneath one — may still be unwinding when the Store goes. **What refuses such a straggler is the drain's fence, not a stopped Store**, and an earlier revision of this paragraph had it the other way round. The -Store is *not* stopped while a straggler is most likely to be unwinding: the -daemon stops it last, in its own phase, so there is a window in which the -Store is alive and accepting. What makes the straggler harmless is that the -drain moved that session's owner epoch before the runtime came down, so its -commit is refused `:stale_owner_epoch` like any other stale writer. The marker -is therefore never held open by a straggler and no straggler appends behind -the daemon's back — but for the fence's reason, which holds whether the Store -is alive or not, rather than for an absence that only begins later. What the -daemon does not promise is that every process has finished before it exits. - -The adapter also **traps exits**, which this arrangement relies on: an owner -that crashes rather than stopping gives the Store's `terminate/2` the chance -to run, so the marker ordinarily comes back. - -**Ordinarily, not always**, and the qualification is about process lifetime -rather than about the adapter. The Store runs `terminate/2` only while the VM -is alive, and the command process that monitors the daemon owner halts the VM -the moment it sees that owner's `DOWN` — a race the adapter cannot win from -inside. So **owner loss is crash-equivalent for the marker**: it is released -or it is stale, the daemon cannot tell which, and neither can this ADR. That -costs nothing, because the successor's liveness-probed recovery already -handles both — a marker whose recorded holder is proved dead is reclaimed, one -that cannot be decided refuses `store_writer_unverifiable`, and a live holder -refuses `store_writer_active`. Claiming the release always happens would have -been a claim about scheduling. What leaves it is a kill, a power loss, or a bounded stop -of the Store that expired and had to be ended with `Process.exit(pid, :kill)` -— the three cases the next daemon's verified stale-writer recovery is for. - -**Store loss inverts it, and the daemon cannot order what it does not -control.** This adapter answers an append error with -`{:stop, reason, commit_unknown, state}` — it terminates *itself* — and its -`terminate/2` releases the marker as it goes. So on a store loss the marker is -released **before** the daemon can react, and any sequence ending "then stop -the Store" is unrunnable, because the Store is what died. The daemon's only -correct response is a fail-stop, and it arranges to be able to make it: the +Store is *not* stopped while a straggler is most likely to be unwinding: on an +orderly stop the daemon stops it last, in its own phase, so there is a window in which the +Store is alive and accepting. The drain therefore reports the exact fence +disposition rather than claiming every epoch moved. A committed fence moves the +epoch and refuses the straggler as `:stale_owner_epoch`; `:superseded` proves +the sole old transaction won first; an unknown fence remains `unsettled` and +may still resolve while the Store is alive. The marker is never held open by a +straggler, but orderly stop makes no stronger append claim than those reported +dispositions support. The daemon also does not promise that every process has +finished before it exits. + +The adapter **traps exits**, but that does not turn owner death into a Store +stop. It defines no `handle_info({:EXIT, ...})`, so the linked owner's abnormal +exit becomes an unhandled mailbox message and `terminate/2` does not run. The +command process then observes owner `DOWN` and halts the VM, which also runs no +termination callback. So **owner loss is crash-equivalent for the marker** and +leaves it stale. The successor's liveness-probed recovery handles that exact +case: a marker whose recorded holder is proved dead is reclaimed, one whose +liveness cannot be decided refuses `store_writer_unverifiable`, and a live +holder refuses `store_writer_active`. A kill, power loss, or bounded Store stop +ended with `Process.exit(pid, :kill)` leaves the same recovery obligation. Any +Store stop that reaches `terminate/2`, deliberate or self-initiated, attempts +the adapter's exact-marker release. On the healthy path the marker is removed; +because the unlink and parent-sync results are discarded, callback completion +cannot distinguish that path from a complete residual or an uncertain durable +removal. A later recovery request applies the existing classifications: a live +holder refuses `store_writer_active`, a proved-dead holder is reclaimed, and a +holder whose liveness cannot be established refuses +`store_writer_unverifiable`. + +**The Store marker is physical-writer exclusion; the host placement lock keeps +Runtime Controls from overlapping.** Accepted ADR 0008 distinguishes those +facts, and `LoopexCli.Placement` already implements the latter for the reference +host as a crash-reclaimable `placement.lock` bound to OS pid and process start +identity. M5 moves that implementation without changing its file path, record, +guard, owner-handle or liveness rules into a host utility in +`loopex_composition`; the CLI uses that utility through its existing surface and +the daemon uses the same one. This is reuse of an accepted host invariant, not a +second lock protocol. + +The daemon acquires the placement lock **before** it opens the Store or reads, +removes or binds the socket path. On an orderly stop it attempts the +acquisition-specific release only after every Runtime Control is known gone and +the Store has stopped. An unlinked, monitored helper owns that exact call under +one absolute `placement_release_ms: 5_000` deadline. Exact `:ok` followed by the +helper's normal `DOWN` proves only that the attempt completed; a missing, +malformed or abnormal result selects `placement_lock_failed`, and expiry hard +halts without waiting further. Failed-start cleanup and the offline +`prepare-index` command use the same helper and deadline, preserving an earlier +failure class when one is already latched. + +`LoopexCli.Placement.release/1` compares the owner handle and canonical lock +inode before removing the canonical path, then removes the handle; it ignores +both removal results and always returns `:ok` (`placement.ex:77-99,233-241`). A +completed call therefore does not prove either pathname absent. The exact-handle +comparison prevents a delayed release from removing a successor's lock, so a +residual is safe; once the old daemon's operating-system incarnation is proved +dead, the next acquirer reclaims it. On every fatal path other than a final +placement-release failure the daemon instead keeps the lock through +`System.halt/1` and leaves that same recovery to the next process. A second acquisition in the +same VM also refuses while that OS holder is live, which closes the hole a +Store marker cannot close: `WriterLock` deliberately treats a dead recorded +Store pid in the current VM as reclaimable. The supported daemon topology is +therefore safe both across VMs and inside one VM without changing the local +adapter's behaviour for embedded hosts. + +**Store loss attempts marker release early but does not release placement.** This +adapter answers an append error with `{:stop, reason, commit_unknown, state}` — +it terminates *itself* — so any sequence ending "then stop the Store" is +unrunnable because the Store is what died. Its existing `terminate/2` invokes +the best-effort writer-marker release; the result cannot prove the marker +absent. The still-live daemon process continues to hold +`placement.lock`, so another daemon or the reference CLI refuses before opening +the Store and before touching the socket. After the daemon halts, the placement +lock is stale and its existing liveness-probed recovery may reclaim it. This +preserves ADR 0008's one active Control per `{Store identity, runtime_id}` +instead of treating Store commit fencing as permission for overlapping +runtime-local caches. + +The daemon's only correct response is a fail-stop, and it arranges to be able to make it: the daemon **start_links the adapter itself**, from an owner process that traps exits and keeps the adapter's pid, so the termination arrives as `{:EXIT, store_pid, reason}` at a clause the daemon wrote — carrying the @@ -82,20 +156,27 @@ which would have meant a second copy of the wiring layer. On the reported exit i refuses service, closes every connection with `store_lost`, or `store_capacity_exceeded` where that was the store's own reason, and exits non-zero. It does **not** unlink the socket — and neither does any other exit path, -orderly or otherwise: a daemon's claim on that pathname is its marker, and ADR -0032 makes removing the pathname the next verified marker holder's job -precisely so that no departing daemon can remove a successor's socket. The next daemon finds no marker to -recover, because the dying store already gave it back, and removes the stale -pathname before it binds. - -An abrupt kill of the daemon runs no `terminate/2` at all, which is why *that* -leaves a marker behind and why the next daemon's verified stale-writer -recovery exists. The cases are distinct and the operator documentation keeps -them so: a daemon that stops the Store releases the marker in order — whether -that is an orderly shutdown or a fatal class where the Store is still alive -and the daemon stops it before halting; a store loss releases it early and -unexpectedly; and a kill, a power loss or an expired stop leaves it for -recovery. The adapter's limits are the +orderly or otherwise: a daemon's claim on that pathname is the joint authority +of its host placement lock and its successfully opened Store, and ADR 0032 +makes removing the pathname the next verified placement-lock and marker holder's job +precisely so that no departing daemon can remove a successor's socket. A +contender before the old daemon halts cannot acquire the placement lock and +therefore cannot touch the pathname. A contender after the halt recovers the +stale placement lock, then acquires or recovers the Store marker as needed and +removes the stale pathname before it binds. + +An abrupt kill of the daemon runs no `terminate/2` at all, which is why it +leaves a marker behind and why the next daemon's verified stale-writer recovery +exists. A failed acquisition after exclusive create can leave the same complete +stale marker or an undecodable partial marker without ever producing a Store +pid. The cases are distinct and the operator documentation keeps them so: a +daemon that stops the Store attempts marker release in order — whether that is +an orderly shutdown or a fatal class where the Store is still alive and the +daemon stops it before halting; a Store self-stop attempts it early; and an +ignored unlink failure, kill, power loss, expired stop or failed acquisition +may retain a complete marker for recovery. A partial startup marker remains an +operator-inspection case. In all fatal cases the independent +placement lock stays until the daemon OS process is gone. The adapter's limits are the daemon's limits, and every one is an existing constant or refusal of `Loopex.Store.Local.Log`: @@ -113,8 +194,9 @@ daemon's limits, and every one is an existing constant or refusal of Physically nothing was written; contractually the transaction is ambiguous and the store is gone. The daemon therefore cannot keep observers attached past a capacity refusal, and does not claim to: it closes the listener and - every connection and exits, naming the capacity. Changing that would be a - change to the adapter's own contract, which this ADR does not make; + every connection and exits, naming the capacity. The Store attempts its + best-effort marker release while the daemon's placement lock continues to + exclude a successor, without changing the refusal or result; - a 4 MiB frame ceiling (`@max_frame_bytes`) on any single record; - full-history retention: no compaction, no retention cutoff, and full replay at every open, so replay time and memory grow with the root's history until @@ -138,21 +220,39 @@ daemon's limits, and every one is an existing constant or refusal of does not. Root retirement is an operator procedure, not a store operation: stop the -daemon so the marker is released; move the root directory aside under a name -of the operator's choosing; start the daemon on a fresh root with the same -placement identity source. A session in a retired root is resumed only by -stopping the daemon and reopening that root, with the daemon or the -foreground server. The daemon's operator documentation states the capacity, -the refusal reason, the frame ceiling, full retention and this procedure. +daemon; on the healthy path verify marker absence before moving the root +directory aside under a name of the operator's choosing; then start the daemon +on a fresh root with the same placement identity source. A complete residual +uses the existing verified stale-writer recovery or, where liveness is +unverifiable, the documented inspection procedure. A session in a retired root +is resumed only by stopping the daemon and reopening that root, with the daemon +or the foreground server. The daemon's operator documentation states the +capacity, the refusal reason, the frame ceiling, full retention and this +procedure. Evidence for the M5 selection is the M5 plan's Outcome 1 obligation, not a second copy here: a root driven to the capacity ceiling refuses the append with the store's own reason and takes the daemon's listener and connections -down with it, a root already past the bound refuses at open, a stale marker is -recovered where its holder is proved dead and refused where it is not, and -after an orderly stop the foreground server reopens the same root. No new -conformance evidence is required, because the adapter and its suites are -unchanged. +down with it and its Store attempts marker release. A contender held at that +cut receives the placement-lock live-owner refusal while the predecessor VM +and Control are live. Only after that daemon halts may verified stale-owner +recovery acquire the placement lock; a same-VM second acquisition refuses by +the same rule. A root already past the bound refuses at open. After a healthy +orderly stop, evidence asserts marker absence and the foreground server's +immediate reopen without recovery; it does not infer either fact from +`terminate/2` returning. A prepared complete residual separately proves the +writer recovery's live, proved-dead and unverifiable branches. The shared +placement-lock tests prove atomic exclusion, same-VM live refusal, cross-VM +live refusal, dead-owner recovery, healthy acquisition-specific release and +that a residual ignored by best-effort release is reclaimed only after the old +operating-system incarnation is dead. The durable format, +callback inventory, arities and result union remain unchanged. The local adapter +and the M1 controllable test Store also gain one conformance case +for the existing `runtime_command/2` read projection: an exact retained create +binding returns `{:completed, %{result: session_id}}`; changed create inputs or +a cross-kind command ID return `runtime_command_conflict`; every query leaves +the root byte-identical. That is a projection correction, not a new persistence +or migration contract. ### What this pair leaves open @@ -188,11 +288,17 @@ are questions, and this pair does not answer them. Concept: [Consequences and rollback](0031-daemon-grade-store-selection-and-migration.md#concept-adr-0031-consequences). -No journal format changes; the daemon, the foreground server and the CLI -reopen one another's roots, and rollback is stopping the daemon. The private -journal is a separate compatibility surface and stays experimental in 0.x. -There is no forward migration, so there is no migration to roll back and no -oldest-reader claim to defend. +No journal format changes; at the Store and journal layer the daemon, the +foreground server and the CLI replay the same bytes, and Store rollback is +stopping the daemon. The private journal is a separate compatibility surface +and stays experimental in 0.x. There is no forward Store or journal-format +migration, so there is no engine migration to roll back and no +oldest-journal-reader claim to defend. ADR 0032's daemon-owned bounded index +and explicit offline legacy import are a compatibility projection outside the +Store adapter: a populated legacy root requires that import before its first +M5 daemon start, while daemon-to-foreground rollback and later switches after +the import need no Store conversion. The index's interrupted-write and +rollback mechanics belong to that decision and never rewrite a journal record. Acceptance binds this complete pair at the exact candidate the maintainer names in the governance record, and it carries exactly one disposition: the diff --git a/docs/adr/0031-daemon-grade-store-selection-and-migration.md b/docs/adr/0031-daemon-grade-store-selection-and-migration.md index 730b5e8a1..285ea8074 100644 --- a/docs/adr/0031-daemon-grade-store-selection-and-migration.md +++ b/docs/adr/0031-daemon-grade-store-selection-and-migration.md @@ -23,17 +23,20 @@ state root, replayed in full at every open, held by one operating-system process through a writer marker, with a hard capacity, no compaction and no session index. That is exactly right for a foreground process that owns one session at a time and exits with it. The vision's reference daemon runs on -an ADR-selected store, and a service makes operational claims that the -bootstrap adapters were never asked to make: bounded replay, an index, a -migration pair with interrupted-migration recovery, backup and restore, and -a stated oldest binary that may reopen a migrated root. The vision freezes -the store contract, not an engine, and says adapters are selected by -evidence. None of those operational claims is made for `0.2.0`; what has to -be decided now is which store the daemon runs on and what the operator is -owed about its limits. +an ADR-selected store, and a daemon-grade Store engine makes operational +claims that the bootstrap adapters were never asked to make: bounded replay, +a Store-owned index, a Store/journal-format migration pair with +interrupted-migration recovery, backup and restore, and a stated oldest binary +that may reopen a migrated root. The vision freezes the store contract, not an +engine, and says adapters are selected by evidence. None of those +**Store-engine** claims is made for `0.2.0`; what has to be decided now is +which store the daemon runs on and what the operator is owed about its limits. +ADR 0032 separately adds a daemon-owned bounded listing index and explicit +offline compatibility import over the unchanged journal. That projection is +not a Store index or Store migration. **Select the existing local adapter as the daemon's store for `0.2.0`.** The -Store process holds the local writer marker for the Store process's lifetime, +Store process claims the local writer marker for that Store process's lifetime, while the daemon owns and watches that process, and the daemon inherits the adapter's exact, documented limits: one append-only log per state root with a hard 256 MiB capacity, a 4 MiB frame ceiling, full-history retention @@ -42,8 +45,21 @@ capacity is a truthful stop, never a silent loss, and it is not survivable on this adapter. The append is refused before a byte is written, with `store_capacity_exceeded`; the adapter then terminates its Store process and the caller receives `commit_unknown` for that transaction, because that is -what this adapter does with every append error. So the daemon meets capacity -as a loss of the store, not as a recoverable refusal: it closes the listener +what this adapter does with every append error. An abnormal Store self-stop +runs its marker-release path before the daemon can react, but that path is best +effort: its success result does not prove that the marker was removed. The +daemon therefore holds the **host placement lock** accepted ADR 0008 requires +independently of that marker. It acquires the same crash-reclaimable root lock +the reference CLI uses before opening the Store, and an orderly teardown +attempts its acquisition-specific release only after the old Control is gone +and the Store has stopped. That release runs in a monitored helper under a +fixed five-second deadline; completion is still only a best-effort attempt, and +a timeout hard-halts. A residual remains safe and the next acquirer reclaims it +after the daemon's operating-system incarnation is dead. Fatal exit leaves the +same recovery obligation. This keeps +a successor out while the old Runtime Control may still route consequences +without changing the adapter for every embedded host. So the daemon meets +capacity as a loss of the store, not as a recoverable refusal: it closes the listener and every connection and exits, naming the capacity in the close, and the operator retires the root. A log already past the bound is refused at open as `store_log_too_large` rather than opened and truncated. Nothing committed is @@ -51,6 +67,19 @@ lost and nothing false is recorded, which is what the truthfulness claim means here. Sessions in a retired root are resumable only by reopening that root. +The existing marker implementation can leave a residual in two ways the daemon +cannot classify from a release result. Marker creation may fail after exclusive +create but before a Store pid or lock handle is returned. A completed Store +`terminate/2` can also leave the complete marker because `WriterLock.release/1` +ignores marker-unlink and parent-sync failures and always returns `:ok`. A +complete marker follows the adapter's existing live, dead and unverifiable +holder rules; an empty or partial startup marker is unverifiable and requires +the documented operator inspection and removal while no holder is live. The +daemon reports a failed acquisition, keeps placement through cleanup and never +touches the socket. On the healthy release path, marker absence and an immediate +reopen without recovery are the evidence; callback completion alone is not. +This limit is part of selecting the adapter unchanged. + This is a bounded, experimental selection made on evidence the local adapter already carries; it is not a daemon-grade store, and the 0.2.0 daemon's operator documentation states these limits and the @@ -72,9 +101,15 @@ what backup and restore, and which binary is the oldest reader of the new root their own ADR, proposed with the successor milestone's plan, accepted on its own review, declaring `Supersedes: 0031` for the selection this pair makes. Nothing about that work binds M5, and nothing in M5 forecloses it: the local -format, its ports and its adapter are unchanged — the adapter gains nothing at -all, the read-only marker query an earlier revision gave it having gone with -the unlink it was invented for — so any successor starts from +durable format and private port shape are unchanged. ADR 0032's daemon-owned +listing index and legacy-root import remain an external compatibility +projection, not part of this adapter or its journal. M5 adds the missing read +projection for a retained create through the existing `runtime_command/2` +callback and result union. The daemon also reuses the reference CLI's existing +placement-lock mechanism through a shared host utility; this changes no Store +callback, transaction or durable byte and preserves the lock's current path, +record and recovery rules. The read-only marker query an earlier revision proposed is +gone with the unlink it was invented for, so any successor starts from exactly the root M5 leaves. **Alternatives rejected.** Deferring this decision out of M5 entirely was @@ -108,12 +143,19 @@ its class is process and store fault injection on the real adapter plus a rollback proof: a root driven to capacity refuses the append with the store's own reason, terminates the store, and the daemon closes the listener and every connection and exits naming the capacity, with nothing committed lost; a root -already past the bound refuses at open; and after an orderly stop on a root -below the bound the foreground server and reference CLI reopen it. No new -conformance evidence is required, because the adapter and its suites are -unchanged — which is the point of selecting it. That is the whole of the -evidence this pair owes, because that selection is the whole of what it -decides. +already past the bound refuses at open; and after a healthy orderly stop on a +root below the bound the marker is absent and the foreground server and +reference CLI immediately reopen it without recovery. Recovery evidence covers +a complete residual marker whose holder is live, proved dead or unverifiable; +the Store's `terminate/2` result itself cannot say which filesystem action +failed when the residual remains. The existing +Store conformance lane gains the exact create-history projection case on the +real local adapter and its controllable test Store: an exact canonical create +binding returns `{:completed, %{result: session_id}}`, while changed options and +a cross-kind command ID return `runtime_command_conflict`, with byte-identical +durable storage. No new Store callback or persistence conformance class is +required. That is the whole of the evidence this pair owes, because that +selection is the whole of what it decides. Technical depth: [Contract and evidence](0031-daemon-grade-store-selection-and-migration-technical.md#technical-adr-0031-decision). @@ -123,7 +165,10 @@ Technical depth: [Contract and evidence](0031-daemon-grade-store-selection-and-m The daemon and its clients see the same durable session truth the embedded API and the foreground server see; the store adapter is a host choice, not a semantic one. In M5 the foreground server, the reference CLI and the daemon -all run on the local adapter and can reopen one another's roots. A root that +all run on the local adapter and can reopen the same journal bytes. ADR 0032's +separate daemon index means a populated legacy root needs its one-time offline +import before the first M5 daemon start; daemon-to-foreground rollback and +later switches after that import need no Store or journal conversion. A root that reaches the local log's capacity takes its daemon down with it and is retired by the operator; nothing already committed is lost, and the operator documentation says plainly that capacity is an outage rather than a @@ -132,12 +177,22 @@ is a separate compatibility surface: adding an adapter later freezes no wire, artifact or embedded contract, and the exact private format stays experimental in 0.x. -M5 rollback is stopping the daemon in its ordered Store-last path, which lets -the Store process release the marker before the foreground server or CLI -reopens the same root under the same placement identity. A Store that exits on -its own releases the marker before the daemon can react; a kill or power loss -may instead leave a stale marker for the adapter's verified recovery. There is -no forward migration to roll back, because M5 introduces none. +M5 rollback is stopping the daemon in its ordered Store-last path, which runs +the Store marker's best-effort release and then attempts the placement lock's +exact-handle release, under its fixed helper deadline, only after the old +Control and Store are gone. The healthy +path proves release by marker absence and immediate foreground-server and CLI +reopen, rather than by either release function's unconditional `:ok`. A Store +that exits abnormally on its own attempts its marker release, but the placement +lock still names the live daemon process and refuses a contender until the +daemon halts. Either release can leave a complete residual after an ignored +unlink failure: Store-marker recovery applies the existing live, dead and +unverifiable classifications, and the next placement acquirer reclaims a stale +lock only after proving the old operating-system incarnation dead. A kill or +power loss leaves the same recovery obligations. There is no forward Store or +journal-format migration to roll back. ADR 0032's offline daemon-index import +can leave only the complete bounded projection states and residuals that its +own rollback contract names; it never rewrites the journal. Technical depth: [Compatibility mechanics](0031-daemon-grade-store-selection-and-migration-technical.md#technical-adr-0031-compatibility). diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md index 69e6c0fd7..2721da0bf 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay-technical.md @@ -21,8 +21,10 @@ the daemon's to re-permission. `LoopexAppServer.Host` creates it with M4 root is `0755` — measured, not assumed. Requiring the *root* to be `0700` would have made the daemon refuse every root the foreground server and the CLI have been writing since M4, which contradicts this milestone's central -compatibility claim that moving a root between the daemon and the foreground -surfaces is stopping one and starting the other. Tightening the root instead +compatibility claim: daemon-to-foreground rollback and switches after the +one-time daemon-index import require only stopping one surface before starting +the other. A first M5 daemon over a populated legacy root still requires that +explicit offline import. Tightening the root instead would be an unannounced permission change to an operator's existing directory. The daemon therefore owns one subdirectory and leaves the root's mode exactly as it found it. @@ -35,8 +37,9 @@ bind at 103 bytes succeeds and at 104 bytes is refused with `{:invalid, {:sockaddr, …}}`. Each supported platform derives its own bound the same way rather than carrying a constant, and a path beyond it is refused at start with `socket_path_too_long` naming the derived bound, never -truncated. The tests bind at the bound and at one byte past it on every -platform the release check runs. +truncated. The closure matrix binds at the bound and at one byte past it on +both supported platforms: Darwin in the floor-pair fast check and Linux in the +current-pair CI and release lanes. **Peer authorization has two layers, and the load-bearing one is the filesystem.** The socket lives in that `0700` daemon-owned subdirectory and is @@ -67,6 +70,181 @@ backend exposes neither, so the listener uses OTP's own `:socket` API (or classic backend. A peer whose decoded uid differs from the daemon's is closed before any frame is read. +**Startup creates a parked listener before it creates an accept.** The bound, +listening socket is transferred to the listener with an unforgeable +`startup_ref`; the listener monitors the daemon owner, acknowledges that it is +parked and performs no `accept` until the lifecycle sentinel sends exact +`{:begin_accept, startup_ref}`. The signal handler targets that sentinel. The +owner submits exact +`{:begin_readiness, owner_ref, startup_ref, listener_pid, line}`; the sentinel +starts and monitors the whole-line helper, records the absolute five-second +deadline and becomes the single startup-disposition arbiter. It serializes +matching stop, helper result, helper `DOWN`, deadline check, owner-reported +startup fatal and owner release authorization. The timer only prompts a clock +check, and every candidate result is rejected at or after the absolute instant. + +From submission until the sentinel returns a disposition, the owner remains in +its owned-exit loop and immediately reports a consumed component fatal. Exact +output success does not release the listener. The sentinel sends exact +`{:readiness_output_succeeded, owner_ref, startup_ref, sentinel_pid}` to the +owner; the owner consumes queued component exits, rechecks the clock and every +required component, then sends exactly one of +`{:readiness_release_authorized, owner_ref, startup_ref, owner_pid, +listener_pid}` or +`{:readiness_startup_fatal, owner_ref, startup_ref, owner_pid, listener_pid, +class, status}`. Because +one owner sends both, an owner-observed fatal is ordered against its later +authorization. The owner waits for the sentinel's exact disposition and does +not independently clean up or declare startup complete. + +The first valid disposition consumed by the sentinel wins. Stop selects +provisional `:operator_stop`; startup fatal retains that class and status; +helper refusal, helper death or deadline selects `readiness_write_failed`. +Every nonzero winner is also the sentinel's retained first-fatal class and +status and arms its watchdog. Deadline expiry hard-halts with that exact status +because an IO request already queued at the IO server cannot safely be +recalled; a completed refusal or helper death tells the owner to reverse-clean. +Stop merely authorizes the owner to halt with status `0` after cleanup +completes; owner death before then selects `owner_lost`. Except for deadline +hard-halt, the winner is returned as exactly one of +`{:readiness_disposition, owner_ref, startup_ref, :operator_stop}`, +`{:readiness_disposition, owner_ref, startup_ref, {:fatal, class, status}}` or +`{:readiness_disposition, owner_ref, startup_ref, :running}`. Stop or fatal +tells the owner to reverse-clean and +leaves the gate parked; every later candidate is cleanup-only. The sentinel +kills and reaps any retained helper during bounded cleanup without claiming it +recalled queued IO. The complete line may already be visible because helper, +signal handler and owner are different senders, but no server connection +process, registry row, relay origin, lease owner, attachment, core call or wire +state exists. + +Only release authorization consumed before the deadline and any other +disposition lets the sentinel send `{:begin_accept, startup_ref}`. It records +`running` before returning the exact `:running` disposition and forwards any later +stop for the ordinary shutdown path. That exact send is the classification +cut: an owner-observed linked listener `EXIT` ordered into the sentinel before +authorization is `listener_start_failed`; after the send it is +`listener_lost`. The rule uses observable messages and the sentinel's send, +without inferring kernel-time order. A client queued in the backlog observes +service only after release, or close without initialize or mutation. Verified +stale placement, marker and socket recovery handles crash residue. Forced +cases cover stop versus success/refusal/death/deadline in both sentinel orders, +component fatal versus success/deadline in both sentinel orders, and both +sides of the listener cut. + +**The listener transfers every accepted socket before the connection becomes +live, with a monitor in both directions during the handoff.** After `accept`, +the registry holds a provisional row +`{rollback_token, listener_incarnation, accepted_at, initialize_deadline, +connection_pid | nil, connection_incarnation | nil, transfer_disposition}` and +monitors the listener. `transfer_disposition` is exactly `:listener_owned`, +`:transferring` or `:connection_owned`. +`accepted_at` is the listener's monotonic instant immediately after the kernel +accept returns, and `initialize_deadline = accepted_at + 30_000`; neither value +is recomputed. The listener never creates a connection process. It asks the +registry to start one for the exact rollback token. In that one serialized +registry callback, after rechecking the row, listener incarnation and deadline, +the registry calls `GenServer.start_link/3` with itself, the listener and that +unchanged deadline in the waiting child's arguments. The child's `init/1` does +no IO or external call: it installs monitors on the registry and listener and +returns immediately. Before it serves, the registry sets +`Process.flag(:trap_exit, true)` and retains the exact daemon-owner pid, whose +own `EXIT` still stops the registry. A temporary child's `EXIT` is instead +matched by its exact pid and handled idempotently with that child's monitor +`DOWN`; it can never take the registry down. Before the callback replies or +processes any queued listener `DOWN`, child `EXIT` or child `DOWN`, the registry +installs its provisional child monitor, binds the returned pid and fresh +connection incarnation into the row, prepares the updated state, then unlinks +the child. From the instant of creation until that unlink, the registry link +owns the child; afterwards the child's registry monitor and the registry's +child monitor own each other. A caught start exit or returned start +failure leaves `connection_pid: nil` and enters the ordinary no-child abort. +Thus `nil` means no child exists, never “a child may have been returned but not +recorded.” If the registry dies at any point, its link or the child's registry +monitor ends the child; registry loss remains daemon-fatal. + +Only the exact successful registry reply gives the listener the child pid and +incarnation. The connection already monitors the listener. While the listener +is still the socket owner, it compare-and-sets the row from `:listener_owned` +to `:transferring`, calls +`:socket.setopt(socket, {:otp, :controlling_process}, connection_pid)`, and +reports that exact call's result to the registry before it may promote. The +registry changes a successful result to `:connection_owned`; a refusal returns +the row to `:listener_owned` for exact close. + +Only after that succeeds may the connection ask the registry to promote the +slot. In one registry callback, promotion changes the exact provisional row to +live **before** replying and keeps its connection monitor as the permanent live +monitor. After that acknowledgement, the connection flushes and removes its +listener monitor, begins receiving, and sends the listener +`promotion_complete`. Only that message lets the listener demonitor and flush +its temporary connection monitor. + +The registry transition is a compare-and-set on the rollback token and +connection incarnation. Reservation, child start, socket transfer, promotion, +the connection's first receive and every initialize continuation recheck +`monotonic_now < initialize_deadline`; the same deadline survives every +handoff. Before promotion, either provisional monitor `DOWN`, expiry, a +deadline check that loses, a +failed child start, a failed transfer or a failed registry commit changes +`provisional(token, :handing_off)` to `provisional(token, :aborting)`; that +substate remains an occupied provisional slot. The registry already monitors +the exact listener incarnation, so its `DOWN` is terminal evidence that every +socket still owned by that listener is closed. If no child was started, the +registry removes the row only after either the listener's exact socket-close +acknowledgement or that exact listener `DOWN`. With a child, the transfer +disposition decides cleanup. In `:listener_owned`, the registry requires that +close acknowledgement or listener `DOWN` **and** kills and reaps the child. In +`:connection_owned`, it kills and reaps the exact connection, whose death +closes its socket. In `:transferring`, it marks abort pending and waits for the +listener's exact transfer result, then takes exactly one of those branches. If +the listener dies before reporting, listener `DOWN` closes the +listener-owned possibility and killing/reaping the child closes the +successfully transferred possibility; the registry removes the row only after +both exact `DOWN`s are accounted. This remains true +when the transferred socket's owner is suspended: an abort request being queued +is not evidence that the pid or socket is gone. Promotion changes only +`:handing_off` to `live` and requires `:connection_owned`. After promotion or exact reap, a late abort, promotion +or `DOWN` for the token is a no-op. The daemon owner also observes listener exit +and orders +`abort_provisional_for(listener_incarnation)` before fatal listener teardown; +that idempotent sweep covers listener loss between slot reservation and child +start and simultaneous listener/connection death rather than depending on one +temporary peer surviving to report the other. + +The connection process owns the transferred socket, and the registry owns its +live monitor and buffer interface without linking to it. Because no listener +monitor remains after the two acknowledgements, listener death cannot +propagate to or close a promoted connection. No accepted socket enters the +registry's live set while the listener still controls it. Forced witnesses +cover slot reservation before child start, listener death after reservation +but before child start, and the registry paused after `start_link/3` returns but +before it binds and unlinks the child: listener death makes the child exit too, +but the trapped child `EXIT`, child `DOWN` and listener `DOWN` remain queued; +the registry completes the atomic bind when resumed, consumes them +idempotently, survives, and reaps the exact child, row, socket and slot. They +also cover expiry after child +start while the listener still owns +the socket, listener death after a failed transfer restored +`:listener_owned` but before close acknowledgement, transfer failure on each +side of the ownership change, expiry and abort racing transfer in both result +branches, promotion refusal, abort racing promotion, connection death +after transfer but before promotion, and simultaneous listener/connection +death; each awaits the exact close acknowledgement or listener/connection +`DOWN` required by its disposition and +leaves no socket, pid or provisional row. A suspended post-transfer connection +keeps its aborting slot charged while repeated accepts prove there is no 513th +connection process or socket; reaping it frees exactly one slot. A final case completes +promotion, kills the listener and proves the connection and socket remain +available for the bounded `fatal:listener_lost` write and close. The registry +owns the one deadline timer keyed by rollback token and connection incarnation. +The timer only prompts a monotonic check: expiry in a provisional row takes the +ordinary abort-and-reap path; expiry after promotion but before initialization +moves the live row to closing and closes it with EOF; and only the registry's +exact initialize-complete transition consumed while `now < deadline` cancels +and flushes the timer. A completion queued before the instant but consumed at +or after it is cleanup-only and cannot make the connection initialized. + **Fail closed.** Where a platform has a named mechanism, a credential read that errors, returns a short or unrecognised structure, or reports a uid the daemon cannot decode closes the connection before initialize; it is never @@ -76,18 +254,29 @@ alone — which the daemon proves it has, because it refuses to serve when ownership and mode cannot be verified. The evidence follows the same split. The fast check proves the filesystem -layer and the fail-closed paths without needing a second user: a permissive -directory or socket mode, a parent the daemon does not own, and a path -component the daemon did not create are each refused at start; an unreadable -or undecodable peer credential closes the connection. The real cross-uid -refusal is a release-check case on the Linux lane, where a second unprivileged -user exists: a connection from another uid is refused before initialize and a -connection from the daemon's own uid succeeds, both recorded with the run. - -Startup order is fixed. The daemon first opens the state root through the -local adapter and acquires its writer marker; a daemon that does not hold the -marker refuses with the adapter's `store_writer_active` or -`store_writer_unverifiable` reason and never reads, unlinks or binds the +layer and every fail-closed credential branch without needing a second user: a +permissive directory or socket mode, a parent the daemon does not own, and a +path component the daemon did not create are each refused at start; a +credential read that is unreadable, short, undecodable, or validly decoded to +a mismatched uid closes the accepted connection before initialize. The Linux +release lane has two tagged cases under a real second unprivileged user. The +foreign-user case first proves the verified `0700`/`0600` filesystem boundary +denies the connection in the kernel. The fixture then deliberately relaxes +those two permissions *after readiness*, allowing a new foreign-user +connection to reach `accept`, and proves `SO_PEERCRED` decodes that uid and the +daemon closes it before initialize; this test-only tampering is what makes the +second-layer assertion non-vacuous. The paired daemon-uid connection succeeds. +Both cases restore the directory and socket modes during cleanup and record +their results with the run. + +Startup order is fixed. The daemon first acquires the root's host placement +lock through the shared mechanism accepted ADR 0008 and already used by the +reference CLI. A live or unverifiable placement owner refuses before the Store +or socket path is touched; a stale owner is reclaimed only after its OS pid and +process incarnation are proved dead. The daemon then opens the state root +through the local adapter and acquires its writer marker; a daemon that cannot +hold the marker refuses with the adapter's `store_writer_active` or +`store_writer_unverifiable` reason and still never reads, unlinks or binds the socket path. The daemon opens the root with `recover_stale_writer: true`, explicitly, because that option defaults to `false` in both `Loopex.Store.Local` and `LoopexComposition` and a daemon that did not ask for @@ -96,31 +285,419 @@ ignore a holder: the adapter reclaims the marker only where it probes the recorded holder and finds it dead, leaves it in place with `store_writer_unverifiable` where the holder cannot be decided, and refuses with `store_writer_active` where the holder is alive. All three are proved -before the socket path is read, unlinked or bound. Only the marker holder may remove a stale `daemon.sock` left by -a dead daemon and bind a new one, so two simultaneous starts on one root -resolve at the marker, exactly one listener exists, and the loser exits -without touching the socket. +before the socket path is read, unlinked or bound. Only a daemon that holds +both the placement lock and the Store marker may remove a stale `daemon.sock` +left by a dead daemon and bind a new one, so two simultaneous daemon starts on +one root resolve at the placement lock, exactly one listener exists, and the +loser exits without touching the Store or socket. **Removing the pathname is the successor's job, not the predecessor's**, and that follows from the same rule read in the other direction. A daemon's claim -on the path is its marker, so the claim ends when the marker does — which can -happen without the daemon being asked, since the Store releases the marker in -its own `terminate/2`. **No daemon unlinks on its way out at all** — not on an orderly stop, not on -any fail-stop, not in reverse cleanup — because a daemon that checked its -ownership and then unlinked would be acting across a window in which the Store -can die, the marker can be released and a successor can bind, and the -predecessor would then delete the successor's socket. The next daemon to -acquire and verify the marker removes the stale pathname before binding, which -is the one moment at which removing a socket file is unambiguously correct. If the daemon's **Store process exits**, it closes the listener and every -connection before anything else and then exits; no connection outlives the -daemon's ownership of the root. An earlier revision wrote that as "its Store -child exits **or the marker can no longer be proved held**", which named a -check that does not exist: nothing polls the marker, and the read-only -ownership call a revision once invented for it was withdrawn with the unlink -it existed for. **The marker's lifetime is the Store process's lifetime** — -`Loopex.Store.Local` takes it at start and releases it in its own -`terminate/2` — so the Store's exit *is* the event, and there is no second -condition to observe. +on the path is its placement lock plus its successfully opened Store. **No daemon unlinks on its way out at all** — not on +an orderly stop, not on any fail-stop, not in reverse cleanup. The next daemon +to acquire and verify the placement lock and marker removes the stale pathname before binding, +which is the one moment at which removing a socket file is unambiguously +correct. + +M5 also closes the placement gap behind that rule. A Store self-stop invokes +its best-effort marker release before the daemon can react, so the marker alone cannot protect the +old Runtime Control. The independent placement lock names the daemon OS process +and stays held through every fatal halt. While the predecessor daemon and its +Control remain live, a contender receives the placement live-owner refusal and +cannot open the Store or touch the socket. After the predecessor halts, +verified stale-owner recovery reclaims the placement lock; the successor then +acquires or recovers the Store marker and removes the pathname. The forced +interleaving witness holds predecessor Store-EXIT handling after the release +attempt returns, +starts both a separate-VM contender and a same-VM second acquisition and proves +both refuse while the old Control is live, then releases the predecessor to +fail-stop and proves one successor starts by stale-placement recovery. There is +no interval with two active Controls for one `{Store identity, runtime_id}`, +preserving accepted ADR 0008; Store commit fencing alone is not treated as +placement safety. + +After composition the daemon owner resolves and monitors the exact `Control` +and `EventDispatcher` pids for that runtime generation. Either `DOWN`, or a +child lookup that identifies a replacement while the daemon is serving, is +fatal `runtime_lost` even when the root supervisor survives. An empty +replacement would erase core session or attachment state while daemon leases, +reservations and sockets still claim it. Those monitor messages are expected +only once deliberate runtime teardown begins. During active `quiesce/1`, root +loss remains `runtime_lost`. A captured-Control event first checks the retained +exact root pid: dead root selects `runtime_lost`, while live root with lost or +replaced Control invalidates the drain as `drain_failed`. A captured- +EventDispatcher event checks the retained root and Control pids in that order: +dead root selects `runtime_lost`; live root with absent or dead Control selects +`drain_failed`; and both exact pids live selects `runtime_lost` for isolated +dispatcher loss. The checks are nonblocking and call neither process nor the +supervisor, so root exit and Control-triggered `:rest_for_one` each retain one +classification in every monitor/link-message order. Later monitor events +are cleanup-only after the first class is latched. Tests kill each child with +controller and observer attachments live, force both monitor orders for a +Control restart during quiesce, force root/child messages in both orders for a +root exit, and force dispatcher-only loss with root and Control still live. +They prove the exact fatal class, close and absence of stale daemon +accounting. A healthy branch proves marker +absence and immediate reopen; an injected unlink or parent-sync failure leaves +a complete residual that follows the adapter's live, dead and unverifiable +holder rules. + +The shutdown fence does not give the quiesce caller a Store handle. The first +census is one atomic `Control` operation: it sets `quiescing: drain_id` and +returns the entries and ordinary coordinator pids. From that point, create, +resume, attach and ordinary coordinator-route requests ordered after the +barrier return `runtime_unavailable`. Create and resume perform their Store +work inside their serialized `Control` calls: when either call is already being +handled it finishes its Store work and entry-or-dormant decision before +`begin_quiesce/1` can be handled, and when the gate wins it refuses that call +before Store access. Every handled-first path that leaves a coordinator writer +installs its entry; a committed create whose owner cannot start is durable and +dormant with no writer, so it needs no shutdown fence. The +gate freezes the census key set until every fence disposition is known. +Owner-ready, owner-replayed, owner-unavailable and monitor messages may update a +retained entry, but may not delete one; an owner-group `DOWN` for +`:awaiting_owner_barrier` answers its waiters `runtime_unavailable`, retains the +entry and its fence inputs, and never calls `do_start_owner`. The gate is +terminal because `quiesce/1` is a shutdown operation. + +That transition is single-use. `begin_quiesce/1` succeeds only when +`quiescing` is unset; a concurrent or later call that finds any drain ID already +installed returns `{:error, :runtime_unavailable}` before starting per-session +work. Two callers therefore cannot admit two aborts, terminate the same +coordinator twice or start competing fence-mode writers. A forced concurrent +case proves one caller owns the drain and the other starts no worker. + +The daemon-scoped, `@doc false` `quiesce/1` entry point starts and monitors one +private phase-owner process; +it does not change the arbitrary caller's `trap_exit` flag. The phase owner +monitors that caller, sets `trap_exit`, owns the census and deadlines, and starts +the linked, non-trapping per-session workers. It is a pure receive coordinator: +child lookup, `Control`/coordinator calls, supervisor calls and temporary-owner +waits all run in workers, so caller `DOWN` and worker exits cannot wait behind a +blocking call. One abnormal worker `EXIT` becomes +only that session's conservative phase result while siblings finish. Phase-owner +death makes the public call return `runtime_unavailable`; caller death makes the +phase owner terminate every linked worker. For the daemon, the caller is +its unlinked outer helper, so killing that helper during fail-stop also removes +the phase owner and its worker tree before any later phase can start. + +Core owns four fixed phase clocks rather than accepting a daemon deadline: +`quiesce_admission_ms: 70_000`, `status_census_ms: 10_000`, +`coordinator_termination_ms: 330_000`, and `fence_budget_ms: 130_000`. Every +clock is one absolute instant shared by the whole bounded population. The first +reserves its initial 5,000 ms for exact-Control resolution and +`begin_quiesce/1`, admits all per-session aborts concurrently before its +5,000 ms kill/reap tail, and leaves at least 60,000 ms for the maximum two-call +drain-only local-Store path. A failed initial projection returns +`runtime_unavailable`; an unanswered per-session admission is `unsettled` and +releases no cleanup. + +The initial projection is also the process and result bound. `Control` +maintains a monotonic set of session IDs whose `writer_started?` fact became +true. `begin_quiesce/1` installs the gate, freezes that writer-domain set and +projects only those IDs. The bit and set membership are written in the same serialized Control +callback immediately after `DynamicSupervisor.start_child` returns `{:ok, +coordinator}` and before later attach or readiness work. If that eligible set exceeds 64, the phase owner returns +`{:error, :runtime_unavailable}` before it spawns any per-session worker. The +terminal gate remains installed because this is a shutdown-only entry point. A +daemon cannot reach that branch under its activation-plus-reservation invariant, +while another internal caller cannot turn one call into an unbounded process +fan-out or cross-application result. One witness holds more than 64 no-writer +dormant entries beside 64 writer-domain IDs and proves the no-writer entries +are omitted from all three lists and the fence map and spawn no workers; a separate +65-eligible-entry core witness asserts the refusal and zero per-session workers. + +For each active coordinator from that census, the helper sends one +drain-specific call. In the coordinator mailbox that call atomically closes +ordinary command admission and then proposes the existing abort. An ordinary +command processed before it is part of the run the abort observes; an ordinary +command processed after it refuses `runtime_unavailable`. Internal owner, +commit, cancellation, receipt and recovery messages remain admitted so work +already linearized can settle. Therefore `rejected_no_active_run` is evidence +that no later ordinary command can start in that coordinator, rather than a +snapshot a delayed routed command can invalidate. A forced witness holds a +pre-barrier prompt after `Control` routing but before +`SessionCoordinator.command/3`, lets the drain call return +`rejected_no_active_run`, then releases the prompt and proves it refuses with no +prompt record. Paired create and resume calls are forced in both `Control` +mailbox orders. If the gate is handled first, the call refuses with no entry or +durable record; if the create or resume call is handled first, its Store +operation and entry-or-dormant decision complete before the gate. A resulting +entry whose writer was started follows the ordinary terminate-and-fence path; a +post-commit owner-start failure has no writer, remains dormant and is omitted +from the drain projection and fence map. + +At most 64 admission calls run concurrently. At +`admission_deadline - 5_000` the phase owner kills every unanswered worker and +requires its exact exit by the outer instant. A coordinator call already queued +may later admit only the deterministic paused abort; no cleanup is released for +it, and termination plus exact-ID recovery and fencing conservatively resolves +its disposition. The phase never waits through an arbitrary coordinator +mailbox backlog. + +Every committed abort pauses at the existing cleanup split. Only when every +admission is committed or definitively `rejected_no_active_run` does one +phase-owner transition compute `budget_ms` from the committed paused-cleanup +set, start `cancellation_deadline = now + budget_ms`, and release every cleanup +together. An empty set has budget `0`; if any admission failed, remained +ambiguous or did not answer, no cleanup is released and the budget used is `0`. +All released sessions share that one absolute instant. The status census begins +at the earlier of every released cleanup reaching a terminal state or that +deadline, without a per-session, timer-delivery or late-message restart. A +maximum-population witness releases 64 cleanups at the same controlled instant, +proves an all-early set advances as soon as all are terminal, then holds a mixed +set through the cutoff and proves the deadline advances classification once +rather than 64 times in sequence. + +The drain abort's identity is restart-recoverable. Core adds +`SessionState.drain_abort_command_id/2`, using the existing deterministic +`stable_id/3` discipline under the `"drain_abort"` namespace with the session +ID and pre-admission `owner_epoch` from the durable head. The Store binds that +identity on first presentation to the exact journal version, owner incarnation +and canonical abort digest. The +result is both the abort `command_id` and its Store `tx_id`; it grants no +authority, while the Store still binds the proposal to the current owner +incarnation and canonical mutation. The namespace prevents accidental +cross-kind collisions but is not reserved from a client supplying the same +binary. Live admission and restart therefore validate the retained +command-idempotency row's exact abort type, canonical drain-abort digest and run +binding before replay; transaction status alone never proves that an abort was +committed. During the live drain, a row deliberately pre-bound to another +command makes abort admission fail as `idempotency_conflict`; cleanup is not +released, the session is reported unsettled, and termination/fencing proceeds. +On restart, exact replay of a different committed command proves that no drain +abort occupied that candidate, so recovery treats it like an absent drain +candidate and continues. Only a committed status whose replay binding is +missing or malformed keeps activation unavailable. The ordinary coordinator presents that +commit once. On `commit_unknown` it returns the candidate ID and head and +releases no cleanup. + +After that coordinator is `DOWN`, fence mode queries the exact abort ID. A +terminal commit is replayed before fencing from the resulting head; a terminal +non-commit proceeds; `:absent` is non-terminal and proceeds to the fresh fence +CAS, so whichever of the delayed abort and fence moves the original head makes +the other stale; `:unavailable` proposes no fence and returns a tagged +abort-stage unknown. After a crash, existing-session activation replays, reads +current epoch `E`, and queries `drain_abort(E)` and, only on absence or exact +replay that proves a different-binding collision/no-drain, `drain_abort(E - 1)` +when a predecessor exists. A retained commit is replayed +from the journal only when its exact abort type, digest and run binding match. +An exact different binding is collision/no-drain and continues the bounded +search; a terminal non-commit resolves that exact operation; an unattributable +committed, unavailable or malformed result stays fail-closed. Only then does +activation resolve the current and predecessor epoch fence IDs before ordinary +succession. It admits +no command until exact-ID recovery and its fresh-ID owner-succession CAS both +finish. Abort and fence discovery each add at most two status queries to +existing-session activation. A fresh create adds none. The ordinary shutdown +fence remains at most three Store calls; ambiguous-abort resolution plus that +fence is at most four. + +The abort namespace is single-use per owner epoch. The terminal quiescing gate +permits one drain abort per session in a daemon lifetime, and a later lifetime +must commit fresh owner succession before admission or another drain. Correct +core therefore cannot bind `drain_abort(session_id, epoch)` to a second journal +version. Forced restart cases cover a same-epoch stale-journal result, a +predecessor-epoch commit after a fence advanced the head, both candidates +absent, unavailable and malformed status, attempted same-epoch reuse, and a +client command deliberately pre-bound to the derived ID with a different +digest and type. + +Attach has a second serialized cut because its registration spans Control and +EventDispatcher. Its state-changing Control pending-row reservation is the +linearization point against `begin_quiesce/1`. Gate first refuses with no +pending or dispatcher state and no borrowed capacity charge. Reservation first +grandfathers only that exact transaction and dispatcher incarnation through +stage, authorize, publish and finalize or discard. Quiesce neither enumerates +nor waits for this transient attach state. During ordinary service and holder +retirement, the relay retains its ticket and the daemon slot until the real +result. During orderly shutdown, successful `seal_after_quiesce` kills the relay +task and removes an unresolved ticket; the core transaction and capacity charge +remain cleanup-owned until holder `DOWN` or runtime teardown, with no capacity +reuse after the admission cut. + +After the root-derived cancellation budget, the status census issues all at +most 64 `session_status/2` calls together under one +`status_census_ms: 10_000` instant. Their existing 5,000 ms call bound is the +work cutoff; the remaining 5,000 ms kills and reaps unanswered workers, whose +sessions are `unsettled`. + +The later termination projection is a read under the already-closed gate. It is +the first 5,000 ms of one +`coordinator_termination_ms: 330_000` clock and has +the same writer-domain session-ID set as the first census, although an entry may +have changed status or disappeared. Each domain entered the monotonic set when +its `writer_started?` fact was set immediately after the coordinator child started successfully and never cleared in +that runtime lifetime. Status alone is insufficient: dormant can mean either a +post-commit start failure with no writer or a formerly active entry, and +unavailable can follow either kind of path; in particular, a started owner whose +attach later fails is reset to `:unavailable` but may already have entered Store +succession. Entries for which the fact is false need no fence because no process +was ever authorized to write; they are deliberately absent from the bounded +projection and result. Every projected domain is fence-eligible, including a coordinator child that started +but failed before owner readiness or attach completion. Ordinary start and bit +assignment are one serialized `Control` callback: `begin_quiesce` cannot enter +until `DynamicSupervisor.start_child` returns and that callback sets the bit. If +the bounded `Control` call cannot finish, quiesce returns +`{:error, :runtime_unavailable}` and claims no census. Thus no ordinary pending +start crosses a successful projection. The +serialized projection rejects more than 64 writer-domain IDs +as `{:error, :runtime_unavailable}` before spawning per-session work. A correct +daemon cannot reach that branch because the activation set plus reservations is +bounded at 64, even when it has accumulated more no-writer dormant entries. + +After that projection, the phase owner issues all at most 64 +`DynamicSupervisor.terminate_child/2` calls together. They serialize through +the one session supervisor and each child has `shutdown: 5_000`, so the work +cutoff is `termination_deadline - 5_000`: 320,000 ms after the projection +allowance. At that cutoff the phase owner directly kills every coordinator still +alive and every still-live termination worker blocked in the suspended +supervisor call, then reserves the final 5,000 ms for every exact coordinator +`DOWN` and worker exit. A missing signal at the outer instant returns +`runtime_unavailable` and starts no fence. Only after +all enumerated ordinary coordinators are `DOWN` does the phase owner start a +fence operation for every eligible entry through an operation-ID handshake that +cannot authorize Store work after its deadline and leaves no pid after timeout +cleanup. A start handled just before the instant may still materialize a waiting +pid just after it, which the later checks and reap make harmless. The phase owner preallocates and retains `op_ref`, then +sends `start_fence(op_ref, phase_owner, session, absolute_deadline)` to Control. +In its serialized mailbox Control first rejects an expired deadline, otherwise uses +`spawn_monitor` with its Store handle captured inside core. The new fence-mode +`SessionCoordinator` first links to the phase owner, handshakes with Control and +waits. Control records that exact pid in the frozen entry and sends +`{fence_started, op_ref, pid}` **directly to the phase owner**; it does not send +`go`. The phase owner installs its own monitor of that pid, retains +`{op_ref, pid, monitor_ref}`, and, only while the shared fence deadline remains +live, sends `authorize_fence(op_ref, absolute_deadline)`. Control validates the +registered operation and rechecks the absolute deadline before sending +`{go, absolute_deadline}`. The fence process checks that same deadline when it +receives `go` and refuses before any Store operation if it has expired. The +phase owner never receives a Store handle. + +The phase computes two named absolute instants once for every eligible entry. +At `fence_work_deadline = t0 + 125_000`, the phase owner sends +`cancel_fence(op_ref)` for every unresolved operation, kills every exact +already-authorized pid, and permits no further Store operation to begin. If +Control has not handled start before the work deadline, the deadline carried by +that earlier message makes it refuse without spawning. A started but +unauthorized operation makes Control kill the exact waiting pid and acknowledge +cancellation only after its own monitor receives `DOWN`. Authorize before cancel +means the phase owner already owns the exact pid and monitor; its kill is +idempotent and it awaits `DOWN`, while Control consumes the same terminal +operation idempotently. The phase owner uses no separate waiter worker in the +fence phase. A Store call authorized and begun before the work cutoff keeps its +ordinary ambiguity. Control cancellation acknowledgements and exact `DOWN`s are +consumed only until `fence_deadline = t0 + 130_000`. A missing acknowledgement +or surviving pid at that outer deadline returns `runtime_unavailable`; no new +head read, status query, transaction or exact re-presentation may begin after +the work cutoff. + +The Store-work cutoff is `125_000` ms: four sequential local-Store calls at its +fixed 30-second call timeout cover abort-status recovery plus the worst fence +path, and five seconds cover the Control start/authorize handshake. All entries start concurrently against that one cutoff; clocks are never restarted per entry. A separate outer deadline at `130_000` ms reserves five seconds to kill and reap every exact pid after the work cutoff. The result reports that outer bound separately as `fence_budget_ms`; the existing +`budget_ms` remains the cancellation budget derived from committed session +graces, and the daemon stop line and operator page show both. Sixty-four held +fence paths plus one ordinary sibling case prove cancellation starts at the +125-second work cutoff, every exact pid and operation is absent by the 130-second +outer fence deadline, and the sibling can finish. + +The other fixed clocks have matching maximum-population witnesses. One suspends +the initial Control projection and proves `runtime_unavailable` inside its +5,000 ms gate with no per-session worker. Another holds 64 admission calls past +their work cutoff, proves every worker is reaped by 70,000 ms, no cleanup is +released and a late deterministic abort is recovered rather than mistaken for +absence. A third holds 64 status calls and proves all become `unsettled` with no +worker left by 10,000 ms. A fourth suspends the session supervisor with 64 +coordinators: the direct-kill cutoff runs at 325,000 ms, every exact coordinator +`DOWN` and blocked termination-worker exit arrives by 330,000 ms, and the worker +population is at baseline before fencing. Resuming the supervisor afterwards +starts no delayed coordinator, result or Store call. Each boundary is run on +both supported toolchain pairs at its smallest admitted population and at 64. + +Fence mode is the only start admitted under the terminal gate. Its process is +the sole serial session owner for one abort-unknown resolution, one +`advance_owner` transaction and, on `commit_unknown`, one exact byte-identical +re-presentation of that fence transaction, reports a closed disposition, then +exits. Phase-owner death ends every such coordinator, although any Store call +already delivered retains its ordinary ambiguity. Neither the caller nor the +daemon writes Store truth directly. Forced deadlines cover cancel before Control +handles a delivered start after its carried deadline, after spawn before the phase owner receives it, +after receipt before authorization, and after authorization before `go`, as +well as before the head reply, inside the first fence transaction, and before +and inside exact re-presentation. Every cut leaves no temporary coordinator or +waiter and starts no later Store call while a sibling session finishes normally. +A suspended ordinary session-supervisor witness proves fence start still +completes through Control and that resuming the supervisor creates no late +coordinator. A forced `:awaiting_owner_barrier` case releases its owner group +after the first census and before the termination census. It proves the waiters +receive `runtime_unavailable`, the entry remains in both censuses, no replacement +ordinary coordinator starts, and the fence-mode process is the sole writer. This +keeps the founding one-serial-owner rule true during shutdown as well as service. + +Fence transaction ID and proposed incarnation are deterministic under separate +namespaces from `{session_id, expected_owner_epoch}`. Journal version remains +part of the Store's immutable transaction binding and canonical digest, but not +the recoverable operation identity. +The current fence owner resolves an initial `commit_unknown` by one +byte-identical re-presentation, not by `transaction_status/4`, because status +carries no immutable binding and could describe a conflicting retained +transaction. That exact re-presentation is available only while the fence owner +still holds the transaction bytes. + +A `{:not_committed, :tx_id_conflict}` on the **first** presentation is a +different, reachable branch: a client command may already have bound the +deterministic ID. Fence mode chooses no alternate identity and makes no retry; +it reports `{:unknown, :fence, head}` and the session remains `unsettled`. +That is conservative because the live process cannot attribute the retained +binding from the refusal alone. Evidence deliberately pre-binds the current +fence ID with a different client transaction and distinguishes this branch from +a conflict on exact re-presentation, which is an invariant violation after the +fence owner has already presented its own binding. + +After restart a successor first replays the journal, then reads the current durable owner epoch `E`. It first +queries `transaction_status/4` for `drain_fence(session_id, E)`. A terminal +non-commit resolves a fence that lost without advancing the epoch. For a +committed result, recovery requires a replayed `owner_advanced` record carrying +the fields the adapter actually journals: matching prior and new owner epochs, +the deterministic proposed incarnation and the deterministic transaction ID. +The replayed record's stamped journal version yields +`expected_journal_version = record.journal_version - 1`; together with the +session ID from journal context and the prior epoch, those values reconstruct +the exact `Store.advance_owner/6` candidate and its canonical mutation digest. +Recovery requires every journal field to match that reconstruction. A replayed +different binding is a client collision and proves this candidate was not a +fence; a committed status with no attributable replay stays unavailable. A +matching fence while the head still reports `E` is inconsistent +and stays unavailable. Only if that identity is absent or a proved collision does the successor query the bounded predecessor +identity for `E - 1`, when such an epoch exists. A committed result there +resolves the fence that advanced the head to `E` only when the same +reconstruction matches every replayed field; a proved different +binding is collision/no-fence. A terminal non-commit also +resolves that exact operation. Absence at both identities means neither +candidate for the immediately unresolved stop is retained; it does not erase +older fence history. Store unavailability, exit, malformed output, or any result +inconsistent with the observed head stays fail-closed. + +The namespace prevents accidental cross-kind collision but is not reserved +from client command IDs. The terminal quiescing gate permits one fence per +session in a daemon lifetime, and a later service lifetime must commit ordinary +owner succession before activation or another drain. Correct core can therefore +present only one **core fence** binding under `drain_fence(session_id, epoch)`; +replay attribution, rather than identity-only status, makes this the +restart-safe ADR 0008 recovery path. An acquiring coordinator's already-delivered succession +may move the epoch after its `DOWN` but before fence mode reads the head. Once +fence mode has read its head, however, the gate starts no owner and every older +CAS is bound to an older head; only the fence or a competitor on that observed +head can move it. Current and predecessor fence IDs are therefore complete even +when the acquiring straggler and then the fence produce two post-`DOWN` epoch +moves. No older identity is searched. +Only after this exact-ID recovery does ordinary fresh owner succession run; no +command is admitted until it commits. + +Collision evidence covers both current- and predecessor-epoch candidates. It +reconstructs the candidate from the replayed journal fields and stamped version, +proves a different client binding is collision/no-fence, and proves a committed +status with no attributable `owner_advanced` record remains unavailable. Framing, the initialize handshake, admission records, snapshot, event and progress records, the frame ceiling, the strict UTF-8/LF rule and @@ -189,23 +766,226 @@ in that holder set and calls `release_transfers/2` for each; Control removes the same IDs and their repetition state. Each component demonitors only after its set for that holder is empty. -The monitors are installed before the snapshot scan starts. A holder `DOWN` -marks every pending attach for that holder cancelled in each serial owner; an -install step rechecks that mark and refuses rather than publishing an -attachment for a process already known dead. This covers death before, during -and immediately after the relay task's core call. - -**Replacement names one attachment.** Core attach options gain optional -`replace_attachment_id`; when present, the target must be a live attachment -owned by the same holder and session. Installation and removal are one serial -EventDispatcher transition: the named target is removed at its last emitted -cursor, its transfers are released, and the new attachment takes its place. -An absent, stale, foreign-holder or other-session target refuses +**Dispatcher replacement is an attachment-generation cut, including for an +embedded runtime.** The runtime supervisor can restart EventDispatcher without +restarting Control, so every attach transaction is also bound to an opaque +dispatcher incarnation. `init/1` returns only an `initializing` dispatcher; +its `handle_continue(:register_dispatcher, ...)` starts a linked, monitored, +non-trapping registration worker and then returns, leaving the GenServer loop responsive. +The worker resolves Control through the runtime supervisor and begins the +handshake. Resolving a sibling from `init/1` would call the supervisor while it +was synchronously waiting for this child's `start_link/3` and deadlock startup; +performing the Control call in `handle_continue` would create a second +deadlock, because `Control.handle_call(:post_commit, ...)` synchronously calls +`EventDispatcher.acknowledge/3`. + +Control atomically marks that incarnation initializing and terminally resolves +every predecessor pending transaction before it clears the predecessor's live +and pending attachment rows, repetition rows and holder monitors. Each retained +live caller receives the stable core error `:attachment_superseded`; a dead +caller's reply alone is dropped. The daemon relay settles the matching ticket +and releases its reserved or borrowed charge exactly once. Reserved, staged, +authorized and published-with-acknowledgement-lost rows take that same result +because the dead dispatcher cannot prove a usable handle or transfer survived. +Control releases their holder monitors and repetition state, never restores an +old replacement target, and treats any late predecessor stage, publish, +acknowledgement, cleanup or finalize message as cleanup-only under the old +incarnation. It then returns +a registration reference plus the acknowledged event sequence from each active +Control entry to the worker. The worker sends that seed to the dispatcher. +While initializing, the dispatcher refuses ordinary external operations with +`dispatcher_initializing` but **accepts and replies to acknowledgement calls**, +merging each event position into its local map. It merges the Control seed by +per-session maximum, so a post-commit acknowledgement delivered during the +handshake cannot be overwritten by an older seed. + +After the dispatcher reports the merged seed to the worker, the worker asks +Control to finalize the registration reference. Control validates the exact +incarnation and moves it only to `ready_pending`; it does not open attachment +admission. The worker sends the final token to the dispatcher and exits. The +dispatcher marks itself ready and sends an asynchronous ready notice to +Control; only when Control consumes that notice does it allow attach or +attachment-authorized commands. Thus Control never waits for the dispatcher +while the dispatcher waits for Control, and Control never opens a call path to +an initializing dispatcher. A lookup, worker death or handshake failure stops +the initializing dispatcher without serving an ordinary operation; dispatcher +death kills the linked worker, and exact-incarnation validation rejects every +late predecessor message. No registration worker survives its dispatcher. The +projection contains session IDs and acknowledged positions only, no Store +handle. + +Every stage, publication acknowledgement and finalization carries the +dispatcher incarnation. A late message from a predecessor refuses and cannot +recreate a cleared row. Old handles are stale and callers attach again. The +dead dispatcher owned the transfer descriptors, so its death closes them as +ADR 0028 requires; the successor never claims they survived. Seeding the +watermarks is as important as clearing the rows: without it, a replacement's +empty `acknowledged` map would make a fresh snapshot scan unbounded past an +unacknowledged outbox row even though Control retained the last safe event +sequence. A forced witness holds Control in `post_commit` while the successor +registers: the replacement accepts and merges the synchronous acknowledgement, +both operations complete, and the ready watermark is the maximum of the seed +and the acknowledgement. This is the interleaving that a synchronous +`handle_continue` registration would deadlock. + +The monitors are installed before the snapshot scan starts. Control retains a +holder-liveness tombstone on every attach transaction, beside its +`reserved | staged | authorized | published` phase. A holder `DOWN` before +publication marks the transaction cancelled in each serial owner; an install +step rechecks that mark, discards the staged row and refuses +`:holder_unavailable` rather than publishing an attachment for a process +already known dead. The tombstone is retained through a publication race, so +death immediately after the relay task's core call cannot be forgotten merely +because the publish acknowledgement is still in another mailbox. + +**Replacement names one attachment, and installation is a cross-process +transaction.** Core attach options gain optional `replace_attachment_id`; when +present, the target must be a live attachment owned by the same holder and +session. The existing bounded, read-only `begin_attach` preflight remains, but +M5 replaces the state-changing dispatcher-then-Control calls with one +`:infinity` Control call. Its `handle_call` revalidates the request, retains the +caller's `from` value and a caller monitor, reserves the transaction and returns +`{:noreply, state}`. Control owns the resulting asynchronous state machine keyed +by attachment identity and continues to a defined disposition if that caller +dies, dropping only the reply route. **Control allocates that identity.** +Its state gains a per-generation attachment counter and moves the existing +`fresh_id/3` derivation for both `attachment_id` and `incarnation_id` out of +EventDispatcher's install step. During reservation Control increments the +counter, derives both IDs, and binds them to the session generation, dispatcher +incarnation, holder and optional replacement target. Discarded IDs are not +reused. EventDispatcher receives those supplied IDs, stages and later installs +exactly them, and never mints a second identity. Control first reserves that +pending row. It drives every later step by exact-incarnation messages and never +blocks its mailbox in a dispatcher call; dispatcher acknowledgements return +directly to Control, leaving `post_commit` serviceable. EventDispatcher stages +the new cursor barrier and queue under that identity without +publishing it and without removing the old target. Control validates its +generation/status again and marks the pending row authorized but not live. +EventDispatcher atomically publishes the staged row and, for replacement, +removes the named old row at its last emitted cursor and releases its transfers. +That acknowledgement is the transaction's **commit point** within that +dispatcher incarnation. After it, while that incarnation remains current, +Control can only roll forward to the terminal result selected by the holder +tombstone; it can never restore a replacement target the dispatcher already +removed. If Control consumes the acknowledgement while the holder is live, its +final idempotent transition makes the new row live for the holder gate and +removes the old routing row. A later `DOWN` takes the ordinary full-holder +cleanup path. If Control consumes `DOWN` first and later learns publication +committed, it marks the transaction `published/down`, never creates a live +routing row, and requests idempotent dispatcher removal of the new attachment +and release of its transfers. The dispatcher may already have removed it on +its own holder monitor; either answer is the same cleanup acknowledgement. +Only then does Control send `GenServer.reply/2` with +`{:error, :holder_unavailable}` to a caller that is still alive. The attach +result is replied only by Control and only after both owners acknowledge the same transaction identity +and, for the dead-holder terminal, agree that the new row is gone. + +Snapshot preparation runs in a linked, monitored, non-trapping dispatcher +worker, at most one per pending transaction. Worker death refuses that +transaction; dispatcher death ends every such worker. The pending-attachment +charge bounds the group at 512 in daemon use, and embedded construction uses +the same core pending-row ceiling. The dispatcher loop therefore remains +available for acknowledgements and cleanup throughout a scan. + +The pending-row reservation is also the exact linearization point against +`begin_quiesce/1`; the read-only `begin_attach` validation is not. If the +terminal gate is installed first, reservation refuses `runtime_unavailable` +and no dispatcher row, borrowed replacement charge or holder monitor exists. +If reservation wins first, that exact transaction and dispatcher incarnation +are grandfathered through only their stage, authorize, publish, finalize or +discard messages. The gate admits no new reservation. Before publication a +refusal discards; after publication the existing roll-forward rule still +applies. Quiesce neither awaits nor enumerates the transaction because it +changes no durable session truth. During ordinary service and connection +retirement the relay retains its ticket and reserved daemon slot until the real +result. During orderly shutdown the post-quiesce seal removes an unresolved +ticket after killing the caller task, while the transaction and charge remain +until holder cleanup or terminal runtime teardown; admission is already closed, +so the charge is never reused meanwhile. + +Before the commit point, every refusal or holder death has an idempotent +discard path in both owners. Initiating-caller death drops only its reply route +and the state driver still reaches a terminal disposition. A Control refusal after dispatcher staging +discards only the new pending row and leaves the replacement target and its +transfers untouched. A holder `DOWN` removes live rows and selects discard for +unpublished transactions or released/no-live-route for published ones. After +the commit point, Control drives that idempotent terminal transition even if +the transient caller or relay task is gone. A dispatcher-generation cut is the +one exception: the replacement handshake first selects +`:attachment_superseded` for every half-finished transaction, replies to each +live retained caller, then clears both sides before the successor becomes +ready. An embedded caller therefore observes that stable core result. In the +daemon, the exact dispatcher `DOWN` independently selects fatal `runtime_lost`; +fail-stop clears the relay ticket and charge, so the transport may see that +fatal close instead of the core reply. A Control restart is daemon-fatal under the +sentinel rule, so teardown is the other case that interrupts that driver. It +never tries to restore a transfer already released and never reports success +before agreement. + +Daemon capacity uses one explicit equation: `charged = live + nonreplacement_pending ++ replacement_pending - borrowed_replacement_targets`. Each valid replacement +pending row borrows exactly the named live target's one charge until commit or +discard, so replacement at 512 is net-zero; an ordinary pending attach consumes +a new charge. Pending rows are not live attachments, and the daemon cannot +undercharge or admit a 513th charge. The steady-state +invariant, whenever the registered dispatcher is ready, is exact equality of +the live attachment-ID sets. A published/dead cleanup may transiently leave one +side ahead only while its transaction identity and daemon charge remain +retained; the cleanup acknowledgement restores equality before either is +released. During dispatcher replacement both are cleared before ready, and +pending rows must return to zero. + +Borrowing is exclusive by the exact live target identity +`{holder, attachment_id, attachment_incarnation}`. The connection first installs +its exact `pending_ticket(origin_id, :attach, nil)` at the relay. The connection +registry is the daemon's one serial reservation owner; it then installs +`borrow[target] = {request_binding, primary_ticket_id}` and synchronously asks +the relay to promote that exact primary. The call direction is always +registry-to-relay. The relay never synchronously calls the registry, because +the daemon owner also calls the relay for cut, freeze and seal. + +An exact repetition of `request_binding` makes its distinct pending origin +`waiting(primary_ticket_id)` and starts no second task or core transaction. A +different request for an already borrowed target terminalizes its origin as the +inherited `attachment_conflict`, with no second borrow or task. Before primary +promotion, relay refusal, connection-incarnation loss or an admission cut +releases the exact borrow synchronously in the registry; after promotion, only +the real result converts or releases it, while shutdown abandonment retains it +through runtime teardown. Two pipelined +replacements therefore cannot each subtract the same live target from the +capacity equation. Core independently reserves and revalidates the same exact +target in Control so embedded callers receive the same exclusion without +depending on daemon state. + +An absent, stale, foreign-holder or other-session replacement target refuses `:stale_attachment` in core, mapped to generation 2's inherited `attachment_conflict`, and changes nothing. With no selector, a distinct request installs another attachment even when that holder already owns one for the session. Exact repetition of the same attach identity returns the same live -handle rather than installing a duplicate. +handle rather than installing a duplicate. A distinct concurrent replacement +of a target already reserved by another pending transaction refuses +`attachment_conflict`; the first reservation and target remain unchanged. +Forced cases change Control's +generation/status between staging and validation for ordinary attach and for a +replacement at the ceiling, then assert no orphan, the old replacement remains, +both live maps agree, transfer disposition is exact, pending rows are empty and +the daemon count never exceeds 512. Ordinary, replacement, exact-repetition and +published/dead cleanup cases also assert the same attachment and incarnation IDs +in Control's pending/live rows, the dispatcher's staged/live row, the returned or +replayed handle and the cleanup acknowledgement; any second minted ID fails the +case. + +Shutdown cases force the gate immediately before reservation and, with +reservation first, pause before dispatcher stage, before Control authorization, +and after publication before finalization. At the last cut, ordinary and +replacement attaches force both Control mailbox orders: publish acknowledgement +then `DOWN`, and `DOWN` then publish acknowledgement. The first may finalize a +handle before ordinary holder cleanup; the second returns +`:holder_unavailable` only after idempotent dispatcher cleanup. For replacement, +neither order restores the already-removed target or its transfers. Every case +ends with an exact result or cleanup acknowledgement, zero pending rows, equal +live maps, the correct transfer disposition and no retained charge or attachment +count above 512; none delays the durable drain. ADR 0023's boolean remains the wire field on both protocol adapters. Each adapter permits only one connection attachment, so on `replace: true` it maps @@ -214,20 +994,55 @@ the sole handle it already holds to core's `replace_attachment_id`; on use the core selector directly and are the case for which several candidates can exist. -**Holder cleanup and daemon ceiling release are one acknowledged sequence.** -The daemon registry owns connection and attachment reservations. When a -connection ends it marks that holder's installed and in-flight slots -`closing`; it does not release them merely because its own monitor fired. The -admission relay first accounts for every ticket from that holder. The registry -then calls the internal, idempotent `Runtime.release_holder/2`, which returns -only after EventDispatcher and Control contain no attachment for the holder; -a cleanup already caused by their monitors is success. Only that reply frees -the daemon slots. If core cannot confirm the cleanup, the slots remain charged -and the runtime failure follows the daemon's fatal path. A late attach cannot -appear after confirmation because the relay had already settled every holder -ticket. This ordering prevents the registry from admitting a replacement -while core still holds the old attachment and makes the 64-per-session and -512-per-daemon ceilings true at every instant rather than eventually. +**Holder cleanup, request retirement and connection-slot release are one +acknowledged sequence.** The connection registry owns accepted slots and the +daemon's activation and attachment reservations. Before a connection can send +any admitted request, it +synchronously registers its pid and fresh connection incarnation with the +admission relay, which installs its own monitor. Every one of the connection's +at most 32 active request slots has one relay origin row keyed by +`origin_id = {connection_incarnation, request_slot, request_sequence}` and +carrying the operation class. The monotonically increasing sequence prevents a +late result from a prior use of the same local slot from touching its successor. +A lightweight call uses its permit row. A ticketed call first installs +`pending_ticket`; create, an activation-capable resume and attach then pass that +exact origin through the registry's reservation handshake, while another +lease-authorized mutation sends its descriptor to the lease owner only after +the pending row is acknowledged. Only the owner named for that path may promote +the exact row to `ticketed(task_pid, monitor)`, with task start ordered before +acknowledgement. + +When the connection ends, the registry changes its accepted slot from `live` +to `closing`; it does not release the slot merely because its monitor fired. +The relay terminalizes every unpromoted origin row for that incarnation and +retains every promoted ticket until its real result, fatal disposition or +successful shutdown seal. Promotion after terminalization refuses and starts +no task. + +The registry must remain responsive while core cleanup runs. In the same +callback that changes `live` to `closing`, it destroys the socket/output buffer +and starts one unlinked monitored cleanup worker identified by +`{connection_incarnation, cleanup_ref}`. That worker alone calls the internal, +idempotent `Runtime.release_holder/2`, which returns only after EventDispatcher +and Control contain no attachment for the holder; cleanup already caused by +their monitors is success. The operation is internal cleanup admitted even +after core's quiescing gate, because orderly step 3 closes holders only after +quiesce. Its exact success acknowledgement sets `holder_cleanup_acked`; a stale +ack is a no-op. Only the exact normal `DOWN` after that acknowledgement sets +`cleanup_worker_reaped`. Abnormal worker exit, timeout or loss at either stage +leaves the slot charged and selects fatal `runtime_lost`. The registry never +reuses that incarnation. + +The accepted slot becomes free only under the conjunction +`closing && relay_retired && holder_cleanup_acked && cleanup_worker_reaped`, +where `relay_retired` means there is no nonterminal origin, waiter, permit, +request worker or relay task for the incarnation. Up to 512 cleanup workers may run concurrently, one per +closing slot; orderly step 3 awaits their exact acknowledgements and `DOWN`s +within its shared deadline, kills and reaps survivors at the deadline, and +takes the fatal path rather than reporting a successful stop. This ordering +prevents a late ticket or attachment after slot reuse and makes both the +connection and attachment ceilings true at every instant without serializing +accept, status or an unrelated connection behind core cleanup. The same path handles an orderly daemon close and an abrupt peer loss. For an embedded caller no daemon counter exists; the two core monitors still remove @@ -299,7 +1114,7 @@ rather than `null`, and unknown fields refuse before a facade call | entry | `residency` | `"active"` \| `"dormant"` | required | | entry | `controlled` | bool | required | | result | `next_after_session_id` | binary identity | present **exactly when** more entries exist | -| result | `index_full` | bool `true` | present **exactly when** the index is at its 4,096-entry ceiling | +| result | `index_full` | bool `true` | present **exactly when** the index is at its 4,096-entry ceiling; the row-size derivation below guarantees that row ceiling fits inside 4 MiB | Entries are ordered by session ID bytes ascending, and carry nothing else — no content, no durable session state. @@ -312,7 +1127,7 @@ no content, no durable session state. | result | `placement_identity` | binary identity | required | | result | `daemon_incarnation` | binary identity | required | | result | `socket_path` | string | required | -| result | `connections` | integer, accepted connections currently open | required | +| result | `connections` | integer, occupied accepted slots: provisional (including aborting) + live + closing | required | | result | `connection_limit` | integer, 512 | required | | result | `attachments` | integer | required | | result | `attachment_limit` | integer, 512 | required | @@ -344,31 +1159,77 @@ The rule is that **a reservation counts**: cleanup-pending attachment slots, for the same reason `activations_used` does; a connection `DOWN` does not lower it before core confirms holder cleanup; -- `connections` counts accepted connections, reservation-free by nature. +- `connections` counts occupied accepted slots: `provisional` (including its + aborting substate), `live` and `closing`; + socket death alone does not advertise headroom while an origin row or holder + cleanup remains. So `activations_used` may exceed `active_sessions` for as long as a call is in flight, and settles to it. Reporting the set alone would advertise headroom the very next call would refuse. -**At the attachment ceiling a named replacement is net-zero, and it reserves -that way.** A replacing attach ends one attachment and installs one, so it -needs no free slot — but the daemon reserves before it calls core, and a naive -reservation would refuse at 512 a request that leaves the count at 512. So a -replacing attach takes an **atomic net-zero reservation**: in the daemon's -serial owner it claims the slot held by the exact -attachment ID to which the connection's `replace: true` was mapped, and it converts or releases that claim through the -same table every other reservation uses, so the count never moves and no -second caller can take the slot in between. A stale, foreign-holder or -other-session core selector refuses and releases the claim; an ordinary -attach with no selector reserves a new slot and is refused at the ceiling. - -**Create reservations bind the request, not only the command identity.** The -reservation key retains `command_id` together with the canonical digest of all -creation inputs, including `session_options`. An exact retransmission may -coalesce behind the first ticket. Reusing the command ID with different input -refuses as a command conflict and never receives the first request's success. -The binding is retained until the relay has the real core result, so a caller -disconnect cannot free the slot while its create is still executing. +**Every ceiling consumed by a ticketed core call uses one reservation-to-relay +handshake.** The connection preallocates +`origin_id = {connection_incarnation, request_slot, request_sequence}` and first +installs `pending_ticket(origin_id, class, nil)` at the relay. The connection +registry then makes the serial capacity decision and binds any reservation or +borrow to that exact origin before it synchronously asks the relay for one of +two transitions. Create and attach still have `pending_ticket`; a resume has +already bound its request worker and is `queued`: + +- `pending_ticket | queued -> ticketed(primary_ticket_id, task_pid, monitor)` + starts and monitors the one primary task before acknowledging promotion; or +- `pending_ticket | queued -> waiting(primary_ticket_id)` starts no task and + retires and reaps any queued request worker before acknowledging the waiter. + +For activation, the registry retains +`activation_binding = {kind, request_binding, primary_ticket_id, reservation}`. +A create's request binding is its `command_id` plus the canonical digest of all +creation inputs, including `session_options`; a dormant resume's is its +`{session_id, command_id}`. Exact repetition joins the existing primary, while +reuse of a create command ID with different inputs is a command conflict and a +different resume command is a different request. A resume for a session already +in the activation set needs no reservation. At the activation ceiling, a +dormant resume is refused before promotion and before core; a create instead +promotes one history-only primary that may return a historical session ID, but +an `absent` result becomes `activation_ceiling_reached` without invoking the +activation-capable create call. + +For attachment, an ordinary primary reserves one charge. A replacing primary +takes an atomic net-zero borrow of its exact +`{holder, attachment_id, attachment_incarnation}`. The registry retains +`borrow[target] = {request_binding, primary_ticket_id}`, so exact repetition +joins that primary and a different request for the target receives +`attachment_conflict` before any second borrow, task or core transaction. A +stale, foreign-holder or other-session core selector refuses and releases the +claim; an ordinary attach with no selector is refused when it cannot reserve a +new charge. + +Registry serialization keeps a duplicate from overtaking an unpromoted +primary. If the relay refuses promotion because the origin or connection was +terminalized, or because the admission cut won, the registry synchronously +releases that exact reservation or borrow and installs no waiter. Once +promotion succeeds, primary connection loss drops only its reply route: the +task, reservation and closing slot remain through the real result. Each +coalesced caller owns its distinct origin and route; its connection loss +terminalizes only that waiter. A primary result moves the relay row to +`settling(result, reservation_ref)` and is sent asynchronously to the registry; +after the registry idempotently converts or releases the exact charge, its ack +lets the relay answer and terminalize the primary and all live waiters. This +asynchronous result leg avoids a relay-to-registry synchronous call opposite +the reservation call direction. A shutdown seal that must abandon a promoted +primary terminalizes the primary and its waiter origins but retains the charge +until runtime teardown, so admission never reuses an outcome it could not +classify. + +Thus every active origin is one of `pending_ticket`, `queued`, `ticketed`, +`waiting`, `settling` or a lightweight-permit state. The exact bounds are +`occupied_slots = provisional_including_aborting + live + closing <= 512`, +`active_origins <= occupied_slots * 32 <= 16_384`, and +`relay_tasks <= promoted_primary_origins <= active_origins`; waiters consume +origins but start no task. A dead accepted slot remains `closing` until its last +origin and holder cleanup are terminal, so reconnect churn cannot evade either +equation. **`session.acquire_control`** @@ -412,21 +1273,26 @@ errors answering one request: each carries that request's `request_id`, no | Code | Answers | Carries beyond the envelope | | --- | --- | --- | | `control_held` | `session.acquire_control` | **Nothing.** It does *not* carry the current epoch: an epoch is authority-shaped, and handing one to a client that was just refused is exactly the value it must not have. An earlier revision of ADR 0033 said it named the current epoch; that is withdrawn | -| `control_not_held` | `session.release_control` from a non-holder, **and every lease-authorized existing-session mutation whose combined admission gate fails** — any of the **five** conditions ADR 0033 lists: wrong connection, wrong epoch, a lease that is not `held`, a deadline already passed, or no live attachment for the pinned session. A request missing `writer_epoch` altogether is `invalid_request` instead, being malformed before the gate | **Nothing**, deliberately: the five conditions are indistinguishable on the wire, because saying which one failed would make the refusal an epoch and lease oracle. ADR 0033 fixes the gate; this is the one answer it has | +| `control_not_held` | `session.release_control` from a non-holder, **and every lease-authorized existing-session mutation whose combined admission gate fails**, except the verified dormant-session `session.resume` ADR 0033 expressly allows before attachment — any of the **five** conditions ADR 0033 lists: wrong connection, wrong epoch, a lease that is not `held`, a deadline already passed, or no live attachment for the pinned session. A request missing `writer_epoch` altogether is `invalid_request` instead, being malformed before the gate | **Nothing**, deliberately: the five conditions are indistinguishable on the wire, because saying which one failed would make the refusal an epoch and lease oracle. ADR 0033 fixes the gate; this is the one answer it has | | `control_pending` | `session.acquire_control` that waited out its deadline | nothing | -| `control_capacity_reached` | any lease operation beyond the 512 concurrent-owner cap | nothing | +| `control_capacity_reached` | an acquisition for an unrelated session that would reserve a 513th lease-owner slot; a same-session successor takes the freed process slot only after the daemon owner consumes the predecessor's exact linked `EXIT`, starts only after exact mirror pop, owner-loss classification acknowledgement and terminal holder-close or correlated-refusal settlement, and grants only after the relay's monitored `DOWN`, retirement completion and prior tickets, while renew and release use an existing owner and remain available at the cap | nothing | +| `control_owner_lost` | an acquire or release whose `owner_lost` CAS wins, or a pending/queued lease-authorized mutation claimed before promotion because its exact lease owner or fresh acquisition child is lost | nothing; this correlated form carries only its request envelope and keeps a non-holder connection open. An origin on the returned granted holder receives the mutually exclusive uncorrelated form below and closes instead; a promoted mutation remains relay-owned to its real core result | | `session_dormant` | `session.attach` | nothing | -| `daemon_stopping` | any method arriving after the daemon's admission cut | nothing | -| `session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate` | any method that validates existence first | nothing | -| `activation_ceiling_reached` | `session.create`, `session.resume` | nothing | +| `session_unavailable` | `session.inspect` after an attach to a session whose one-way daemon activation remains recorded but whose temporary core coordinator has died | nothing; generation 2 maps only core's exact `:session_unavailable` reason to this code and never parses `message`. Other inspection failures keep their existing mapping or select the daemon's runtime-fatal path | +| `daemon_stopping` | any post-initialize method arriving after the daemon's admission cut; an uninitialized peer has negotiated no encoding and receives EOF instead | nothing | +| `session_unknown`, `session_id_invalid`, `store_unavailable` | any method that validates existence first | nothing | +| `activation_ceiling_reached` | a fresh `session.create` or dormant `session.resume`; an exact historical create replay remains available through the read-only discriminator | nothing | | `composition_mismatch` | `session.resume` on a session this composition cannot serve | nothing | -The one **uncorrelated** error generation 2 adds is `control_owner_lost`, -defined below with its cursor and its close behaviour. +The same `control_owner_lost` code also has one **uncorrelated** granted-holder +form, defined below with its cursor and close behaviour. Its two exact shapes +are distinguished by `request_id` versus `session_id`; neither shape admits +the other's discriminator. **The limits input is not unchanged**, which an earlier revision's digest -table said while this pair advertised residency limits a client can read. The -added keys are enumerated so the digest covers them: +table said while this pair advertised limits a client can read. The following +seven keys are the complete generation-2 additions to initialize `limits` and +are enumerated so the digest covers them: | Limit key | Value | | --- | --- | @@ -440,6 +1306,10 @@ added keys are enumerated so the digest covers them: ADR 0023's own framing and input ceilings are unchanged; these are additions beside them, and **all five** digest inputs therefore change in generation 2. +The event queues, encoded-byte buffers and windows, aggregate retention, idle +interval and per-lifetime activation ceiling remain server-enforced; where a +client needs them they appear through the exact `daemon.status` projection, +not as undeclared initialize keys. **A connection reserves its one session before asynchronous work begins.** Its state is `unbound`, `reserving(session_id, request_id, request_digest)` or @@ -452,33 +1322,38 @@ flight, and every later request naming another session after binding, refuses with ADR 0023's existing `invalid_request` before any gate or side effect. Success converts the reservation to `bound`. A definite refusal that created -neither attachment nor lease clears it back to `unbound`; an admitted relay -ticket keeps it reserved until the real result arrives, and an unaccounted -task makes the relay fatal rather than guessing. This closes the pipeline race +neither attachment nor lease clears it back to `unbound`; in ordinary service an +admitted relay ticket keeps it reserved until the real result arrives, and an +unaccounted task makes the relay fatal rather than guessing. During orderly +shutdown the successful post-quiesce seal may remove an unresolved ticket, but +the connection reservation remains until holder or runtime cleanup and cannot +admit another request after the cut. This closes the pipeline race in which attach for one session and acquire for another could both pass while the connection still appeared unpinned. Without the rule a connection could hold a lease on one session and an attachment on another, and -`control_owner_lost` — whose close ends *the connection* — would take down an +the uncorrelated `control_owner_lost` form — whose close ends *the connection* — would take down an attachment belonging to a session that had nothing to do with the lost owner. -**`control_owner_lost` therefore carries `event_cursor` exactly when there was -an attachment to carry one for.** It is an ADR 0023 `error` record with +**The uncorrelated `control_owner_lost` form therefore carries `event_cursor` +exactly when there was an attachment to carry one for.** It is an ADR 0023 `error` record with required `code`, bounded non-secret `message` and `session_id`. A connection that acquired and never attached has no emitted cursor, and inventing one would be a lie about what it received; `event_cursor` is **absent** in that case and present otherwise. Both shapes are generation-2 vectors — one with the cursor, one without — because a client parser must accept both. -**Connections are bounded, and an earlier revision said they were bounded by +**Accepted connection incarnations are bounded, and an earlier revision said they were bounded by the attachment ceiling, which they are not.** A client may connect, `initialize`, call `session.list`, `daemon.status` or `session.acquire_control`, or sit idle, without ever attaching — so the attachment ceilings bound nothing about the number of sockets the daemon holds, and a daemon whose bound is "the attachment ceiling" has no bound on -connections at all. The ceiling is **512 concurrent accepted connections**, +connections at all. The ceiling is **512 occupied accepted connection slots**, +where occupied means `provisional` (including a handoff being aborted and +reaped), `live` or `closing`, the attachment number reused rather than a fourth 512 invented, and the -daemon reports it as `connection_limit` with the live count as `connections` -so an operator can see the headroom before it is gone. +daemon reports it as `connection_limit` with the occupied count as +`connections`, so an operator can see usable headroom before it is gone. **The slot is taken at `accept`, not at `initialize`.** A ceiling enforced only at the handshake bounds nothing that matters: a peer that connects and @@ -486,9 +1361,11 @@ never speaks holds a socket, a process and a buffer, and the daemon would count it as zero. So the listener **reserves a connection slot as it accepts** and closes the socket immediately when none is free — before any frame is read, before the peer check, with no record, because a connection that was -never admitted has no generation to be told anything in. The slot is released -when the connection process ends, which is the same `DOWN` everything else -about a connection hangs from. +never admitted has no generation to be told anything in. A process `DOWN` +closes the socket but changes the slot to `closing` while any relay origin row, +request worker, ticket task or core holder cleanup remains. The cleanup worker +runs outside the registry callback; a connection with no retained relay work +still frees only after that worker's exact acknowledgement and `DOWN`. **There is no `initialize`-time refusal for the connection ceiling, and an earlier revision of this section kept one beside the accept-time slot.** The @@ -503,11 +1380,14 @@ an operator sees the headroom instead. The peer-credential and filesystem checks are unaffected, running on connections that did get a slot; a foreign peer is closed before any of this. -Its witness is the boundary pair that matches the rule: the **512th** +Its witness is the boundary pair that matches the rule: the **512th occupied** connection is accepted, initializes and is served; the **513th socket is accepted and closed with no frame read and no record written**, asserted from the client side as an immediate EOF rather than as an error record; and -closing one of the 512 lets the next one through. A witness asserting a +closing a connection with no retained relay work lets the next one through only +after its cleanup worker acknowledges and exits, while a connection with a held +ticket remains `closing` and keeps the next peer out until that row, every +request worker and holder cleanup are terminal. A witness asserting a `capacity_exceeded` at `initialize` would be asserting a path this decision does not have. @@ -519,7 +1399,7 @@ Nothing else releases such a connection — there is no attachment to evict, no lease to expire, and ADR 0023's connection-state rules govern what a connection may *do* before `initialize`, not how long it may take. So an accepted connection that has not completed `initialize` within the **lease -term, 30 seconds**, is closed, under its **own** advertised limit key, +term, 30 seconds measured from kernel accept**, is closed, under its **own** advertised limit key, `initialize_deadline_ms`. It is a separate key carrying the same value as `lease_term_ms`, and the separation is the point: one key meaning two contracts would let a later change to the lease term silently move the @@ -536,12 +1416,34 @@ literal is computed over it. The close carries no record — the connection has negotiated nothing, so there is no generation whose error shape it could be sent in — exactly as the peer-credential refusal closes before initialize. +The listener records one monotonic `accepted_at` as soon as `accept` returns +and the provisional registry row stores the absolute +`initialize_deadline = accepted_at + initialize_deadline_ms`. That exact value +is passed unchanged into the connection process and retained when the registry +promotes the row. The registry owns the timer and the final initialize-complete +CAS; the listener, registry and connection each recheck `now < deadline` before +every handoff, promotion or initialize continuation. The timer only prompts a +check. At or after the instant, a provisional row enters exact abort/reap and a +promoted uninitialized row enters closing with EOF. An initialize result queued +before the instant but consumed by the registry at or after it loses and cannot +reset or extend the deadline. Only an exact initialize completion consumed +before the instant marks the row initialized and cancels and flushes the timer. + Its witness is the pair that must differ: a connection accepted and left silent is asserted **closed** after the term and the slot it held asserted -free, while one that completes `initialize` inside it is asserted to stay open -indefinitely with no such close. It is a long-duration bound, so it is tagged -`long_bound` and injected where it is armed, with the production default -asserted once. +free, while one whose exact completion is consumed inside it is asserted to +stay open indefinitely with no such close. Boundary cases expire after child +start while the listener still owns the socket; race expiry against +controlling-process transfer and force both its failure/listener-owned and +success/connection-owned results; hold registry promotion across the instant; +and queue initialize completion before the instant but let the registry consume +it afterwards. Every expiry closes with EOF, reaps the exact socket owner, child +and provisional or live row, and frees one slot, while the transfer race takes +exactly one ownership branch. The paired just-before cases advance once. The timer is delivered on +both sides of the completion in each case to prove it only prompts the clock +check. It is a long-duration bound, so it is tagged `long_bound`; the same +cases inject the clock at the accept-time arming point, with the production +default asserted once. The tables above are the contract for both directions; an earlier revision kept a second, prose summary of the same four methods beside them, which is @@ -553,7 +1455,7 @@ carry. | Field | Value | | --- | --- | -| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for a live-registry fatal class. The set includes `fatal:listener_lost`: listener loss stops new accepts but leaves the connection registry and existing sockets available, so the registry can make the bounded write and close them. The set excludes `fatal:connections_lost`: once that registry is gone there is no live inventory or buffer-control interface through which to write. On that class the owner closes the listener, synchronously cuts relay admission, stops the remaining components and halts; existing sockets close with the VM. The ordinary component reasons remain `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, and `fatal:relay_lost`. A lease owner's death is session-scoped and uses `control_owner_lost`. Startup classes have no socket, and `owner_lost` has no owner to write a record | +| `reason` | One of `operator_stop`, `store_lost`, `store_capacity_exceeded`, or `fatal:` for a live-registry fatal class. The set includes `fatal:listener_lost`: every live socket has already transferred from the listener to its connection process, so listener loss stops new accepts but leaves the connection registry and existing sockets available for the bounded write and close. The set excludes `fatal:connections_lost`: once that registry is gone there is no live inventory or buffer-control interface through which to write. On every fatal class the owner directly kills the listener and relay without awaiting them, sends at most one unacknowledged ordinary message asking a still-live registry to attempt its bounded writes and closes, first sends the lifecycle sentinel the exact class, unique integer status and latch instant; the sentinel starts an unawaited diagnostic helper and owns `latched_at + 35_000`, while the owner waits for the executor only until `latched_at + 5_000` and for the Store only until the earlier of its own 30-second deadline and the global instant. A suspended registry or blocked stderr cannot extend that wall-clock bound, and existing sockets close with the VM. The ordinary component reasons remain `fatal:runtime_lost`, `fatal:transfers_lost`, `fatal:workspace_lease_lost`, `fatal:executor_lost`, `fatal:registry_lost`, `fatal:custody_lost`, `fatal:capability_lost`, `fatal:relay_lost`, and `fatal:drain_failed`. A lease owner's death is session-scoped and uses `control_owner_lost`. Startup classes have no socket, and `owner_lost` has no owner to write a record | | `message` | A bounded non-secret sentence for an operator to read | There is no `retry_after_ms`. Even on `operator_stop` the daemon does not know @@ -576,8 +1478,19 @@ number to come from an accepted or proposed decision. One non-blocking attempt into a bound that already exists is the same guarantee with nothing new to justify. +**The two generations have two exact contract values.** +`LoopexProtocol.Session` remains the generation-1 compatibility facade used by +the foreground server and keeps its existing zero-arity `generation/0`, +`methods/0`, `record_families/0`, `error_codes/0`, `limits/0`, +`schema_digest/0` and generation-1-only `negotiate/2` API. M5 adds +`LoopexProtocol.Session.V2` with that same metadata and negotiation API for +generation 2; only the daemon aliases and calls it. Neither zero-arity module +can report the other generation, and the foreground server does not gain a +generation-2 route. A private canonical digest helper may remove duplicated +calculation, but the two explicit modules own their different inventories. + **This changes the generation-2 digest, and so do the error codes.** -`LoopexProtocol.Session.schema_digest/0` is taken over the generation, the +`LoopexProtocol.Session.V2.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits — five inputs, and generation 2 changes **all five**: @@ -586,10 +1499,11 @@ limits — five inputs, and generation 2 changes **all five**: | Generation | New string | | Methods | Adds `session.list`, `daemon.status`, `session.acquire_control`, `session.release_control` | | Record families | Adds `daemon.stopping` and `daemon.notice` | -| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `daemon_stopping`, the four existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`, `existence_indeterminate`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, `session_index_corrupt` or `session_index_upgrade_required`, which are startup exit classes and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 keeps for the two **attachment** ceilings — `attachments_per_session` and `attachments_per_daemon`, the "stable reason when exhausted" the attachment-lifecycle list names — and no longer for the connection ceiling, which is enforced at `accept` and therefore reaches no `initialize` | +| **Error codes** | Adds every refusal generation 2 can return and generation 1 cannot: `control_held`, `control_not_held`, `control_pending`, `control_capacity_reached`, `control_owner_lost`, `session_dormant`, `session_unavailable`, `daemon_stopping`, the three existence-query refusals the daemon maps to the wire (`session_unknown`, `session_id_invalid`, `store_unavailable`), and the activation and residency refusals (`activation_ceiling_reached`, `composition_mismatch`). **Not** `session_index_too_large`, `session_index_corrupt` or `session_index_upgrade_required`, which are startup exit classes and can reach no client, and **not** `capacity_exceeded`, which generation 1 already carries and generation 2 keeps for the two **attachment** ceilings — `attachments_per_session` and `attachments_per_daemon`, the "stable reason when exhausted" the attachment-lifecycle list names — and no longer for the connection ceiling, which is enforced at `accept` and therefore reaches no `initialize` | | **Limits** | ADR 0023's framing and input ceilings are unchanged, and generation 2 **adds** the residency keys a client can read: `connections_per_daemon`, `initialize_deadline_ms`, `attachments_per_session`, `attachments_per_daemon`, `session_list_page_max`, `session_index_entries`, `lease_term_ms` | -**`control_owner_lost` closes a controller whose lease owner died.** ADR 0033 +**The uncorrelated `control_owner_lost` form closes a controller whose lease +owner died.** ADR 0033 makes a lease owner's failure session-scoped: the daemon closes that session's controller connection, leaves its observers attached on their own, and lets the next acquisition start a fresh owner with a fresh epoch. The closing client is owed @@ -667,16 +1581,30 @@ daemon cannot know — and it equals the **lease term**, 30 seconds, so no number enters that ADR 0033 has not already fixed. A waiter that reaches it refuses `control_pending` and the client may acquire again. -**A waiter whose connection disappears is cancelled**, and the lease owner -learns of it the same way it learns of any connection loss: the waiter is -bound to the connection that made the request, so when that connection is -gone the acquisition is abandoned, no grant is made, and no epoch is minted. -A grant to a connection that no longer exists would hold a lease nobody could -release until it expired. - -**`control_owner_lost`, exactly.** It reuses the record family ADR 0023 -already defines for post-admission writer loss rather than adding one: **one -uncorrelated `error`**, with +**A waiter whose connection disappears before the permit's result CAS is +cancelled.** Connection `DOWN` wins `connection_lost`; for a fresh acquire the +daemon owner then exact-clears any provisional routing mirror and kills and +reaps the child named by `start_op_ref`, so no epoch or grant becomes visible. +If the daemon owner's `result` CAS wins first, the lease is already granted and +the later EOF follows the ordinary rule: it does not shorten that lease even +when the reply was lost. This cut is what distinguishes cancellation from a +grant to a connection that disappeared after the grant linearized. + +**`control_owner_lost`, exactly, has two mutually exclusive forms.** It reuses +the `error` record family ADR 0023 already defines rather than adding one. + +The **correlated in-flight lease-operation refusal** carries required `type: error`, +`code: control_owner_lost`, the request envelope's `request_id` and a bounded +non-secret `message`. It carries no `session_id`, `event_cursor` or session +state. It answers exactly one acquire or release whose `owner_lost` CAS won, or +one pending/queued lease-authorized mutation claimed before promotion, when +that origin is not the holder returned by the exact mirror pop, and it leaves +that connection open. A promoted mutation is outside this form and stays +relay-owned to its real core result. +An origin on the returned holder suppresses this form and receives only the +uncorrelated form below. + +The **uncorrelated granted-holder loss** carries no `request_id` and has: | Field | Value | | --- | --- | @@ -686,7 +1614,8 @@ uncorrelated `error`**, with | `session_id` | the session whose lease owner died | | `event_cursor` | optional; present exactly when this connection held an attachment, carrying that attachment's last completely emitted durable cursor exactly as `detached` does | -It is uncorrelated because no request caused it. **Close behaviour:** it is one +It is uncorrelated because no request caused it. A record containing both +`request_id` and `session_id`, or neither, is invalid. **Close behaviour:** it is one instance of the daemon-initiated detach rule below — the daemon writes the record best-effort into that connection's output buffer and then **closes that connection**. Every other connection is untouched, so every observer keeps its @@ -710,7 +1639,7 @@ client in a state neither side had defined. So: | The controller's lease owner died | `error`, `control_owner_lost`, with required `message` and `session_id`, plus `event_cursor` exactly when the connection held an attachment | close that connection | | Output-buffer or core-queue overflow | `error`, ADR 0023's `detached`, with `session_id` and `event_cursor` | close that connection | | Aggregate byte pressure chose this attachment | the same `detached` | close that connection | -| Idle eviction at ten minutes | the same `detached` | close that connection | +| Idle observer eviction at ten minutes; a connection holding a controller lease is exempt until release or expiry | the same `detached` | close that connection | Reusing `detached` for the three eviction rows is a **widening inside generation 2**, stated rather than slipped in: ADR 0023 defines that code for @@ -740,20 +1669,160 @@ instead. No new timer and no new number. property the witnesses assert: a case per occasion, each with a second connection attached to the same session, asserting the first connection sees the record where its buffer admits one and sees EOF either way, and the second -keeps receiving durable events across the whole of it. Each of the four is a -generation-2 vector: `control_owner_lost` under its own code, and three -`detached` vectors distinguished by nothing on the wire — the code and fields -are identical, which is deliberate, because why the daemon detached is an -operator fact in its logs and not authority-shaped information a client acts -on differently. +keeps receiving durable events across the whole of it. The four +daemon-initiated close occasions have generation-2 vector coverage: both +optional-cursor shapes of the uncorrelated `control_owner_lost` form and one +vector for each of the three `detached` occasions. The correlated in-flight +lease-operation `control_owner_lost` refusal has its separate +request-shaped vector. The three `detached` vectors have identical code and +fields, which is deliberate, because why the daemon detached is an operator +fact in its logs and not authority-shaped information a client acts on +differently. + +**The orderly transport cut follows the admission cut and has its own exact +barrier.** Once the relay has closed method admission and acknowledged it, the +connection registry atomically enters `transport_closing(cut_ref)`. Its +acknowledged state rejects every later provisional reservation or promotion and +marks every existing provisional or uninitialized row for EOF close. The owner +then kills and reaps the listener; only after that exact exit proves no further +accept can arrive does the registry close and reap the complete marked set and +acknowledge it empty. A peer accepted between the relay acknowledgement and the +registry gate may hold a provisional slot briefly but never initializes. The +registry gate, listener reap and final sweep share one absolute 5-second clock; +missing listener exit is `listener_lost`, and either missing registry +acknowledgement is `connections_lost`. Initialized peers remain open through the +drain. **`daemon_stopping`, the refusal after the admission cut.** Every -post-initialize method request takes a linearized permit from the admission relay. For the ten -state-changing calls ADR 0033 names, the relay records a ticket and starts the -monitored core task before returning the permit. For queries and artifact -transfer calls it returns an unticketed permit; those calls grant no lease and -change neither Control nor the journal, but using the same gate removes a -connection-layer check/use race. +post-initialize request linearizes admission at the relay. For the ten ticketed +calls ADR 0033 names, admission creates an origin row before any cross-process +descriptor can be sent. The row begins as +`pending_ticket(origin_id, class, nil)`; a lease-mutation row also binds the +session and currently registered owner incarnation before acknowledgement. +Create, activation-capable resume and attach then take the reservation handshake +above; another lease mutation goes to its lease owner. Promotion records the +ticket, starts the monitored core task and records its pid and monitor before +acknowledgement. Queries, artifact transfers, `session.acquire_control` and +`session.release_control` use lightweight permits. The lease calls change +lease-owner state but start no ticketed core mutation; reads and transfers +change neither Control nor the journal. Using and accounting at the same gate +removes a connection-layer check/use race. + +The connection does not execute a permitted call inline. It first reserves one +of its 32 local request slots, assigns a strictly increasing sequence within +that connection incarnation and synchronously installs the corresponding exact +origin row. Every worker bind, promotion, result and terminalization must match +the full origin ID. Create and attach submit that acknowledged origin to the +connection registry; it owns their reservation and promotes the exact primary +or installs a waiter. For an epoch-authorized mutation, the acknowledged +pending ticket exists before the connection starts a waiting worker and sends +the descriptor to the session's lease owner. An activation-capable resume makes +the lease owner ask the registry to reserve and promote that origin; another +mutation is promoted directly by the lease owner. Acquire, release, queries and +transfers instead install their lightweight permit row. + +Every request worker closes its spawn window with a parent-monitor/ready +handshake: before reporting ready it monitors the connection and waits without +dispatching. After readiness the connection asks the relay to bind the exact pid +and a relay-owned monitor. If the connection dies before that bind, the child +exits on parent `DOWN`; after bind, the relay owns retirement. A lease-mutation +origin therefore transitions +`pending_ticket(origin, class, nil) -> queued(origin, class, worker_pid, +worker_monitor, owner_incarnation) -> ticketed(task_pid, task_monitor, ...)`. +The connection sends the owner descriptor only after `queued` is acknowledged. + +Messages from that one connection pid preserve wire-arrival order; distinct +workers never race their own `GenServer.call`s into the owner. The owner queues +the descriptor by connection incarnation and sequence and processes +lease-sensitive requests in that order. It validates a mutation's combined gate +at the head, then asks the relay or registry to promote the named queued row. +Promotion starts the core task before acknowledgement and tells the waiting +request worker to retire; the relay retains its monitor until exact `DOWN`, while +the relay task continues independently. If worker `DOWN` wins while the row is +still queued, the relay terminalizes that origin, authorizes the existing +generic request failure when the reply route is live, and later promotion starts +no task. If promotion wins, later worker death cannot cancel or settle the core +call. The owner remains the only initiator of mutation promotion, preserving +ADR 0033's ticket-before-owner-`DOWN` ordering. + +If the cut wins before origin-row creation, the relay answers +`daemon_stopping`, no row or core task exists, and a frame merely read before +the cut has not been admitted. A row created before the cut may promote during +the bounded admission wait; the deadline terminalizes one still pending or +queued, kills and reaps its request worker, and makes later promotion a no-op. + +For an unticketed call, the connection obtains a lightweight permit retaining +the immutable operation class, connection incarnation, optional session ID and +optional intended actor binding, completes the same worker ready/bind handshake, +and only then attempts `pending -> executing`. Before a lease permit is +acknowledged, the daemon owner supplies the session ID and either the current +registered lease-owner pid/incarnation or, for a fresh-owner acquisition, its +own daemon-owner pid/incarnation. Relay creation is serialized with exact owner +`DOWN`; an already-lost actor routes the origin into its retained owner-loss +classification rather than leaving a pending unbound row. The permit stores two roles separately: +`{request_worker_pid, request_worker_monitor}` and +`{actor_pid, actor_incarnation, start_op_ref | nil}`. For a query, read or +transfer the two pids are the same; for acquire or release the actor is the +lease owner or daemon owner, must match the immutable intended binding, and the +request worker only waits for its correlated answer. The relay sends `go` only after the executing CAS, so no worker may +dispatch before it is tracked. That permit remains until a result or one +terminal connection/worker/owner disposition. Ticket settlement remains with +the relay and keeps the originating accepted slot charged after connection +death. The pending origin row, rather than a cross-receiver ordering +assumption, proves that a mutation cannot materialize after slot retirement: +connection `DOWN` terminalizes an unpromoted ticket row that has no compensating +work, and a promoted row must settle before release. Lightweight acquire and +release permits follow the settling acknowledgements below. + +The connection and relay monitor each request worker, at most ADR 0023's 32 +in-flight requests per connection. Results, worker `DOWN`s, connection `DOWN`s +and lease-owner `DOWN`s settle a lightweight permit through one relay-owned +winning-disposition compare-and-set from `pending` or `executing`. A disposition +whose mirror, classification or actor cleanup is incomplete remains +`settling(disposition, op_ref)` until its exact acknowledgement and cleanup; +only then does it become terminal and render, if rendering is owed. The +connection reports its worker signal but never renders a result independently; +only the relay's winning disposition tells it whether to render the result, the +existing generic failure, or a correlated `control_owner_lost`. + +Connection loss CASes every permit for that incarnation to `connection_lost`, +kills and reaps only its exact request workers, and emits no reply. It never +kills an actor merely because the actor pid appears in the permit: that pid may +be the daemon owner or a lease owner shared with other work. The actor's later +result is cleanup-only; ADR 0033 supplies the compensating rule for an +acquisition that had not yet made its grant visible and a release whose owner +must be restored from `release_pending`. Owner loss claims every pending +acquire/release permit whose immutable intended binding names that exact owner +and every executing permit whose actor binding names it. It also claims every unpromoted +lease-mutation origin bound to the dead owner, kills and reaps a queued worker +and starts no core task; a promoted relay task remains retained to its real +result. Each claimed origin waits for exact mirror-pop classification: an origin +on the returned holder suppresses its correlated form and receives only the +uncorrelated close, while any other origin receives the correlated refusal and +stays open. A later worker result or `DOWN` is cleanup-only. Thus two signal +orders cannot double-answer or double-release one row. Slot retirement waits for every worker monitor `DOWN`, so even a worker +blocked in an `:infinity` call is killed and reaped rather than relying on it to +notice its parent's monitor. Forced cases cover connection death while a +mutation worker is queued behind a prior ticket and while a lightweight read is +blocked at `:infinity`, plus worker death on each side of promotion; they prove +no queued core call after failure, one real result after promotion, and every +origin, worker, permit and accepted slot returning to baseline. + +Owner-death cases pause acquire and release before and after their executing +CAS, including after a pending permit with an immutable exact-owner binding is +acknowledged but before that owner claims it, and pause a lease mutation as +`pending_ticket`, `queued` and promoted. The pending-permit case proves the +relay selects `owner_lost` from retained data without guessing and leaks no row. +Holder and non-holder origins prove the mutually exclusive close/refusal forms, +the two unpromoted mutation cuts start no core task, the promoted cut returns +the real core result, and every predecessor set drains before replacement. + +A forced-order witness pauses a lease owner after a pre-cut pending ticket is +created but before promotion. Released within the admission wait, it promotes +and remains in the bounded set. Held past the absolute deadline, the pending row +becomes `shutdown_cancelled`; later promotion refuses, no relay task starts and +no durable or Control state changes. A request whose origin-row creation is +ordered after `cut` receives `daemon_stopping` and creates no row. An orderly stop sends `cut` to that relay. When the relay handles the message it switches to closed and acknowledges immediately. The mailbox order is the @@ -762,15 +1831,80 @@ core and is allowed to finish; a request processed after the cut refuses with the correlated `daemon_stopping` carrying its `request_id` and nothing else. The acknowledgement means **no later request can be admitted**. It does not mean admitted work has settled or that no pre-cut task will enter core after -the acknowledgement. The drain waits separately, to its absolute bound, for -the tickets that the cut returned as outstanding. +the acknowledgement. The cut returns the exact retained origin IDs with +pending, queued, ticketed, waiting or settling state and exact +lightweight permit IDs, not only their counts, and changes daemon lease routing +to `draining`. No request admitted after that transition may start a lease +owner. Any permit named by the frozen pre-cut set may claim execution before the +absolute admission deadline; only an acquisition may finish validation and +start its owner. The +drain waits for those frozen rows against one absolute admission-wait bound. A +pre-cut acquire or release already owned by an existing lease owner may return +its real result inside the bound. An acquire still in existence validation or +waiting for owner creation remains represented by its permit, but owner creation +must finish inside the bound; after the bound no later start is accepted. + +At the bound the relay compare-and-sets every remaining `pending` lightweight +row and every unpromoted `pending_ticket` or `queued` ticket to +`shutdown_cancelled`, sends correlated `daemon_stopping` when the socket remains +writable, and kills and reaps its exact request worker before it can dispatch. +The registry releases a reservation whose primary never promoted. A lease owner +that later attempts to promote a cancelled row starts no task. Promoted ticket +tasks remain tracked +through their result, fatal disposition or post-quiesce seal. Executing non-lease queries, reads and transfers remain tracked through result +or the step-3 connection/worker barrier; if still live then, that barrier kills +them and `connection_lost` wins exactly once. Executing lease operations follow +ADR 0033's actor or provisional-child teardown and become +`shutdown_admitted`; their mutation is not described as rolled back. The closed +terminal permit states are therefore exactly `result`, `owner_lost`, +`connection_lost`, `shutdown_cancelled`, or `shutdown_admitted`, with one winner. +The same barrier returns ADR 0033's tagged acquisition, proposed-release and +pre-proposal owner-loss settlement descriptors. Each keeps its already selected +disposition, finishes exact no-output relay and mirror cleanup inside +`freeze_deadline`, and leaves no permit or owner mirror before core quiesce; it +is never silently treated as an executing row or omitted from the frozen set. +Core then installs its early quiescing barrier. A surviving mutation that already +obtained a coordinator route is ordered against the coordinator's drain-specific +admission close; one that has not reached its first `Control` operation refuses +at the barrier and can create no late entry. A surviving read or transfer may be +ended by the later connection close, which is safe because it changes neither +Control nor the journal. The contract deliberately promises completion only +before that bound, not an unbounded shutdown wait. + +After every connection and request worker is gone, the daemon owner performs a +mailbox barrier with itself and the relay, changes both relay and daemon-owner +lease phases to `tearing_down`, and freezes the exact lease-owner pid/incarnation set. No owner +start or routing-mirror install is accepted after that barrier. Registry stop and +the collective owner sweep consume exactly this frozen set, so no lease owner or +mirror can appear behind the sweep. The connection stays open until the later close phase, so a post-cut frame can still receive its correlated refusal. That refusal closes nothing by itself; `daemon.stopping` is the subsequent uncorrelated best-effort notice that names -why the connection is closing. The two witnesses deliberately differ: a -pre-cut request completes on its own terms, while the same request admitted -after the cut receives `daemon_stopping` and never invokes its facade. +why the connection is closing. The witnesses deliberately differ: a pre-cut +unticketed request released within the bound completes on its own terms; one +held past the bound ends with the connection and changes no durable or Control +state; the same request admitted after the cut receives `daemon_stopping` and +never invokes its facade. + +The lease-call witness forces an acquire before and after its existence reply, +before owner start, after owner start but before provisional mirror +installation, and after that install, plus a release while queued and after its +state transition. It forces both orders of connection `DOWN` and the acquire's +result CAS: loss first exact-clears the provisional mirror, reaps the start child +and exposes no epoch; result first promotes the exact mirror even if the holder +slot is already closing and leaves a granted lease whose reply may be lost. +Each cut is also held past the admission bound. A fresh executing acquisition is +frozen before and after provisional install, and settling acquisition, proposed +release settlement and pre-proposal owner-loss classification are separately +held through the barrier. It must return their tagged descriptors, retain their +winning dispositions and remove every cancelled row and mirror without post-cut +output before quiesce. It +asserts one terminal permit +disposition and at most one correlated reply, `daemon_stopping` for every +unlinearized survivor, no rollback of a linearized lease change, no stale mirror, +no owner or mirror appearing after the freeze barrier, and zero permit, worker, +owner and mirror rows after the step-4 sweep. **Index startup failures are not wire codes.** `session_index_too_large`, `session_index_corrupt` and `session_index_upgrade_required` all stop startup @@ -797,35 +1931,55 @@ reachable regardless, and the daemon's own `stderr` keeps the operator's copy. It is never broadcast; other connections did not ask. The activation it follows **succeeded**: the session is usable and reachable -by ID, and its persistent index row is missing, to be written by the retry the -plan already describes. The legacy directory entry is an independent rollback -artifact and its failure is logged separately. Reporting the index failure as an `error` would +by ID. After a pre-rename failure whose cleanup proved `.next` absent, the +persistent row is missing and the next ID-bearing command may retry it. After +a poisoned cleanup path, later publication is refused for this daemon +lifetime. After rename succeeded but the directory sync failed, the complete +next image is already named and adopted in memory, but the daemon claims no +crash durability and likewise performs no in-lifetime retry. The legacy +directory entry is an independent rollback artifact and its failure is logged +separately. Reporting the index failure as an `error` would tell a client its command failed when it did not, and saying nothing would leave a session absent from `session.list` with no explanation. The family enters the digest's record-families input beside `daemon.stopping`. **Correlation, for the refusals above.** `control_not_held`, `control_pending`, `control_capacity_reached`, `control_held`, -`session_dormant`, `daemon_stopping` and the four existence-query refusals are +the in-flight lease-operation form of `control_owner_lost`, `session_dormant`, +`session_unavailable`, +`daemon_stopping` and the three existence-query refusals are ordinary **correlated** errors: each answers one request and carries that request's `request_id`, no `event_cursor` and no session state, and none closes anything **by itself** — the connection and every attachment on it are untouched by the refusal, and where the connection is nonetheless closed a moment later it is the stop sequence or the detach rule below doing it, not the error. The uncorrelated cases in generation 2 are the ones named above, -`control_owner_lost`, ADR 0023's `detached` as this pair's detach rule reuses +the granted-holder form of `control_owner_lost`, ADR 0023's `detached` as this pair's detach rule reuses it, and the `daemon.stopping` and `daemon.notice` records, and each states its own close behaviour where it is defined. Stating this once is what lets the vectors be written without guessing. -**The existence query's `unexpected` maps to `existence_indeterminate`.** Core -answers one of five results; the daemon maps `store_unavailable` to the wire's -`store_unavailable` and **`unexpected` to `existence_indeterminate`**, because -a result core did not recognise is exactly a case where existence could not be -decided, and inventing a distinct wire code for "core said something we do not -understand" would expose an internal disagreement a client cannot act on. The -two refuse identically in effect — nothing created, nothing attached, no lease -— and differ only in the reason a client is given. +**The existence query has four domain results and one runtime-boundary +failure.** Core adds this exact host-facing API: + +```elixir +Loopex.Runtime.session_existence(runtime, session_id) :: + {:ok, :present | :absent | :invalid_id | :store_unavailable} + | {:error, :runtime_unavailable} +``` + +It validates the session ID before dispatch, returning `{:ok, :invalid_id}` +without a Store call. For a valid ID it resolves one exact `Control` incarnation +and maps the existing `Loopex.Store.ownership_head/3` result exactly: +`{:ok, head}` to `{:ok, :present}`, `:absent` to `{:ok, :absent}`, and +`:unavailable` to `{:ok, :store_unavailable}`. That Store facade already +normalizes an adapter's malformed or out-of-set answer to `:unavailable`, so +the daemon maps that path to the same wire refusal and does not invent a fifth +domain result or an `existence_indeterminate` wire code. Failure to resolve or +call that exact `Control` is instead `{:error, :runtime_unavailable}`. The +daemon treats it as daemon-fatal `runtime_lost`; it never disguises loss of +core as Store unavailability. Every negative domain result creates nothing, +attaches nothing and grants no lease. ### The session index, and what it may claim @@ -845,52 +1999,165 @@ participates in create, resume, admission, replay or recovery. Core's read-only existence query is the only yes/no authority the daemon uses for an exact ID. **The persisted format is bounded before parsing.** The file is canonical -UTF-8 JSON Lines with one version header, zero to 4,096 rows sorted by session -ID bytes, and one SHA-256 trailer over the exact header-and-row bytes. Header, -row and trailer keys and their order are fixed; unknown keys, duplicate or -out-of-order IDs, invalid identity alphabets and bad digests are corruption. -Each line is at most 1,024 bytes and the complete file is at most 4 MiB. The +UTF-8 JSON Lines with these exact compact objects and one LF after each: + +```text +{"format":"loopex-session-index","version":1} +{"session_id":"","placement_identity":""} +{"sha256":"<64 lowercase hexadecimal characters>"} +``` + +There is exactly one header, zero to 4,096 rows sorted by the **decoded raw +session-ID bytes**, and exactly one trailer. `` and `` are the +canonical unpadded base64url encodings ADR 0023 uses for binary identities; +each must decode to 1 through 256 bytes and re-encode byte-for-byte to the input +string. The SHA-256 domain is the exact header LF plus every row and its LF, in +order; it excludes the trailer. JSON has no optional whitespace or escapes in +this format. Key order is the literal order above. Unknown keys, duplicate or +out-of-order decoded IDs, padding, a noncanonical or invalid base64url alphabet, +the wrong version or format literal, CRLF, and bad digests are corruption. +The complete file is at most 4 MiB. The daemon opens without following a symbolic link, checks the regular-file identity and byte size before reading, reads no more than 4 MiB plus the single byte needed to prove overflow, and checks the identity again after the read. Oversize refuses `session_index_too_large`; malformed content refuses `session_index_corrupt`. Both occur before socket bind. -**Updates are atomic snapshots, not an append protocol.** The marker-holding -daemon serializes index changes, writes the complete next canonical image to a -mode-`0600` sibling created with exclusive creation, syncs that file, renames -it over `session-index-v1`, and syncs the `daemon/` directory before it reports -success. A crash before rename leaves the prior image; a crash after the -directory sync leaves the next one. Only a daemon that has acquired the Store -marker may remove an abandoned temporary. This adds no journal record and +The line and file bounds are compatible by construction, rather than two +ceilings whose first winner is undefined. A 256-byte identity has a 342-byte +unpadded base64url spelling, so a maximal **row including its LF is exactly +726 bytes**. The header is 46 bytes and the trailer 78 bytes, including their +LFs. Thus the largest admitted image is +`4096 * 726 + 46 + 78 = 2_973_820` bytes, below 4 MiB. The boundary has three +explicit dispositions: an existing image with a 726-byte canonical row can +open, while a 727-byte row is `session_index_corrupt`; live publication accepts +only the already-validated 1-to-256-byte identities and reports its existing +bounded publication warning rather than writing if an internal caller violates +that invariant; offline import refuses an invalid or over-bound legacy identity +and preserves the prior index byte-for-byte. It never truncates or silently +omits that legacy row. The 4 MiB read ceiling remains independent corruption +protection. + +**Updates are atomic snapshots, not an append protocol.** The placement-lock +and marker-holding daemon serializes index changes and writes the complete next +canonical image to the one fixed sibling `session-index-v1.next`, mode `0600` +and created exclusively. The publisher retains the opened file's device and +inode identity. It syncs and closes that file, treating a close failure as a +pre-rename failure, then renames it over +`session-index-v1`, and syncs the `daemon/` directory before it reports success. +A crash before rename leaves the prior image and at most that one `.next` file; +a crash after the directory sync leaves the next image. After acquiring both +locks and before loading or writing the index, startup removes that exact +temporary only after `lstat` proves it is a non-symlink regular file owned by +the daemon user; any other shape is `session_index_corrupt`. No random or +per-attempt temporary name exists, so repeated crashes cannot accumulate an +unbounded directory. This adds no journal record and changes no local Store byte. At 4,096 rows a new exact-ID session remains usable but is not added; `session.list` reports `index_full: true` rather than pretending completeness. -A successful activation or exact-ID recovery adds the row after durable -existence is established. The row becomes visible in memory only after the -snapshot is durable. A failed index write does not reverse the session -operation; the causing connection receives `daemon.notice` with -`index_write_failed`, the daemon logs it, and later commands carrying that ID -retry the same idempotent write. A retry with the same placement is idempotent; +**Failures split at the rename, because only the earlier side can preserve the +prior image.** A write, file-sync, close or rename error occurs before a successful +replacement. Where still open, the publisher closes the descriptor and invokes one +cleanup path while it still holds both locks. If `lstat` finds the fixed +`.next` path, the publisher removes it only when its regular-file type, owner, +device and inode match the file this attempt opened, then syncs `daemon/`; +absence is already clean. A different identity, an unverifiable result or a +failed unlink or cleanup-directory-sync poisons index publication for the rest +of that daemon lifetime. Successful cleanup proves the prior canonical image +is still named and lets the next ID-bearing command retry the same snapshot. + +A directory-sync error **after rename succeeds is different**: the canonical +path already names the complete next image in this running process, `.next` no +longer names the attempt, and restoring the prior bytes would be a second +unproved mutation. The publisher therefore adopts that valid next image in its +in-memory index, reports `daemon.notice: index_write_failed`, poisons later +publication without touching either path, and makes no durability claim for +the rename. A crash may expose either the prior or next complete canonical +snapshot; startup validates whichever image the filesystem presents. It may +not expose a partial image as valid because the file was synced before the +atomic rename. A poisoned daemon keeps serving the durable session and refuses +every later publication until restart. + +`prepare-index` uses the same split and lock order. A pre-rename failure with +successful cleanup preserves the prior index; a post-rename directory-sync +failure leaves the valid next image named in the running filesystem but admits +that a crash may recover either complete image. In either failure case it +stops Store, attempts placement release last through ADR 0031's bounded helper, +and exits +`session_index_write_failed`. The witnesses inject write, file-sync, close and rename +failures before replacement, prove the exact temp is removed and an in-process +retry succeeds, then substitute a mismatched identity at cleanup and prove no +later write occurs before restart. A distinct post-rename directory-sync +failure proves the canonical path and in-memory projection hold the next valid +image, the publisher is poisoned, no rollback or later write is attempted, and +after an abrupt restart the image is one of the two complete valid snapshots. + +A successful create or resume adds the row after durable existence **and this +daemon's placement** are established. Bare exact-ID existence and historical +create replay do not publish. The row becomes visible in memory only after the +snapshot is durable on ordinary success. The named post-rename +directory-sync failure is the sole different case: the complete newly named +image becomes visible in this process, the daemon issues +`daemon.notice: index_write_failed`, poisons later publication, and claims no +crash durability. A failed index write does not reverse the session operation; +the causing connection receives that notice, the daemon logs it, and later +commands carrying that ID retry the same idempotent write only when a +pre-rename failed attempt proved the fixed temporary gone. A poisoned +publisher keeps refusing until restart. A retry +with the same placement is idempotent; a different placement conflicts. The independent legacy `SessionDirectory.record_session/3` write remains for foreground rollback and -may succeed or fail separately. - -**Upgrade is explicit so startup stays bounded.** A new root whose `sessions/` -directory does not exist gets an empty canonical index before bind. If +may succeed or fail separately. Its failure emits a bounded operator warning, +does not reuse `index_write_failed` for a different fact, and is retried on the +same later ID-bearing commands as the index write. Neither publication failure +reverses the session operation. + +**Upgrade is explicit so startup stays bounded.** After acquiring the host +placement lock and then the Store marker, ordinary startup creates or verifies the owner-only, non-symlink +`daemon/` directory with mode `0700`; a new root whose `sessions/` directory +does not exist gets a **persisted** empty canonical mode-`0600` index there +before bind. If `sessions/` exists but the index does not, daemon startup performs only the bounded `stat` needed to learn those two facts and refuses `session_index_upgrade_required`; it never calls `File.ls/1`. The operator runs `loopex daemon prepare-index` while no daemon or foreground server owns the -root. That offline command acquires the local Store marker, uses the legacy -session-directory enumeration, validates every non-temporary row, refuses -rather than truncates above 4,096 valid rows, writes the atomic index, and -releases the marker. Its scan is explicitly **not** a bounded service-start +root. That offline command acquires the same host placement lock first and the +local Store marker second, creates or verifies +the same owner-only, non-symlink mode-`0700` `daemon/` directory, uses the legacy +session-directory enumeration, and validates any existing canonical index. It +constructs the **union** of those two inputs. A session present in both must +carry the exact same placement identity; a disagreement refuses as +`session_index_corrupt` with status 84 and leaves the old index byte-for-byte +intact. The command validates +every non-temporary legacy row and enforces both the 4,096-row and 4 MiB bounds +over the union, refusing rather than truncating. Only after the complete union +passes does it atomically write or replace the mode-`0600` index, sync the +directory, stop the Store so its best-effort marker-release callback runs, and +then attempt the acquisition-specific placement-handle release through the +fixed `placement_release_ms` helper. A healthy branch proves both paths absent +and an immediate foreground reopen. Injected marker or placement removal and +sync failures instead prove that a complete residual is handled only by the +corresponding dead/live/unverifiable-owner recovery; a suspended placement +release reaches its deadline and exits non-zero without an unbounded tail. On a failure before rename it removes +only an empty `daemon/` directory that this invocation created and leaves a +pre-existing valid index unchanged. On a directory-sync failure after rename, +the new complete image remains named but its crash durability is unknown as +described above. Its scan is +explicitly **not** a bounded service-start operation: the command warns that legacy `File.ls/1` materializes the directory and may need operator repair of a corrupt or oversized legacy directory. This one-time cost is kept outside daemon availability rather than mislabeled as a -bound. +bound. Re-running the command is therefore a refresh: an index-only row and a +legacy-only row both survive. + +Successful import exits `0` after those bounded release attempts, remains +silent on `stdout`, and emits no daemon readiness record. Parser refusals use +the reference CLI's existing status `1` before either exclusion. Operational +refusals reuse the plan's applicable state-root, placement, Store or index class +and integer status, including `session_index_corrupt` for the identity conflict; +they have no wire surface and write only bounded diagnostics or warnings to +`stderr`. Rollback needs no reverse migration. The M4 foreground server ignores `daemon/session-index-v1` and continues using `sessions/`; the index may remain. @@ -905,20 +2172,29 @@ import. The in-memory projection claims only facts its owners can keep true: - `session_id` and `placement_identity` come from the validated persisted row - or from an exact-ID operation after core answered `present`; + or from a successful create/resume under this daemon's configured placement; - `residency: active` means this daemon activated that session in this lifetime; `dormant` means it has not. It never claims a coordinator is live; -- `controlled` is updated by the one lease owner on grant, release, expiry and - owner death. It names no durable controller. +- `controlled` is updated by the daemon owner's serialized projection after + acknowledged lease results and after an exact lease-owner `EXIT` plus routing + mirror-pop disposition. A dead lease owner never updates it. It names no + durable controller. Lineage, lifecycle state and committed sequence are deliberately absent. A client that needs them attaches and reads the snapshot anchored by core. -**Recovery of an omitted row uses identity the client already owns.** Core's -existence query answers exactly `present`, `absent`, `invalid_id`, -`store_unavailable` or `unexpected`; only `present` permits an index write, -lease grant or later activation. The other four leave no attachment, lease, -activation or row and map to their distinct generation-2 refusals. +**Recovery of an omitted row first proves existence, then proves placement by +activation.** Core's existence query answers one of the four domain results +inside `{:ok, result}` or the distinct outer +`{:error, :runtime_unavailable}`. Only `{:ok, :present}` permits a lease grant or later +activation but **does not permit publication**, because that result carries no +recorded placement identity. The daemon writes the directory/index row only +after create or resume succeeds under its configured placement. The other three +leave no attachment, lease, activation or row and map to their distinct +generation-2 refusals. Runtime unavailability is daemon-fatal `runtime_lost` +and reaches no existence refusal. A session stored under placement A, absent from both +publications and reached by a daemon composed as B, answers `{:ok, :present}` but its +resume refuses the placement mismatch and neither publication may record B. A client that lost the create reply and therefore lacks a session ID recovers in this exact sequence: @@ -931,17 +2207,49 @@ in this exact sequence: a conflict, not a coalesced success. 4. Replayed create starts no coordinator. 5. The daemon asks core's read-only existence query for the returned ID and - proceeds only on `present`. -6. It idempotently repairs the legacy directory entry and the daemon index row; - either write may report its own failure without changing Store truth. -7. The client acquires control and receives a writer epoch. -8. It sends `session.resume` with a fresh resume `command_id` and that epoch. -9. The daemon activates the session and charges the lifetime ceiling. + proceeds only on `{:ok, :present}`, without publishing a placement row. +6. The client acquires control and receives a writer epoch. +7. It sends `session.resume` with a fresh resume `command_id` and that epoch. +8. Core validates the daemon's configured placement and activates the session, + charging the lifetime ceiling. +9. Only after that success does the daemon idempotently repair the legacy + directory entry and daemon index row from the now-proved placement; either + write may report its own failure without changing Store truth. + +The create-history arm is the companion host-facing API: + +```elixir +Loopex.Runtime.lookup_create_result(runtime, command_id, options) :: + {:ok, {:historical, session_id} | :absent | :conflict + | :store_unavailable | :unexpected} + | {:error, :runtime_unavailable} +``` + +It reuses `Store.runtime_command/2`; it adds no Store callback. Core rebuilds +the canonical create transaction from the supplied +options and the runtime's creation configuration, then presents its bytes and +digest under the existing `command_kind: :create` binding. The local adapter's +read projection recognizes its retained create row and returns +`{:completed, %{result: session_id}}` only on an exact binding; mismatch keeps +the existing `runtime_command_conflict`. This changes no durable frame, +callback arity or Store result union. The five values inside `{:ok, result}` +are the complete create-history domain; failure to resolve or call the exact +`Control` returns the same outer `{:error, :runtime_unavailable}` as the +existence query, and the daemon again treats it as fatal `runtime_lost`. +At the activation ceiling, `{:historical, session_id}` returns the prior create +result without publication, `:absent` maps to +`activation_ceiling_reached`, `:conflict` maps to the existing correlated +admission refusal reason `runtime_command_conflict`, `:store_unavailable` maps +to the correlated `store_unavailable` error, and `:unexpected` maps to the +correlated `internal_failure` error without serializing the term. Each mapping +has a ceiling-path witness; the outer runtime failure is the separate fatal +`runtime_lost` path. 10. The client attaches and drives it. A client that already knows the session ID begins at step 5. If the index is -full, step 6 reports `index_full` and omits the row while steps 7 through 10 -remain available. The witness injects the Store-commit/before-reply crash cut, +full, step 9 omits the row and the next `session.list` reports +`index_full: true`; step 10 remains available. The witness injects the +Store-commit/before-reply crash cut, runs all ten steps, and proves one durable session, no coordinator from the create replay, a repaired row, one charged activation and a subsequent prompt on the recovered session. @@ -958,8 +2266,20 @@ The startup witness places more than 4,096 valid legacy entries and an arbitrarily large population of malformed names beside a valid bounded index, and proves that daemon start reads only the index bytes and performs no `File.ls/1` call. Separate cases prove oversize, digest failure, duplicate ID, -interrupted snapshot replacement, missing-index upgrade refusal, successful -offline import and foreground rollback with the extra file present. +wrong header/version, noncanonical base64url, a maximal 726-byte row accepted, +a 727-byte row refused as corrupt, interrupted snapshot replacement, +missing-index upgrade refusal, successful offline import and foreground +rollback with the extra file present. A fresh root is proved to persist the +literal empty image in a mode-`0600` file under a mode-`0700` non-symlink +directory before bind, and a restart consumes that image. A failed import +before rename removes only an empty daemon directory that invocation created; +with a pre-existing directory or index it leaves every byte and mode unchanged. +A separate post-rename directory-sync failure proves the newly named image is +complete and valid, no rollback is attempted, and an abrupt restart accepts +either complete snapshot. The import +case starts with index-only session A and legacy-only session B and proves both +rows in the replacement; a second case gives one shared ID two placement +identities and proves refusal with the original index unchanged. ### Session residency: active, dormant, and their bounds @@ -985,9 +2305,11 @@ daemon, and retiring a root is what actually frees them. What it costs nothing in is the things activation buys: no coordinator, no replay at start, no attachment, no window, no buffer. -**Activation is one-way for the daemon's lifetime.** A session the daemon has -activated keeps its coordinator until the daemon exits. Dormancy is *not* -deactivation, and the daemon has no operation that stops a coordinator. +**Activation is one-way for the daemon's lifetime.** The daemon never +intentionally stops an activated session's coordinator or returns its +activation fact to dormant. Dormancy is *not* deactivation, and the daemon has +no operation that stops a coordinator. A temporary coordinator can still die; +that does not falsify the one-way activation fact. That is a correction, not a simplification. An earlier draft let an idle session "go dormant, releasing its slot", which is wrong twice over. The idle @@ -998,15 +2320,17 @@ awaiting an answer, a recovery in progress, an unresolved `commit_unknown`, or an admission executing inside core. Stopping it would destroy exactly what Outcome 1 exists to prove, that work progresses with zero attachments. And there is no operation to stop one with: core owns coordinator lifetime, and -none of M5's five core changes (the complete concurrent-attachment lifecycle, -the read-only existence query, the trace exclusion, `quiesce/1`, and the -`disposition` and `control_entry` fields on the detailed create and resume -functions) stops a coordinator, +none of M5's six core changes (the complete concurrent-attachment lifecycle, +the read-only existence-and-create-history query surface, the trace exclusion, +`quiesce/1`, the `disposition` and `control_entry` fields on the detailed create +and resume functions, and managed provider lifetime) stops a coordinator, so a deactivation call would be a further core change this milestone does not make. -- **What dormancy applies to.** Attachments, resident windows and socket - output buffers, and nothing else. An idle attachment is evicted, its window +- **What idle eviction and reclamation apply to.** Attachments, resident windows + and socket output buffers, and nothing else. Dormancy means only that the + durable session has never been activated by this daemon in its current + lifetime. An idle observer attachment, or a connection no longer holding a controller lease, is evicted; its window may be reclaimed, its buffer is released — and the coordinator beneath them keeps running. Every byte ceiling in this decision is about those three and is unaffected. @@ -1024,10 +2348,31 @@ make. query, and attach is refused with `session_dormant` against a session this lifetime has not activated — which is exactly why the CLI's `resume` form exists and why `attach` alone cannot start work. +- **Temporary coordinator death.** If an activated coordinator dies, the + activation set remains active. Attach may therefore succeed, after which + a generation-2 `session.inspect` reaches core and maps only its exact + `:session_unavailable` reason to the wire's `session_unavailable`; repeating + against the same daemon repeats that result without parsing a message or + sending a mutation. + The operator restarts the daemon and retries `loopex resume --daemon`, whose + dormant branch resumes and starts a new coordinator. A forced witness kills + the coordinator, proves attach then inspect refuses without a second + coordinator, restarts the daemon, and proves resume, reattach and a later + prompt succeed on the same durable session. - **Activation ceiling.** At most 64 sessions are activated **per daemon lifetime**, not at once, because nothing gives a slot back. The 65th - activation refuses with a stable reason naming the ceiling and the remedy, - which is to restart the daemon. That is a real limitation rather than a + **fresh** activation refuses with a stable reason naming the ceiling and the + remedy, which is to restart the daemon. Before refusing a create, the daemon + uses core's read-only create-history discriminator with the exact + `command_id` and canonical session options. `historical(session_id)` returns + that prior result without a coordinator, activation or publication; discovery + is repaired only after a later successful resume proves this daemon's + placement (which may require a later daemon lifetime at the ceiling); + `absent` is the fresh case the ceiling refuses; `conflict` preserves the + runtime's command-conflict refusal; store failure and an unrecognised result + fail closed. A resume of an already activated session likewise needs no new + slot; a dormant resume at the ceiling refuses before core is called. That is + a real limitation rather than a design, it is recorded as one in the plan and in the operator page, and it is the honest cost of leaving coordinator lifetime alone in M5. Lifting it needs a core deactivation operation that can tell "quiescent" from "idle", @@ -1084,8 +2429,10 @@ does. The digests are computed and pinned when the files are written; generation 1's two file digests are **unchanged**, because those manifests already carry `loopex.experimental/1` and never carried the retired name; only its schema digest moves, the generation being one of that digest's inputs. -Every served generation is additionally asserted to have `Session.generation()` -equal to its own manifest's `/generation`, which is the check whose absence +Every served generation is additionally asserted against its own contract +module: `LoopexProtocol.Session.generation()` equals generation 1's manifest +`/generation`, and `LoopexProtocol.Session.V2.generation()` equals generation +2's. That is the check whose absence let the released code and the released manifests disagree in the first place. A negotiation vector proves selection from a list that also names generation 1 under its new string, refusal of a list naming only generation 1, and refusal of a list naming only the retired @@ -1115,8 +2462,11 @@ delivered contiguously after the snapshot. The daemon adds: disabled, with identical delivery. Reclamation is deterministic so that it can be tested rather than observed. - When the daemon's aggregate encoded-byte ceiling would be exceeded, windows - are released in this fixed order: first every window whose session has zero + Before an encoded-byte admission, the candidate bytes remain pending and + uncharged. If `charged_aggregate + pending_admission_bytes` would exceed the + daemon's aggregate ceiling, the registry takes one accounting snapshot and + reclaims from that snapshot in + this fixed order: first every window whose session has zero attachments, in ascending order of the monotonic time of their last delivery, ties broken by session ID bytes ascending; then, if the ceiling is still exceeded, the window of the session whose slowest attachment is @@ -1126,15 +2476,28 @@ delivered contiguously after the snapshot. The daemon adds: it is measured in bytes rather than in each session's own sequence numbers. A sequence-distance metric would not be comparable: sequence numbers are per-session and say nothing about how much memory an attachment is costing. - Ties break by session ID bytes ascending. Each step is **repeated until the - aggregate is below the ceiling**, not applied once: releasing one window may - not be enough, so zero-attachment windows are released in that order until - either the aggregate fits or none is left. Only when none is left does the - daemon detach the slowest attachment at its last emitted cursor — sending + Ties break by session ID bytes ascending. Each step is **repeated until + `charged_aggregate + pending_admission_bytes` is at or below the ceiling**, + not applied once: releasing one window may not be enough, so zero-attachment + windows are released in that order until either the pending admission fits + or none is left. Active-session windows follow in + the derived order until none remains. The registry then closes connections + with **no live attachment**, largest output buffer first, ties by ascending + connection-incarnation bytes. Such a connection has no session cursor to + preserve and receives no `detached` record; an initialized one is closed + after exactly one non-blocking write/flush attempt for already-buffered + complete records and is never awaited for peer progress, while an + uninitialized one closes immediately. This step repeats until the pending + admission fits or no unattached connection remains. Only then does the daemon detach + the slowest live attachment at its last emitted cursor — sending that connection a `detached` record and closing it, under the detach rule above, so the bytes the attachment was holding are released with the connection rather than lingering behind an open socket nothing is reading — - and that too repeats until the aggregate fits. Independently of pressure, a window whose session has had zero + and that too repeats until the pending admission fits. Only then does the + registry atomically charge and admit the candidate bytes. If the complete + allowed sequence cannot make them fit, the corresponding connection is + refused, closed or detached without ever charging those pending bytes. + Independently of pressure, a window whose session has had zero attachments for the idle interval is dropped. No reclamation stalls a journal transaction and none changes what any client is owed. @@ -1149,9 +2512,10 @@ delivered contiguously after the snapshot. The daemon adds: close of that connection, under the detach rule above — and the client reconnects at that cursor on a new connection; - at most 512 MiB of retained encoded events across the daemon's output - buffers and resident windows; on aggregate pressure, evict or detach the - slowest eligible attachment before admitting more bytes, without stalling - a journal transaction, and by the same record-then-close; + buffers and resident windows; on aggregate pressure, evict windows, close + unattached buffered connections, or detach the slowest eligible attachment + in the exact order above before admitting more bytes, without stalling a + journal transaction; - 64 attachments per session and 512 per daemon, refused at attach with **`capacity_exceeded`** when exhausted — ADR 0023's existing code, and after the connection ceiling moved to `accept` the only thing in generation 2 that @@ -1205,33 +2569,107 @@ removes only its exact same-holder target and releases only that target's transfers; a foreign, stale or other-session selector changes nothing; holder death removes its complete attachment set in EventDispatcher and Control and releases every transfer while another holder continues; the daemon retains -closing slots until relay settlement and `release_holder/2` acknowledgement, -so a replacement attach never crosses either count ceiling. +closing slots until relay settlement and the cleanup worker's +`release_holder/2` acknowledgement and `DOWN`, so a replacement attach never +crosses either count ceiling. One held cleanup worker does not block status, +acceptance within remaining capacity or retirement of an unrelated slot; 512 +simultaneous closing slots run 512 cleanup workers concurrently, while an +abnormal worker exit or missing acknowledgement selects `runtime_lost` and +never reuses its slot. At the +post-publication/pre-finalization cut, ordinary and replacement cases force +publish-ack-before-`DOWN` and `DOWN`-before-publish-ack orders. Both finish with +equal empty live sets for that holder, no pending transaction or charge and +released new transfers; the latter returns `:holder_unavailable`, while the +former may return the handle before ordinary cleanup. A replacement target and +its transfers are never resurrected after publication in either order. + +The reservation handshake is forced after origin installation, after the +registry's activation reservation or replacement borrow, and on each side of +primary promotion. Create and dormant resume each prove the invariant +`|activation set| + |reservations| <= 64`; exact duplicate creates and resumes +use distinct waiter origins but one reservation and one task. At attachment +charge 512, an exact repeated replacement uses one borrow and one Control +transaction, while a distinct request for that target receives +`attachment_conflict`. Connection loss or cut before promotion leaves no task, +waiter or charge; after promotion, primary connection loss retains the one task +and charge through its real result. Every result settles registry accounting +before any primary or waiter reply, and shutdown abandonment reuses no charge. + +Dispatcher-restart cases kill EventDispatcher with several holders before +stage, after stage, after authorization, and after the publication +acknowledgement was sent but before Control consumed it. At every cut the +original embedded caller receives `:attachment_superseded` within the fixed +bound. In the daemon form the dispatcher sentinel selects fatal `runtime_lost`; +teardown clears the relay ticket and charge exactly once, without promising a +stronger client result than the fatal close. The replacement +registration clears Control and dispatcher live/pending/waiter sets, holder and +repetition state, reserved and borrowed capacity charges, and transfer state; +late old-incarnation messages are cleanup-only, no removed replacement target +is restored, all old handles are stale, and a fresh attach succeeds. A case +holds an unacknowledged outbox row across the restart and +proves the replacement was seeded at Control's retained event sequence: the +fresh snapshot stops there, then resolution and acknowledgement release the +row exactly once. Startup and restart are also held between `init/1` and the +continue: the runtime root completes child start without deadlock, queued +attachment calls remain unserved, and no acknowledged watermark is lost before +ready. The decisive interleaving holds Control inside `post_commit` while the +successor registers: the initializing dispatcher remains responsive to the +synchronous acknowledgement, merges it by maximum with the seed, and both +operations finish before admission opens. Killing the dispatcher at each +registration phase kills its linked worker; no predecessor worker remains to +finalize a later incarnation. + +The call-shape cases prove the read-only preflight keeps its five-second bound, +the state-changing half is one deferred `:infinity` Control call, Control alone +replies, caller death drops only the route, and `post_commit` completes while a +snapshot worker is held. Killing that worker refuses only its transaction; +killing the dispatcher ends all preparation workers, and 512 pending attaches +produce no 513th worker. The protocol suite proves the inherited boolean replacement remains byte- and behavior-compatible in both generations and each adapter maps it to core's exact target, a pipelined attach and acquire cannot bind one connection to different sessions, -`control_owner_lost` vectors cover both optional-cursor shapes with the -required message, `fatal:listener_lost` reaches existing clients and -`fatal:connections_lost` does not claim a record, and the synchronous cut +`control_owner_lost` vectors cover the correlated in-flight lease-operation shape +and both uncorrelated optional-cursor shapes, with the required message and +their opposite discriminators forbidden; `fatal:listener_lost` reaches existing clients and +`fatal:connections_lost` does not claim a record, and the acknowledged cut admits pre-cut work while refusing every post-cut request. Replay evidence proves snapshot-then-contiguous at-least-once delivery with no gap across enabled, disabled and mid-stream-dropped resident windows; bounded -reclamation, slow-client detach, idle eviction and reconnect leave other -attachments progressing; all count and byte ceilings refuse independently -with process RSS recorded; and progress is coalesced or dropped without a -journal delay. +reclamation, slow-client detach, idle-observer eviction and reconnect leave other +attachments progressing; a population consisting only of initialized but +unattached clients attempts the next output-buffer admission for which +`charged_aggregate + pending_admission_bytes` would pass the aggregate +threshold, proves those pending bytes are never charged, reclaims until that +sum fits or closes in the specified order without admitting them, and observes +that the aggregate never exceeds 512 MiB, without a fabricated detach cursor; +a suspended initialized peer proves the +single non-blocking attempt cannot stall reclamation and its retained bytes are +charged until close, then return the aggregate to at most 512 MiB; all count and +byte ceilings refuse +independently with process RSS recorded; and progress is coalesced or dropped +without a journal delay. Index evidence proves startup reads at most the 4 MiB index image and never enumerates `sessions/`, including with more than 4,096 valid legacy files and arbitrarily many malformed names; oversize, corrupt, duplicate and interrupted images fail or recover as specified; a missing legacy-root index requires the offline import; foreground rollback ignores a valid index; paging carries only -the four fields and exact cursor; full-index exact-ID activation succeeds with -`index_full`; and command-ID recovery repairs an omitted row without creating -a second session. The transport cases also cover simultaneous starts, Store +the four fields and exact cursor; and full-index exact-ID activation succeeds +with `index_full`. A clean pre-rename failure notifies the causing connection, +proves the fixed temporary was removed and the directory synced, and permits a +later ID-bearing command in the same daemon lifetime to retry publication. An +unverifiable or failed pre-rename cleanup poisons publication so that later +commands touch no publication path until restart. A post-rename directory-sync +failure adopts the complete next image in memory, notifies the causing +connection, and likewise permits no later publication until restart. A +compatibility-directory failure is independent: it emits only the bounded +operator warning and is retried by a later ID-bearing command. None of those +publication outcomes reverses the session operation, and command-ID recovery +repairs an omitted row without creating a second session. +The transport cases also cover simultaneous starts, Store loss, generation negotiation, peer authorization, socket-path bounds and ADR 0023 framing refusals. @@ -1271,16 +2709,23 @@ Concept: [Consequences and rollback](0032-daemon-attachment-residency-and-replay Generation 2 is additive over generation 1's method set and both are experimental with the exact-generation rule; no mixed-generation stream promise exists. The daemon serves generation 2 only; the existing foreground -server still serves generation 1 with one attachment in its process. The -residency limits are server-enforced ceilings advertised at initialize under -the existing `limits` member. Removing the daemon leaves the foreground server -unchanged; existing embedded callers retain their behavior, and the core -supports independent same-session and same-holder attachments. The new index +server still serves generation 1 with one attachment in its process. The seven +initialize-limit additions are advertised under the existing `limits` member; +the remaining residency ceilings are server-enforced and, where specified, +reported by `daemon.status`. Removing the daemon leaves the foreground server +unchanged. For embedded callers, core keeps the same attach API shape and +preserves the common one-attachment case +while supporting independent same-session and same-holder attachments. Two +intentional transient behaviors change: a second attach no longer implicitly +supersedes the first, and holder death releases that holder's complete +attachment set and transfers. The new index is a bounded daemon discoverability file only: no journal record, Store port, session event or snapshot depends on it. Foreground rollback ignores it, while an M5 daemon validates and reuses it. A legacy root is upgraded explicitly by -the marker-protected offline import; there is no reverse migration. +the offline import under the host placement lock and then the Store marker; +there is no reverse migration. Acceptance binds this complete pair at the exact candidate the maintainer names in the governance record. Its evidence and compatibility claims remain -unproved until the tests the M5 plan maps to outcomes 2 and 4 exist and pass. +unproved until the tests the M5 plan maps to outcomes 1, 2 and 4 exist and pass, +and Outcome 5 closes against those same bytes. diff --git a/docs/adr/0032-daemon-attachment-residency-and-replay.md b/docs/adr/0032-daemon-attachment-residency-and-replay.md index e2ee49ea8..047aefc61 100644 --- a/docs/adr/0032-daemon-attachment-residency-and-replay.md +++ b/docs/adr/0032-daemon-attachment-residency-and-replay.md @@ -7,7 +7,7 @@ Technical depth: [Attachment residency mechanics](0032-daemon-attachment-residen - **Date:** 2026-09-14 - **Decision owner:** Maintainer - **Supersedes:** nothing; ADR 0023's one-attachment-per-foreground-process rule and generation-1 wire remain in force on the foreground server -- **Prerequisite for:** M5 outcomes 1, 2 and 4, accepted before the socket is +- **Prerequisite for:** M5 outcomes 1, 2, 4 and 5, accepted before the socket is bound or the core attachment change lands — that is, before M5's workstreams 1 and 3 @@ -31,10 +31,15 @@ durable events and terminal outcomes, not every dropped progress fragment. Decide the transport and the residency rules together, because the numbers only mean something against a transport. The daemon carries the ADR 0023 JSONL protocol over a Unix-domain socket, reusing its framing, initialize -handshake, admission, snapshot, event and progress records and limits -unchanged — and its request records with exactly one addition, the -`writer_epoch` every existing-session mutation carries, which is what makes -generation 2 a new schema digest rather than a rename. It serves exactly one +handshake, admission, snapshot, event and progress records and ADR 0023's +existing limit keys unchanged while adding the technical contract's exact seven +initialize-limit keys. The remaining residency ceilings are server-enforced and +reported through `daemon.status` where the contract says so. Its request records +have exactly one addition, the +`writer_epoch` every existing-session mutation carries. Request fields are not +inputs to the current schema-digest function; generation 2 has a distinct +digest because its generation, method, record-family, error-code and limit +inventories differ. It serves exactly one generation, `loopex.experimental/2`, which adds `session.list`, `daemon.status`, the two control methods, the writer-epoch field ADR 0033 names, and **two** @@ -57,15 +62,70 @@ connection closes whatever happened, so a client may learn of a shutdown only by its socket closing. It adds no durable method. An earlier draft of this decision also added `session.stop` and called it durable; that is withdrawn, because core owns durable session truth, core -has no durable stop command, and M5's five core changes — the complete -concurrent-attachment lifecycle, a read-only existence query, the trace -exclusion, bounded `quiesce/1`, and the create and resume results' two new -fields — are none of them durable commands. The daemon's bounded maintained -index is adapter state, not a sixth core change. Ending a client's involvement is releasing control and +has no durable stop command, and M5's six core changes — the complete +concurrent-attachment lifecycle, a read-only existence-and-create-history +query surface, the trace exclusion, bounded `quiesce/1`, the create and resume +results' two new fields, and managed provider lifetime — are none of them +durable commands. The daemon's bounded maintained index is adapter state, not +another core change. Ending a client's involvement is releasing control and disconnecting; the session itself keeps running, which is the point of a daemon, and another client reaches it again by acquiring control and attaching. +The bounded `quiesce/1` preserves the founding serial-writer rule from its +first census through its final fence. Its first `Control` operation atomically +enters a terminal quiescing state and returns the initial entries and ordinary +coordinators. That operation also freezes the entry key set until fencing is +complete: lifecycle messages may update a retained entry, but none may insert +or delete one, and delayed owner-ready or owner-group continuations may not +start another ordinary coordinator. Create and resume are serialized in that +same `Control` mailbox, so one already being handled finishes its Store work +and its entry-or-dormant decision before the barrier can run; every resulting +coordinator writer has an entry, while a post-commit owner-start failure is +dormant with no writer. One ordered after the barrier refuses before Store +access. Attach uses its pending-row reservation as the +cut: gate first refuses without dispatcher state, while reservation first lets +only that exact transaction finish or discard under its retained relay ticket +and capacity charge. For a command that obtained a route before the barrier, a +drain-specific coordinator call closes ordinary command admission in that +coordinator's mailbox before it proposes the abort. A command processed first +is included in the abort; one processed afterwards refuses, while internal +commit and recovery messages remain admissible. After every retained ordinary +coordinator is gone, core starts one temporary fence-mode +`SessionCoordinator` per frozen writer domain. `Control` retains the monotonic +set of session IDs for which a coordinator writer ever started and projects +only that set, bounded at 64, when quiesce begins. No-writer dormant entries are +outside the drain result and spawn no work. A drain abort uses a deterministic +`drain_abort` command and transaction ID derived from the session ID plus the +pre-admission owner epoch. The Store binds that identity to the exact journal +version, owner incarnation and canonical abort digest. If that abort is ambiguous, the +temporary coordinator resolves its exact ID before fencing: a committed result +is replayed, a terminal non-commit proceeds, an absent result is ordered against +the fresh fence CAS, and Store unavailability proposes no fence. A successor +resolves the bounded current-epoch and predecessor-epoch abort identities, +attributing a committed candidate only when replay carries the exact drain-abort +binding; a different committed binding is a client collision and no drain, +then uses its ordinary fresh owner CAS before admitting commands. The fence +transaction ID and proposed incarnation are deterministic from the session ID +and expected owner epoch. The Store still binds that identity to the exact +expected journal version and canonical mutation digest on first presentation. +Only the live fence operation re-presents those exact transaction bytes after +`commit_unknown`. After a crash, a successor reads the current epoch `E` and +resolves the bounded recoverable identities `drain_fence(E)` and, only when the +first is absent or proved to be a client collision, `drain_fence(E - 1)`. A +committed candidate counts as a fence only when replay carries the exact +owner-advance binding. Those cover a non-committing fence at the +current epoch and a committed fence that advanced it. Both absent means neither +identity that can represent the immediately unresolved stop is retained; +unavailable or an impossible result stays fail-closed. Only +after resolving that operation does the successor complete ordinary fresh +owner succession and admit commands. +The temporary +coordinator alone performs that resolution, the single +`advance_owner` and, on `commit_unknown`, one exact byte-identical +re-presentation of that fence transaction, then exits; the daemon +and quiesce helper never receive a Store handle or write session truth directly. + A client that offers only generation 1 is refused at initialize under ADR 0023's existing no-common-generation rule and nothing durable is created; generation-1 clients keep the M4 foreground server, whose wire, @@ -77,16 +137,28 @@ attachment has its own identity. Replacement therefore names the exact and no boolean can choose among several candidates. The daemon still binds a connection to at most one attachment, while embedded callers may hold a set. The first attach or acquire tentatively reserves that connection's session -before asynchronous work begins, coalesces only an exact repeated request, and -rolls the reservation back only on a definite refusal. When a connection -ends, its attachment slots stay charged until the relay has accounted for its -tasks and core has acknowledged complete holder cleanup. +before asynchronous work begins. Every activation or attachment reservation is +bound to an exact relay origin before the one primary task starts; only an exact +repetition becomes a waiter, and it starts no second task. A different request +cannot borrow the same live replacement target while one replacement is +pending. When a connection ends, its accepted slot enters `closing`. The +registry remains responsive while a monitored worker asks core to release that +holder, and the slot stays charged until every bounded origin and request worker +is terminal and the cleanup worker has acknowledged and exited. The foreground generation-1 and daemon generation-2 adapters translate their existing per-connection `replace: true` onto the only attachment that each connection may hold, so the wire remains unambiguous and ADR 0023 stays unchanged. Core monitors the stable holder, removes all of its attachments when it dies, and releases every transfer they opened as -ADR 0028 requires. The core continues to own each attachment's independent +ADR 0028 requires. Publication is irreversible for a named replacement, but +it does not resurrect a dead holder: if Control observes holder death before a +committed publication acknowledgement, it completes that transaction directly +to released, with no live route, after both owners acknowledge cleanup. An EventDispatcher-only restart is an attachment-generation +cut: Control clears every predecessor attachment and pending transaction, +seeds the replacement with its retained acknowledged event positions before +the dispatcher becomes ready, and rejects late predecessor messages. Old +handles become stale and embedded callers reattach; the replacement never +forgets a publication fence merely because its local map began empty. The core continues to own each attachment's independent cursor barrier and event-count queue, while the daemon owns per-connection socket output buffers, the resident window and the residency ceilings. The socket path is @@ -94,9 +166,12 @@ socket path is unless the operator names another, and a path beyond the platform bound is refused at start rather than truncated. The subdirectory exists so the daemon never has to re-permission or reject an operator's existing root, which the -foreground server creates `0755` under the ordinary umask. A daemon -acquires the root's store writer marker before it touches the socket path, -so two simultaneous starts resolve at the marker and never at the socket, +foreground server creates `0755` under the ordinary umask. A daemon first +acquires the root's crash-reclaimable host placement lock, then the Store's +writer marker, before it touches the socket path. Two simultaneous daemon +starts therefore resolve at the placement lock and never at the socket; the +marker still excludes a raw or embedded writer that does not participate in +that host lock, and a daemon that loses its store closes the listener and every connection before it exits. Only the daemon's own operating-system user may connect, and the boundary that enforces it is the filesystem: an owner-only subdirectory @@ -134,8 +209,22 @@ close**: the client is told, best-effort, on the connection being ended, and that connection is closed with its attachment while every other connection is untouched. A connection holds one attachment, so there is nothing for it to do afterwards, and the close is what releases the attachment in core. -Concurrent connections are themselves bounded, at 512, because a client that -never attaches is bounded by no attachment ceiling. Transient progress is coalesced or dropped first and +Accepted connection slots are themselves bounded, at 512 provisional — +including a failed handoff being reaped — plus live plus closing, +because a client that never attaches is bounded by no attachment ceiling. A +connection exists only under registry ownership: the registry creates the +waiting child linked inside the same serialized callback that records its pid, +monitor and incarnation, then unlinks it only after that row is prepared. The +registry traps exits before serving, retains the exact daemon-owner pid whose +exit still stops it, and handles the exact temporary-child exit idempotently +with its monitor. The child monitors the registry and listener from its inert +initialization. A +provisional row with no child pid therefore means that no child exists; a +listener death queued during creation is processed only after the row owns the +child and can reap it. A +disconnected slot is not reusable while one of its at most 32 request rows or +its holder cleanup remains, which also bounds relay work under reconnect churn. +Transient progress is coalesced or dropped first and never delays a journal transaction. Listener loss leaves the connection registry alive, so existing clients receive best-effort `fatal:listener_lost` before close. Connection-registry loss leaves no live @@ -154,18 +243,26 @@ activations the ceiling counts — a created session has a coordinator like any other, and a ceiling that counted resumes but not creations would bound the wrong thing. Acquiring control and attaching do not activate. -Activation is one-way: dormancy applies to attachments, resident windows and -output buffers, never to a coordinator, because a session with no attachment +Activation is one-way: idle eviction and reclamation apply to attachments, +resident windows and output buffers, never to a coordinator, because a session with no attachment may still have a model request, a tool effect, an interaction, a recovery, an unresolved `commit_unknown` or an executing admission in flight, and because stopping one would need a core deactivation operation M5 does not add. The cost is stated rather than hidden: at most 64 sessions are activated per -daemon lifetime, the 65th refuses, and the remedy is to restart the daemon. +daemon lifetime, the 65th fresh activation refuses, and the remedy is to restart +the daemon. Dormancy means only that this daemon has never activated the +durable session in its current lifetime. An exact historical create replay remains available at that bound: +the read-only create-history discriminator returns its committed session ID +without starting a coordinator or spending an activation. `residency` therefore means *this daemon activated this session in this lifetime* — a daemon-owned fact, true by construction — and never *a live coordinator exists*, which the daemon has no way to know. A coordinator that dies is core's to supervise and surfaces through core's own refusal on the -next command for that session, which the daemon forwards unchanged. +next command for that session, which the daemon forwards unchanged. Retrying +against that lifetime repeats the refusal; the operator recovery is to restart +the daemon and retry `loopex resume --daemon`, whose dormant branch starts a +new coordinator. Same-lifetime repair would require another core lifecycle +surface and is outside this decision. Lazy recovery is what a daemon can honestly promise on a store whose session directory is not Store truth and whose every open replays a full log. @@ -174,17 +271,19 @@ a bounded, daemon-owned persistent discoverability index — identity, recorded placement identity, active or dormant, controlled or not — and never over what the Store contains. Daemon startup reads only that size-capped index and never enumerates the legacy session directory, so malformed or arbitrarily numerous -directory names cannot defeat the startup bound. An existing root without the -index requires an explicit offline import before the daemon serves it; the +directory names cannot defeat the startup bound. A populated legacy root with +session entries and no index requires an explicit offline import before the daemon serves it; the import's legacy directory scan is intentionally outside the service-start bound. The index is not Store truth and can omit a session committed across a crash cut; exact-ID and command-ID recovery repair such an omission. Lineage, lifecycle state and committed sequence are not list fields: a client that needs them attaches and reads the snapshot. The proposed -limits are exact and are bound at acceptance: 512 concurrent connections per -daemon, thirty seconds for an accepted connection to complete `initialize` -before it is closed — a value derived from the lease term but carried as a key +limits are exact and are bound at acceptance: 512 occupied accepted slots +across provisional (including aborting), live and closing per +daemon, thirty seconds from kernel accept for an accepted connection to complete +`initialize` before it is closed — one absolute deadline retained through +provisional handoff and promotion, and a value derived from the lease term but carried as a key of its own, so neither contract moves the other — 64 attachments per session, 512 attachments per daemon, a 1,024-event core queue per attachment, a 4,096-event resident window per session, 4 MiB of encoded output buffered per @@ -227,12 +326,29 @@ lazy recovery avoids: a root with 4,096 recorded sessions would start 4,096 coordinators to serve the one a client wanted. And a root with one unservable session would fail a start that need never have reached it. The companion records each in full. -**Implementation and milestone-closure evidence.** Two classes together. The transport and +**Implementation and milestone-closure evidence.** Outcome 5's integrated +real-provider socket workflow waits on this decision as well as the direct +outcomes above. Two classes together. The transport and its generation are a protocol claim, so they need vectors and a compatibility proof: a generation-2 negotiation vector, refusal of a generation-1-only initialize, and an independent client over the socket. The residency rules are a durability and resource claim, so they need process fault injection and bounded-resource negatives on real processes: simultaneous daemon starts, +connect-before-readiness followed by readiness-output failure with no accepted +process or daemon/core state; a parked listener exit whose owner fatal notice +the lifecycle sentinel consumes before release authorization selecting startup +`listener_start_failed`, while the same loss after the sentinel sends exact +`begin_accept` selects running `listener_lost`; and one-sentinel arbitration +forcing both orders of stop versus completed success and deadline, and owner +component-fatal notice versus completed success and deadline, with every +pre-release winner keeping the gate parked even when the line is visible and +release authorization first making the later signal or failure take its +running path, +the accept-time initialize deadline held across provisional handoff and +promotion with queued-late completion losing and exact rows reaped, +listener death while the registry is paused after child start but before its +atomic row bind, with the trapped child exit unable to kill the registry and +the child, row, socket and slot all reaped, loss of the store under a live listener, two attachments from one embedded holder remaining independent, an explicit replacement removing only its named target, holder death releasing the holder's complete attachment and transfer @@ -259,8 +375,11 @@ agreement and no mixed-generation stream promise. Rollback is the M4 foreground server on the same local store: it ignores the daemon's bounded discoverability index, and no Store record, event or snapshot depends on that file. Removing the daemon loses only live residency and lease -state. An existing root enters M5 through the explicit marker-protected -offline index import; no reverse migration is needed. The numbers are safety +state. A populated legacy root with session entries and no index enters M5 +through the explicit offline index import; that import acquires the host +placement lock and then the Store marker. A root with neither sessions nor an +index creates the canonical empty index at ordinary startup. No reverse +migration is needed. The numbers are safety ceilings the M5 tests must show are enforced, not measured service promises. Technical depth: [Compatibility mechanics](0032-daemon-attachment-residency-and-replay-technical.md#technical-adr-0032-compatibility). diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md index 60a9ade58..ae48c8210 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover-technical.md @@ -53,81 +53,638 @@ the cross-owner ticket ledger. Collapsing the lease owners would put every session's lease transitions behind one mailbox. The plan's companion states the population and its bound. +The daemon owner accounts for that population with one explicit equation: +`owner_slots = starting_waiting_pop + starting + live + retiring <= 512`. +A `starting_waiting_pop` row owns a transferred slot but has no child; a +`starting` row reserves a slot before `start_link`; a materialized pid remains charged as `live` or +`retiring` until the daemon owner consumes its exact `EXIT`. Start failure frees +the row. A predecessor tombstone in the relay is not a process and consumes no +owner slot. + **A lease owner's failure ends that session's collaboration state, not the daemon**, on the maintainer's decision of 2026-09-20. The owner loses its transient lease record, but it does not take admitted work with it: the fixed relay retains the session's ticket set and a successor queries that set before -grant. What happens is: - -- the daemon writes `control_owner_lost` to that session's **controller** - connection and closes it with its attachment, under the daemon-initiated - detach rule ADR 0032's generation-2 inventory fixes for exactly this, and - leaves every observer attached, because an observer - holds no lease, is on a connection of its own and loses nothing; -- the lease itself is gone, held by nobody; -- the next `session.acquire_control` for that session starts a **fresh** - owner holding no lease, waits until the relay reports no unresolved mutation - ticket for the session, and then mints a **fresh epoch**. +grant. + +The connection registry holds a bounded routing mirror for every **granted** +lease: `{session_id, lease_owner_pid, owner_incarnation, +holder_connection_pid, holder_connection_incarnation, writer_epoch}`. While an +acquisition is being completed it may instead hold the exact provisional row +`{permit_id, start_op_ref, session_id, lease_owner_pid, owner_incarnation, +holder_connection_pid, holder_connection_incarnation, writer_epoch}`. The +mirror is routing, not lease authority; admission still asks the live lease +owner. There is at most one provisional or granted row per concurrent owner, +and both share the 512 owner-slot bound. + +Mirror publication is an explicit asynchronous operation rather than a nested +synchronous call. A lease owner sends its linked daemon owner +`{mirror, op_ref, owner_pid, owner_incarnation, action, exact_row, from}` and +enters one `mirror_pending` state, admitting no later lease transition. The +daemon owner records `op_ref`, the exact owner and registry incarnations, +action, row and an absolute deadline **before** it sends +`{apply_mirror, op_ref, daemon_owner_pid, registry_incarnation, action, +exact_row}`. The registry applies the exact-incarnation action and acks the +daemon owner. The daemon validates both incarnations and `op_ref`; a one-step +renewal, expiry or retirement then removes the pending row and replies to the +lease owner. Release uses the result-CAS-and-clear settlement below. A +holder-changing acquisition takes the two resolution steps below before either +the owner or a fresh child may finalize. A stale or late ack is cleanup-only. +The effective absolute mirror deadline is +`accepted_at + 5_000 ms`, or the earlier shared admission deadline when shutdown +has begun. It is one clock for the operation, never restarted by an ack or owner +exit. Every apply acknowledgement and continuation rechecks that instant in +serving and draining states. An ack queued before its timer but consumed after +the instant is cleanup-only: the daemon atomically latches `connections_lost`, +notifies the sentinel so the 35-second fail-stop watchdog is running, sends +untrappable `:kill` to the exact registry and enters fail-stop without awaiting +its reap or claiming mirror success. Its later linked `EXIT` is cleanup-only. +The timer only prompts the check; mailbox order never extends the operation. + +An acquisition that would change the holder uses three exact mirror actions: +`install_provisional`, then `resolve_provisional(granted)` or +`resolve_provisional(cancelled)`. Install succeeds only while the named +connection incarnation is still `live`. An exact not-live refusal means the +registry consumed connection `DOWN` before the relay did: the daemon owner +CASes that permit from the recorded `executing` actor to `connection_lost` (or +observes the relay's already-terminal winner), exact-clears any row and cancels +the proposal or kills and reaps the fresh child. The later relay `DOWN` is +cleanup-only. Any other install refusal is an invariant failure and takes the +`connections_lost` fail-stop path. The lease owner, or the fresh child, +only proposes the epoch and holder and remains in a provisional state. The +daemon owner is the resolution coordinator for both: after the install ack it +attempts the exact relay permit CAS +`executing(actor_pid, actor_incarnation, ...) -> result` on behalf of that +recorded actor. That CAS is the sole grant linearization. If `result` wins, the +daemon sends `granted`, and the registry promotes the exact provisional row even +when the holder slot became `closing` after the CAS. Only the promotion +acknowledgement lets the daemon acknowledge the proposer, expose the epoch and +send a reply. The relay retains the winning permit as +`settling(result, op_ref)` until that acknowledgement, so a closing connection +cannot retire its origin while registry resolution is unfinished. If connection +`DOWN` won `connection_lost`, the daemon sends +`cancelled`, exact-clears the provisional row, and tells the existing owner to +discard the proposal or kills and reaps the fresh `start_op_ref` child; no epoch +or grant becomes visible. If the relay instead consumed an existing actor +owner's `DOWN` and won `owner_lost` before the daemon's result CAS, the daemon +also sends `cancelled`, exact-clears the provisional row, finishes proposal +cleanup without addressing the dead owner, and sends that request's one +correlated `control_owner_lost` refusal while leaving its connection open; no +epoch or grant becomes visible. If the daemon's result CAS wins first, it +resolves `granted`; the later owner `DOWN` is ordinary granted-owner loss and +closes the exact promoted holder once. Each terminal permit is retained as +`settling(disposition, op_ref)` until the corresponding promotion or clear +acknowledgement and child/proposal cleanup complete. A provisional row +therefore remains through slot close until one exact resolution, rather than a +registry inferring the outcome from cross-process signal order. Duplicate +resolution is idempotent. Missing acknowledgement or registry loss follows the +same exact-registry kill and `connections_lost` fail-stop rule. Renewal does not +change the holder, and release removes one; neither enters this provisional +holder-change state. + +Release has one coordinator so it cannot split between a result sent to the +relay and a clear sent to the daemon. After the combined gate succeeds, the +lease owner enters `release_pending`, admits no later transition and sends only +the linked daemon owner exact +`{:release_proposed, release_ref, permit_id, owner_pid, owner_incarnation, +holder_connection_incarnation}`. The owner retains the original absolute lease +deadline in `release_pending`; it has not yet made the lease free. The daemon +records that operation before asking the relay to CAS the exact +`executing(owner_pid, owner_incarnation, ...)` permit to `result`. If +`connection_lost` has won, the relay retains +`settling(connection_lost, release_ref)` and renders nothing. The daemon sends +the exact owner `{:release_cancelled, release_ref, permit_id, owner_pid, +owner_incarnation}`. A matching owner still in that `release_pending` state +restores `held` with the original deadline, immediately treats an already +reached deadline as expired before admitting another transition, and returns +the exact cancellation acknowledgement to the daemon. The daemon then sends +the relay exact `release_cancellation_settled`; only its matching acknowledgement +terminalizes the no-reply `connection_lost` disposition. Exact owner death +before the restoration acknowledgement makes the daemon send the relay exact +`release_cancellation_owner_lost`; the relay terminalizes that no-reply +`connection_lost` disposition, acknowledges, and ordinary owner-loss pop and +classification handles the dead owner and every other claimed origin. Fatal +teardown supersedes both. A loss to +`owner_lost` before `connection_lost` preserves the granted mirror for the +pop-and-classification path. If `result` wins, the relay retains +`settling(result, release_ref)` without rendering. That CAS linearizes the +release. The daemon exact-clears the granted mirror under the operation's one +absolute deadline, then sends exact `release_mirror_settled` to the relay. Only +the relay's matching acknowledgement terminalizes and renders the correlated +success; only then does the daemon acknowledge the owner, which enters free or +retirement state. + +The daemon defers an owner `EXIT` ordered after `release_proposed` until the +result, cancellation or owner-loss settlement selects its exact branch, or +fatal teardown completes. The relay may independently consume the +owner's monitor `DOWN` first: if `owner_lost` wins, the later result CAS loses +and the unchanged mirror classifies the holder; if `result` won first, the +later `DOWN` is cleanup, the daemon still clears the mirror and the later pop is +absent, so no uncorrelated holder-loss form can accompany the correlated +release result. Registry or relay loss follows its existing daemon-fatal path; +neither component guesses success from a missing acknowledgement. + +When the daemon records `release_proposed` while serving, it fixes two absolute +monotonic instants from the same acceptance time: +`owner_restore_deadline = proposal_accepted_at + 5_000 ms` and +`release_settlement_deadline = proposal_accepted_at + 10_000 ms`. Neither +restarts. The relay's initial result CAS, any owner cancellation and restoration +acknowledgement, and a result branch's mirror clear must be accepted before the +first instant. The matching relay cancellation or result-settlement +acknowledgement may use the remaining interval but must be accepted before the +second. A missing or malformed relay answer at either exchange is `relay_lost`. +A result branch whose registry clear does not complete by the first instant is +`connections_lost`, as for every mirror apply. On the `connection_lost` branch, +a missing, malformed or late owner restoration acknowledgement at the first +instant makes the daemon send untrappable `:kill` to that exact owner, mark +cancellation superseded, and begin the no-reply +`release_cancellation_owner_lost` settlement. Its matching relay +acknowledgement must arrive before the second instant; otherwise the daemon +selects `relay_lost`. An owner acknowledgement queued before but consumed at or +after the first instant, or a relay settlement acknowledgement consumed at or +after the second, is cleanup-only. + +If the orderly admission cut linearizes before the release row terminalizes, +both serving timers become cleanup-only and the exact row joins the frozen +pre-cut set. It may settle only under the already fixed `admission_deadline`; +at that instant any remaining exact cleanup and terminal CAS are owned by the +`freeze_lease_ops` barrier and must finish by its `freeze_deadline`. Shutdown +therefore starts no release-private extension and suppresses ordinary +owner-loss output, while a live but stuck owner still cannot retain +`release_pending` without bound and an owner failure is not misclassified as +registry loss. + +A mirror timeout cannot merely kill a helper because a delivered registry call +could still run. There is no helper and no synchronous registry call. On the +deadline governing that exact mirror operation, or on registry loss, the daemon +owner atomically latches +`connections_lost`, notifies the sentinel, sends untrappable `:kill` to the +exact registry incarnation and enters fail-stop without awaiting its reap. Its +later linked `EXIT` is cleanup-only; the dead daemon lifetime can expose no +queued apply as a live route. A lease-owner +request sent before that owner's later `EXIT` reaches the linked daemon owner +first by signal ordering; the daemon records the deferred owner disposition and +finishes the exact mirror operation or fatal teardown before handling the +controller close. Death before the request leaves no row; death after an ack +uses the committed mirror. On exact owner `EXIT`, after any signal-ordered +pending mirror operation has completed, the daemon owner starts +`pop_owner_mirror` through the same async operation/deadline protocol. The +registry atomically removes only a row matching that session, dead owner pid and +owner incarnation and returns its exact holder route, or returns absent. The +daemon retains that result while the relay classifies every `owner_lost` +permit against the returned connection incarnation, then closes a returned +controller route only after the relay's exact classification acknowledgement. +A successor start and install remain queued until the pop, classification +acknowledgement and terminal holder-close or correlated-refusal settlement +complete, or fatal teardown wins. Duplicate or +stale pops are idempotent and cannot erase a successor. Exact owner incarnation +and epoch on clear, and exact dead incarnation on pop, prevent an old operation +from erasing a successor. + +The daemon writes the uncorrelated `control_owner_lost` form to the controller +route returned by that atomic pop and closes it with its attachment, while the +relay suppresses a correlated form for that same exact connection and every +observer remains attached. Every other claimed acquire, release or unpromoted +mutation instead receives the correlated form and stays open. The lease is then +held by nobody. The next acquire starts a fresh owner and names the predecessor +pid/incarnation to the relay; its first grant waits until the relay has consumed +that predecessor's `DOWN`, the retirement completion and every ticket ordered +before it. Only then does the new owner mint a fresh epoch. + +Tests suspend the registry while an independent Store exit and `SIGTERM` are +consumed, kill the registry during install, and order owner exit before request, +after request before ack, and after ack. They also force a late stale ack and an +old exact clear racing a successor install. An ordinary-serving ack is queued +ahead of its timer and consumed after the five-second instant, proving the +deadline check rather than timer order kills the exact registry and claims no +success. Owner-death cases prove exact pop before successor install, returned +holder classification before close, absent and duplicate pop, and an old pop +racing a successor. Forced acquire, release and unpromoted-mutation cuts consume +relay `DOWN` and pop result in both orders and prove the returned holder receives +only the uncorrelated close while every other claimed operation receives only +the correlated refusal; a promoted mutation still receives its real result. +One crossing witness pauses a serving classification before +its acknowledgement and orders stop consumption and classification completion +both ways: classification-first may complete its selected form before the cut; +stop-first rebinds the row to the transport-cut instant, makes the old timer and +queued acknowledgement cleanup-only, and emits only the later +`daemon.stopping`/EOF path. A maximum-population stop-overlap case kills every owner +after the admission cut, orders each exact `DOWN` and pop result both ways, and +proves those facts join one already-scheduled stop barrier and deadline: no +per-owner clock starts, no `control_owner_lost` form is emitted and the measured +orderly bound gains no owner-count term. Every case proves one terminal +classification or owner outcome, no stale mirror, and no blocked daemon-owner +receive loop. The fresh epoch alone is **not** what orders the old and new tenures, and an earlier revision of this section said it was. It stops a *later* command from the old tenure, which is different from accounting for a call already on its -way. The relay's retained ticket is what keeps a successor's first call from -overtaking that older call; core orders what it receives and never sees the -writer epoch. +way. The relay's predecessor-retirement barrier and retained ticket set +together keep a successor's first call from overtaking that older call; core +orders what it receives and never sees the writer epoch. **The daemon closes that window with one fixed process, the admission relay**, -added on the maintainer's decision of 2026-09-20. Every post-initialize method -request takes an admission permit from it, which gives orderly stop one linearization point. -Ten calls also take retained tickets: the eight lease-authorized core mutations -that carry `writer_epoch`, `session.create`, and `session.attach`. Reads and the -three artifact-transfer methods take unticketed permits: they grant no lease, -touch neither Control nor the journal, and cannot disturb the session census, -but sharing the permit gate prevents them from slipping past a connection-side -check while the relay cuts admission. - -For a lease-authorized call, the per-session lease owner validates the combined -gate and sends the complete core-call descriptor to the relay. For create, the -connection sends the descriptor and its request-bound activation reservation. -For attach, the connection sends its stable holder pid and reserved attachment -slot; the relay task invokes `Runtime.attach_for_holder/4`, so the task that -executes the call never becomes the lifetime holder. In every ticketed case the -relay performs this sequence before its caller receives an admission reply: - -1. allocate and retain the ticket row, including session where one exists, - request identity and canonical request digest; -2. start and monitor the task that will make the core call; -3. only then answer `admitted` with the ticket identity. - -The task can begin or even finish before the acknowledgement is delivered; -what cannot happen is an acknowledged mutation with no retained ticket or no -started, monitored executor. That is the maintainer's selected order. A -connection or lease owner that dies after acknowledgement does not cancel the -core call. The relay keeps the ticket until the task returns the real core -result, refusal included, and routes the result to the connection only if it -still exists. - -A task that dies without a result settles nothing. The relay cannot infer -whether core received the call, so it exits `relay_lost` and makes the daemon -fail-stop rather than delete the ticket or grant a successor over it. The relay -monitors every lease owner; signal ordering puts a ticket request an owner sent -before the corresponding owner `DOWN`. A replacement owner's first grant for -a session waits until that session's mutation tickets settle. Create names no -existing session and attach grants no control, so neither blocks an unrelated -lease grant; both remain visible to the drain. - -The relay's `cut` changes it to closed and acknowledges immediately. Requests -linearized before the cut retain their permits and may enter or remain in core; -requests processed after it refuse. Ticket settlement is a separate bounded -drain step. This is an admission cut, not a claim that every admitted call has -finished or that no pre-cut task can enter core after the acknowledgement. +added on the maintainer's decision of 2026-09-20. Every post-initialize request +takes a permit from it, giving orderly stop one linearization point. Ten calls +also take retained mutation tickets: the eight lease-authorized core mutations, +`session.create`, and `session.attach`. Reads and artifact transfers use only a +lightweight permit. Acquire and release use lightweight permits that remain +owned by the lease actor through terminal disposition. + +Every request row is keyed by +`origin_id = {connection_incarnation, request_slot, request_sequence}`. At most +32 are active for a connection, while the monotonic sequence prevents slot-reuse +ABA. A ticketed request first installs `pending_ticket(origin_id, class, nil)` at the +relay; a lease mutation also binds its session and the relay's currently +registered owner incarnation. That acknowledged row is the admission point; no cross-sender ordering +between connection, lease owner and relay is assumed. A mutation worker then +binds the row as `queued(worker_pid, worker_monitor, owner_incarnation)`. A +promoted row is `ticketed(task_pid, task_monitor, worker_monitor | nil)`; +promotion starts the relay task before acknowledgement and retires the waiting +worker without transferring result authority to it. Connection loss kills and +reaps a queued worker and terminalizes the row; a promoted row and its accepted +connection slot remain retained until a real result, fatal disposition or +successful shutdown seal. + +Exact lease-owner `DOWN` has its own pre-promotion rule. The relay atomically +claims every `pending_ticket` or `queued` lease-mutation origin bound to that +owner pid/incarnation as `owner_lost`; it kills and reaps a queued worker, +starts no core task and retains the claimed origin for the holder-classification +exchange below. A `ticketed` row already has a relay-owned core task and is not +reclassified: it stays retained to its real result, fatal disposition or +orderly seal. The predecessor barrier waits for both populations, so neither an +unpromoted origin nor a promoted task can be forgotten across replacement. + +A lightweight permit row retains its immutable operation class, connection +incarnation, optional session ID and optional intended actor binding +`{actor_pid, actor_incarnation}` and is +`pending(nil | {request_worker_pid, request_worker_monitor}) | +executing(actor_pid, actor_incarnation, request_worker_pid, +request_worker_monitor, start_op_ref | nil) | settling(disposition, op_ref) | +terminal(disposition)`. +The closed terminal dispositions are `result`, `owner_lost`, +`connection_lost`, `shutdown_cancelled`, and `shutdown_admitted`; one relay CAS +wins. Every acquire/release message carries its `permit_id`. Before acknowledging +a lease permit, the daemon owner supplies its session ID and intended exact +actor: the registered lease-owner pid/incarnation for an existing-owner +operation, or the daemon-owner pid/incarnation for a fresh-owner acquisition. +The relay serializes that creation against its owner monitor. Owner `DOWN` first +routes the new origin into the retained owner-loss classification; a pending +acknowledgement therefore always names a live registered actor and never leaves +an unbound lease permit. Immediately before an existing lease owner mutates +lease state, it synchronously claims `pending -> executing` only when its exact +pid/incarnation matches that immutable intended binding, while retaining the +distinct request-worker fields. For a query, read or artifact transfer, the +request worker is also the actor. In either case the connection first completes +ADR 0032's worker-ready and relay-bind handshake, and the relay sends `go` only +after the executing CAS. +For a fresh acquisition, +the daemon owner is the actor: immediately before it asks to start an owner it +claims the permit, retains an exact start `op_ref`, and remains the completion +authority for that entire first acquire. The child reports its grant or refusal +to the daemon owner, which alone settles the permit; later lease operations use +the registered lease owner as actor. A request worker is never the completion authority +after delivery; the exact lease owner or daemon owner reports the terminal +result to the relay. Connection loss kills only the request worker, never the +daemon or lease-owner actor. An acquisition grant remains provisional through +owner start and mirror install; the daemon owner's relay `result` CAS on behalf +of the recorded actor and the exact mirror resolution follow the rule above. + +Every lease owner first registers its pid, session and fresh owner incarnation +with the relay in a synchronous handshake before it may answer an acquisition +or admit a mutation. A replacement registration carries the exact predecessor +pid/incarnation. For a lease-authorized mutation the owner validates the +combined gate. For an activation-capable resume it asks the connection registry +to bind an activation reservation to the exact queued origin and promote the +primary; for another mutation it promotes the complete core descriptor +directly. Create and attach likewise install their origin first and use ADR +0032's registry-owned reservation handshake. An exact duplicate create, resume +or attach becomes `waiting(primary_ticket_id)` and starts no second task. +Before acknowledging promotion, the relay starts and monitors +the core task, then answers `admitted`. The task may finish before that +reply is delivered; the invariant is recorded ticket, task pid and monitor plus +start ordered before reply, and the ticket remains until the relay consumes the +queued result or `DOWN`. Connection or owner death after acknowledgement does +not cancel the core call. + +A task that dies without a result before the relay enters its orderly-drain +phase makes the relay and daemon fail-stop as `relay_lost`; receipt cannot be +inferred. The relay monitors owners, so a ticket +request sent before owner `DOWN` is consumed first. A replacement grant waits +for the named predecessor `DOWN` and all tickets ordered before it. Create names +no existing session and attach grants no control, so neither blocks an +unrelated lease grant; both remain visible to drain. + +Every daemon-owner lifecycle transition with the relay is a ref-tagged message +exchange, synchronous only in sequencing. The owner sends +`{:relay_barrier, barrier_ref, action}`, waits in its all-owned-exit receive loop +and advances only on the exact +`{:relay_barrier_ack, barrier_ref, action, payload}` before the action's absolute +instant. Stale or wrong-reference messages satisfy nothing. An exact malformed +answer or missing exact answer at the instant atomically latches `relay_lost`, +notifies the sentinel so the 35-second fail-stop watchdog is running, sends +untrappable `:kill` to the exact relay and enters fail-stop without awaiting its +reap; a later linked `EXIT` is cleanup-only. The owner never infers a missing +payload from its own maps. + +The relay's `cut` closes new origin rows, freezes and returns the exact pre-cut +origin-ID set with its pending, queued, promoted, waiting or settling ticket and lightweight-permit states, +then moves lease routing to `draining`, and acknowledges immediately. Before +sending it the owner starts the fixed absolute +`transport_cut_deadline = now + 5_000`; that same instant covers this +acknowledgement and the subsequent registry gate, listener reap and +uninitialized-peer sweep. A suspended relay atomically selects `relay_lost`; +the owner notifies the sentinel, sends untrappable `:kill` and enters fail-stop +without awaiting its reap. Its later linked `EXIT` is cleanup-only; no transport +or core success step follows. Any pre-cut permit +represented by one of those IDs can still claim `pending -> executing`, and any +pre-cut pending ticket can promote, before the absolute admission deadline; +among lightweight permits, only acquisition can start an owner. No origin +outside the frozen set can create a task. + +The cut linearization stores one absolute monotonic +`admission_deadline = cut_linearization_time + admission_wait_ms` in both relay +and daemon-owner state. `admission_wait_ms` is the fixed candidate value selected +before closure from a maximum-population witness with 16,384 origins across 512 +connections, including the slowest permitted pre-cut promotion and owner-start +path; closure evidence and the operator page record its value and measurement +conditions. No event restarts or extends that instant. Every permit CAS, +owner-start or mirror acceptance, and every continuation after child start or +registry acknowledgement rechecks that same instant. An expired path idempotently enters or joins +`lease_ops_frozen` even when the timer message is still queued: a late permit +claim loses, a child that materialized across the instant is killed and reaped +before grant, and a late mirror acknowledgement is cleanup-only and follows the +exact-registry kill/`connections_lost` rule. The timer prompts the transition; +mailbox order never defines the deadline. + +The orderly-stop bound charges the complete five-second transport-cut +allowance and the complete `admission_wait_ms` separately. They can overlap +after the cut acknowledgement, but they cannot be combined by `max`: the +transport clock starts before the send, while the admission clock starts only +at `cut_linearization_time`. + +At the shared admission deadline the relay also terminalizes every unpromoted +pending or queued ticket as `shutdown_cancelled`, killing and reaping its exact +request worker; later owner or registry promotion starts no task and any +unpromoted reservation is released. +The daemon owner first enters its own deadline-checked `lease_ops_frozen` +state, computes a fresh absolute +`freeze_deadline = now + relay_control_timeout_ms`, where +`relay_control_timeout_ms` is **5,000**, then sends the relay's ref-tagged, +idempotent `freeze_lease_ops(admission_deadline)` barrier. The admission +deadline remains the claim-authority cut; the later instant only bounds the +barrier and cleanup. The relay rechecks the same +instant, atomically moves routing from `draining` to `lease_ops_frozen`, CASes +`pending` rows to `shutdown_cancelled`, CASes every still-`executing` lease row +to terminal `shutdown_admitted`, and retains and returns one fixed tagged cleanup +descriptor set. A barrier-owned row is +`{:shutdown_admitted, permit_id, class, actor_pid, actor_incarnation, +start_op_ref}`; +the last field is present for a fresh acquisition and identifies its +daemon-owned provisional start. A proposed release whose relay disposition is +already selected is +`{:settling_release, permit_id, disposition, actor_pid, actor_incarnation, +release_ref}`, where disposition is the row's already selected `result` or +`connection_lost`. A holder-changing acquisition whose disposition is selected +while provisional mirror resolution or child cleanup remains uses +`{:settling_acquire, permit_id, disposition, actor_pid, actor_incarnation, +start_op_ref, op_ref}` for `result` or `connection_lost`; the daemon's exact +retained `op_ref` record supplies its provisional row and phase. Owner loss can +win before a release owner sends a proposal, so a +release or acquire already awaiting dead-owner classification instead uses +`{:settling_owner_loss, permit_id, class, actor_pid, actor_incarnation, +op_ref}` and requires no daemon release record. The immutable actor +binding supplies each pid and incarnation; the daemon's exact `release_ref` +record and retained acquisition `op_ref` supply the selected settlement phases, +so neither process scans an actor map or infers a winner. If an actor result, +connection loss or owner loss CAS wins before the barrier's atomic transition, +the row appears in its exact settling variant; if the barrier wins, the later +actor result is cleanup-only. Every later freeze request returns the same +retained set. No post-deadline claim can join it. The relay returns correlated +`daemon_stopping` for cancelled rows where a +connection survives and kills their waiting workers. An executing non-lease +read, query or transfer remains tracked through its result or the step-3 +connection/worker `DOWN`; if still live then, it terminates as +`connection_lost`. + +The frozen daemon owner rejects or tombstones every not-yet-processed +owner-start and mirror request as `shutdown_admitted`, creating no child or row. +It consumes only the relay's fixed descriptor set, never infers actors by +scanning its owner map. For a barrier-owned `shutdown_admitted` existing-owner +operation it kills and +reaps the exact descriptor actor, exact-pops the pid/incarnation mirror, joins +that result with the relay's exact owner `DOWN`, and settles every +owner-loss-claimable lease permit and pending or queued mutation origin without +`control_owner_lost` output. A promoted ticketed mutation remains relay-owned to +its real core result, fatal disposition or orderly seal. The barrier already won +the target permit before any destructive cleanup begins; a late actor result is +cleanup-only. The cleanup is idempotent and the mirror must be absent before +core quiesce. +For a fresh acquire, whose actor is the daemon +owner itself, the daemon owner remains alive and kills and reaps only the +provisional child named by the descriptor's `start_op_ref`, pid and incarnation; +if its provisional mirror was installed, the daemon first resolves it cancelled +and requires its exact absence before quiesce. A barrier-owned operation is not +described as rolled back; `shutdown_admitted` is the terminal disposition that +authorized this exact cleanup. + +For each settling-release descriptor the daemon requires the matching retained +`release_ref` record. A `result` disposition finishes or confirms the exact +mirror clear, terminalizes `result` without rendering it after the cut, and +acknowledges the owner into free or retirement state. A `connection_lost` +disposition whose owner already restored finishes its no-reply relay settlement +and leaves the restored holder alive for the drain. If restoration is unresolved, +the daemon kills and reaps that exact owner, exact-pops and classifies its mirror +without client output, sends the no-reply cancellation supersede and +terminalizes `connection_lost`. A `settling_owner_loss` descriptor requires no +release record: it completes the retained exact `DOWN`, mirror-pop and +classification join without client output and terminalizes `owner_lost`. A +`settling_acquire` descriptor requires its matching retained `op_ref` record. A +`result` row finishes or confirms `resolve_provisional(granted)`, renders no +post-cut reply and retains the granted owner for the drain. A `connection_lost` +row finishes or confirms `resolve_provisional(cancelled)`, discards an +existing-owner proposal or kills and reaps its exact fresh `start_op_ref` child, +and renders nothing. Either path leaves no provisional mirror operation pending. +A +missing or mismatched required release record, malformed relay answer or +unfinished relay join or terminalization by `freeze_deadline` selects +`relay_lost`; unfinished exact mirror work, including a mirror that remains +after an executing-owner kill, selects `connections_lost`. Shutdown owns those +deaths and dispositions, so ordinary `control_owner_lost` handling is +suppressed. If a mirror is still pending, the +barrier atomically latches `connections_lost`, notifies the sentinel, sends +untrappable `:kill` to the exact registry and enters fail-stop without awaiting +its reap or claiming that routing state settled. Its later linked `EXIT` is +cleanup-only. Idle or granted lease owners remain +alive through the runtime drain. The exact acknowledgement, returned-set +cleanup and terminal-row confirmation must all finish before `freeze_deadline`; otherwise +the owner atomically latches `relay_lost`, notifies the sentinel, sends +untrappable `:kill` to the relay and enters fail-stop without awaiting its reap, +reconstructing the set or calling core quiesce. A later relay `EXIT` is +cleanup-only. + +After the admission wait and lease freeze, immediately before core quiesce, the +daemon owner computes a new `now + relay_control_timeout_ms` instant and sends +the ref-tagged transition to `quiescing(drain_id)`. These are two sequential +uses of the same timeout value within orderly stop, not one shared instant; the +serving-only owner-loss classification instant above is outside `T_orderly`. +Failure to receive the exact acknowledgement atomically latches `relay_lost`, notifies the sentinel, +sends untrappable `:kill` to the relay and enters fail-stop without awaiting its +reap or calling core quiesce. A later relay `EXIT` is cleanup-only. A ticketed +task `DOWN` without a result in this phase retains an unresolved ticket but does +not independently turn an already ordered stop into `relay_lost`; it grants no +successor and asserts no core result. After successful core quiesce the owner +sends the ref-tagged deferred `seal_after_quiesce(drain_id)` barrier, the first consumer of the shared +teardown deadline. The relay kills every remaining exact task pid concurrently +and consumes each result/`DOWN` ordering against the remaining absolute time +before it replies. A +real result sent by a task before its exit wins because that sender's signals +arrive in order; every other retained ticket is returned as unresolved and +abandoned for this shutdown, never relabelled as settled. Each primary result +or abandonment terminalizes its live `waiting(primary_ticket_id)` origins too. +If the relay cannot finish the fixed population by that deadline, or returns +an exact malformed result, the owner atomically latches `relay_lost`, notifies +the sentinel, sends untrappable `:kill` to it and enters fail-stop without +awaiting its reap or reporting an `operator_stop` success. A later relay `EXIT` +is cleanup-only. +The population is bounded independently of connection churn: at most 512 +provisional (including aborting), live or closing accepted connection slots times 32 active origin +rows, so there are at most +16,384 origin rows and no more promoted relay tasks; waiting origins start no +task. A healthy maximum-population +seal must complete within the selected teardown bound; a suspended relay proves +deadline expiry selects the fatal path. +Core's terminal +admission barrier, census, coordinator termination and fencing have then ordered +every durable mutation domain. A pending attach is nondurable; the seal removes +its unresolved ticket after killing the caller task, while holder and runtime +teardown clear any late transaction and charge. A quiesce +error remains `drain_failed` and never receives a successful seal. + +Only after quiesce and that seal have returned and the step-3 connection/request-worker barrier +has observed every such process `DOWN`, the registry has no nonterminal origin +or permit for any closing incarnation, every relay task is gone and +each monitored cleanup worker has both acknowledged `release_holder/2` and gone +`DOWN`, do the relay and daemon owner both enter +`tearing_down`. A ref-tagged mailbox barrier then freezes the remaining idle or granted +owner pid/incarnation set, continues to reject owner-start and mirror work, and +the next teardown step performs one collective sweep. No queued pre-cut start +or mirror crossing the first barrier can be authorized, produce a grant, install a mirror +or survive cleanup, and no remaining owner can materialize behind the second. +The barrier consumes the existing teardown deadline. Missing or malformed +acknowledgement atomically latches `relay_lost`, notifies the sentinel, sends +untrappable `:kill` to the relay and enters fail-stop without awaiting its reap +or sweeping a guessed owner set; a later relay `EXIT` is cleanup-only. Registry +loss while it is +pending retains the existing `connections_lost` classification. So the ordering claim rests on the relay, and the session-scoped rule gives -the rest: the successor is granted a fresh epoch, the dead controller's -connection is closed with `control_owner_lost`, and no command from the old -tenure can be admitted afterwards. The cost is still stated honestly: the -daemon does not tell a new controller what an earlier mutation did, only that -nothing of it is still unaccounted for. +the rest. Owner death is disposed by the state the exact owner incarnation had: + +- with a granted lease, the routing mirror identifies the holder. The daemon + owner pops that exact owner pid/incarnation but does not yet write or close. + It carries the returned holder connection incarnation into the relay's + owner-loss classification exchange described next; no command from the old + tenure can be admitted afterwards; +- before a first grant, while a takeover grant waits on a predecessor or while + any lease operation has no visible result, the relay atomically claims every + pending acquire or release permit whose immutable intended actor is + `{dead_owner_pid, dead_owner_incarnation}`, every matching + `executing(dead_owner_pid, dead_owner_incarnation, ...)` permit, and every + `pending_ticket` or `queued` lease-mutation origin + bound to that exact owner as `owner_lost`. It kills and reaps a queued + mutation worker, starts no core task and retains each winner in + `settling(owner_lost, op_ref)` without rendering a reply. A promoted + `ticketed` mutation instead stays owned by its relay task until the real core + result, fatal disposition or orderly seal. The daemon owner + and relay then join two independently ordered facts: the relay's exact owner + `DOWN` and the registry's exact mirror-pop result. Under one fresh + `now + relay_control_timeout_ms` instant, the daemon sends exact + `{:owner_lost_classified, classification_ref, owner_pid, owner_incarnation, + holder_connection_incarnation_or_none}`. The relay keys and retains whichever + fact arrives first — that classification or the exact owner `DOWN` — and + joins them only when both match; an early classification is not rejected. + It then answers exact + `{:owner_lost_classified_ack, classification_ref, owner_pid, + owner_incarnation}`. If the returned holder is the same exact + connection as a claimed origin, the relay resolves that origin as + `holder_close` and suppresses its correlated reply. Every other claimed + lease-operation origin resolves as `correlated_refusal`, carrying its + `request_id` and leaving its connection open. The relay acknowledges only + after every claimed origin has one of those dispositions. Only then does the + daemon write the one uncorrelated `control_owner_lost` record and close the + returned holder. A missing or malformed classification acknowledgement takes + the existing bounded `relay_lost` path; registry loss takes + `connections_lost`. The predecessor barrier remains until this exchange and + the holder close or correlated replies are terminal. The two monitor/message + orders therefore produce the same mutually exclusive wire forms. + + That fresh five-second exchange is **serving-state only** and is outside + `T_orderly`. When the daemon owner consumes a stop and begins the admission + cut, it atomically marks every locally pending classification stop-owned + before sending the ref-tagged cut. Cut acceptance in the relay atomically + absorbs every matching in-progress classification into the earlier + `transport_cut_deadline_ms` instant; its old private timer becomes + prompt/cleanup-only. A classification whose acknowledgement the daemon owner + consumed and whose selected output it completed before consuming the stop + remains an ordinary pre-cut result. Otherwise, ordinary owner-loss + notification stops: no fresh per-owner deadline starts, any queued + classification acknowledgement is cleanup-only and no `control_owner_lost` + form is emitted. The daemon and relay retain every dead-owner and mirror-pop + fact, batch them into the current or next already-scheduled cut, freeze, + quiescing or teardown barrier, and resolve them under that phase's existing + absolute deadline. Permit dispositions become the stop-owned + `shutdown_cancelled`, `shutdown_admitted` or retained real result that the + barrier already defines; the later `daemon.stopping`/EOF path owns client + notification. Simultaneous owner deaths therefore consume one shared stop + clock rather than serial five-second clocks, and the orderly expression + still contains exactly the freeze and quiescing relay-control terms. + + A pending or executing holder renewal changes no mirror. A pending or + executing release keeps the holder mirror until its relay `result` CAS has + won and the mirror-clear settlement begins. An unpromoted mutation likewise + changes no lease mirror. Thus, when `owner_lost` wins any of those origins, + mirror pop still returns the exact holder connection; the correlated form is + suppressed only for an origin on that holder, while a non-holder origin gets + the correlated refusal and stays open. If `result` won first, the later `DOWN` is cleanup for that + permit and ordinary granted-holder or already-cleared-mirror handling applies. + A renewal result sent directly to the relay before owner exit wins `result` + by signal order and makes the later `DOWN` cleanup-only. Release uses the + daemon-coordinated result-CAS-and-clear protocol above, so it has no + cross-recipient send order to infer. A holder-changing grant report instead + reaches the daemon first and begins the provisional-mirror protocol; the + relay's independently consumed owner `DOWN` may still make `owner_lost` win + before the daemon's later result CAS. That winner is resolved `cancelled`, + exact-cleared and answered once with correlated `control_owner_lost` on an open + connection. If the daemon's result CAS wins first, granted resolution + completes and the later owner loss closes the exact promoted holder. An + `executing(daemon_owner_pid, ...)` fresh acquisition is not claimed merely + because its provisional child died: the live daemon actor remains completion + authority. If that exact child exits before sending a grant or refusal, the + daemon owner exact-clears any provisional mirror and CASes the permit to + `owner_lost`; the connection receives the correlated refusal. If the child + sent its grant report first, same-sender signal order lets the daemon consume + that report before `EXIT`; because the live daemon is the relay actor for a + fresh acquisition, it can complete the result CAS and granted resolution + before disposing the child exit. That result-first resolution makes the + later `EXIT` ordinary granted-owner loss and closes the exact holder. The + winning owner-lost disposition for any claimed non-holder lease operation + answers with a **correlated** `control_owner_lost` carrying its `request_id`; + those connections remain usable and no epoch was ever visible. A later request + worker result or `DOWN` is cleanup only and cannot emit or settle again. A + claimed origin on the returned granted holder instead observes only the exact uncorrelated holder + close; no operation receives both forms; +- when the lease is free or the owner is retiring and no lease operation was + claimed, there is no controller or request to notify. The relay still consumes the exact `DOWN`, preserves + every predecessor barrier and ticket until settlement, and then removes the + owner, predecessor and empty permit rows. + +In every state a later acquisition starts a fresh owner only after the routing +pop, classification and terminal-notification barrier, and receives a fresh +epoch only after its named predecessor ticket and retirement barrier clears. +The cost is still stated +honestly: the daemon does not tell a new controller what an earlier mutation +did, only that nothing of it is still unaccounted for. An earlier draft had the daemon restart the owner and carry on with its sockets intact, and a 2026-09-20 revision made the failure fatal to the whole @@ -156,10 +713,64 @@ lease is free, no acquisition is waiting, and the relay holds no outstanding ticket for that session — all three, since any one alone would retire an owner something still depends on. +Retirement is an acknowledged handshake, not a self-exit the daemon has to +guess about. The owner asks the relay to mark its exact pid/incarnation +retiring. After that acknowledgement, it sends the daemon owner a pre-exit +retirement intent and waits for the daemon's acknowledgement before exiting +`:normal`; same-sender ordering makes that intent precede the linked `EXIT`. +The owner slot remains `retiring` through that acknowledgement and is not free +until the daemon consumes the exact `EXIT`. The daemon may consume only that +exact normal exit as expected. Any other owner exit, including `:normal` +without the intent handshake, is +`control_owner_lost`. The relay consumes its own monitor `DOWN`, waits for +every ticket ordered before it, and sends retirement-complete to the daemon. + +An acquisition arriving before the daemon consumes predecessor `EXIT` is +queued without spawning a successor. In the callback that consumes `EXIT`, the +daemon atomically transfers the freed slot to a same-session +`starting_waiting_pop` reservation and starts no process. It then completes the +exact `pop_owner_mirror`, runs the matching owner-loss classification exchange +and finishes its selected holder close or correlated refusals; expected +retirement supplies an absent holder and an empty classification. Only the pop, +classification acknowledgement and terminal notification settlement together +change the reservation to `starting` and permit the successor child to spawn +naming the dead predecessor pid/incarnation. The relay tombstone and ticket +barrier may outlive the process and that child, but its first grant still waits +for retirement-complete and every predecessor ticket. An acquisition arriving +after `EXIT` but before the full predecessor barrier takes the same +`starting_waiting_pop` reservation without spawning; one arriving after relay +completion and the full barrier starts with no predecessor. At a population of +512, an unrelated +513th session still refuses `control_capacity_reached` rather than borrowing a +live or retiring slot. The daemon drops the predecessor identity at completion, +and the relay drops its tombstone and empty ticket set, so +churn over exact-ID, unindexed sessions cannot accumulate one row per session. +A witness retires more than 512 distinct dormant-session owners and proves the +owner, predecessor and relay maps return to baseline, while a separate +unexpected-normal exit under a held lease takes the session-scoped failure +path. At an exact population of 512, a predecessor is held after retirement +intent acknowledgement and before exit; its same-session successor remains +unspawned, the unrelated 513th acquisition refuses, and consuming exact `EXIT` +transfers that one slot into `starting_waiting_pop` without a capacity refusal +or transient 513th pid, proves no child exists before exact mirror-pop, +classification acknowledgement and terminal notification settlement, and only +then starts the successor. A forced-order case delivers the linked `EXIT` before the relay's +post-`DOWN` completion and proves the recorded pre-exit intent prevents a false +`control_owner_lost`. Owner-loss cases kill the process before its first grant +and while a takeover waits on its predecessor, with acquire and release on both +sides of `pending -> executing` and mutation in `pending_ticket`, queued and +promoted states. Every claimed non-holder operation gets its own correlated +refusal, no returned holder also gets one, an unpromoted mutation starts no core +task, and a promoted mutation returns its real result. The predecessor tickets +remain and every bounded map returns to baseline after settlement. Each case +orders owner `DOWN`, actor result and request-worker `DOWN` both ways, proving +the permit compare-and-set produces exactly one reply or close and one release. + Retaining the **lease** in a survivor was rejected: it would make a replacement process claim collaboration state it cannot reconstruct. The relay retains -only tickets for calls it itself started, holds no lease or authority, and is -not restarted. Its own failure is daemon-fatal, which is the fail-closed edge +pending, queued, waiting and promoted origins, including tickets for tasks it +started, but holds no lease or authority and is not restarted. Its own failure +is daemon-fatal, which is the fail-closed edge that lets its volatile accounting be sufficient without turning it into a durable lease record. @@ -169,9 +780,9 @@ That is the same shape ADR 0032 already gives attachments — one per connection — and it is what makes the session-scoped close exact: when a lease owner dies, "close the controller's connection" names one session's controller and cannot take a second session's control down with it. Without the rule the -close would be ambiguous, and a second acquisition on a connection that -already holds a lease refuses `control_held` for its own session rather than -being quietly admitted. +close would be ambiguous. A same-session acquisition by the holder is the +renewal defined below; an acquisition for another session on that already +pinned connection refuses ADR 0032's `invalid_request` before lease lookup. A holder's connection is **exempt from ADR 0032's idle eviction while the lease is held**, for the reason that decision states: evicting it would close @@ -188,8 +799,9 @@ a live holder's authority. Nothing about a lease is persisted or recovered. After a daemon restart no lease exists, every session is uncontrolled, the previous socket and its connections are gone, and a client presenting an old epoch is refused both because it can never match and because it is not a -holder connection. Writer exclusion between two daemons on one state root is -the local store's writer marker, unchanged. +holder connection. Runtime-Control exclusion between two daemons on one state +root is the shared crash-reclaimable host placement lock; the local Store's +unchanged writer marker remains physical Store-writer exclusion. ### Methods and fields @@ -201,13 +813,14 @@ the local store's writer marker, unchanged. authority-shaped, and a client that was just refused control is the last one that should be handed the current one. An earlier revision of this sentence said the refusal named it; ADR 0032's error table is the contract and it - carries nothing beyond the envelope. The result carries - the new `writer_epoch` and `expires_in_ms`, the remaining term on the - daemon's clock. For a known dormant session, a connection may acquire by + carries nothing beyond the envelope. Every result carries `writer_epoch` + and `expires_in_ms`, the remaining term on the daemon's clock. A holder + renewal additionally carries `renewed: true`; a fresh grant omits `renewed` + entirely. ADR 0032 owns that exact public result shape. For a known dormant session, a connection may acquire by session ID before attach. The daemon validates durable session existence first, and it does so with core's read-only session-existence query — the one that asks only whether the root holds that ID, with no attach, no - resume and no side effect. Its answer is one of the five in + resume and no side effect. Its answer is one of the four in ADR 0032's closed set and nothing more — it says whether the root holds the session, not whether this daemon has activated it, which is a daemon fact core does not carry. Acquisition therefore does **not** refuse a dormant @@ -218,22 +831,26 @@ the local store's writer marker, unchanged. taken a durable or attaching side effect to answer a question. The maintainer rejected that on 2026-09-20. An unknown ID refuses with nothing created, nothing attached and no lease granted; a known one grants, and the - held lease lets that connection call `session.resume` and then attach. Daemon startup recovery of sessions is a root-owner operation under - the store's writer marker, never a client mutation and never a grant of +held lease lets that connection call `session.resume` and then attach. Daemon startup recovery of sessions is a root-owner operation under +the host placement lock and Store writer marker, never a client mutation and never a grant of controller authority. - `session.release_control` (`session_id`, `request_id`, **`writer_epoch`**): releases the caller's own lease. It carries `writer_epoch` like every other lease-authorized call, and ADR 0032's DTO table is the contract for it; an earlier revision of this line omitted the field the table already required, which would have left two documents describing one request. A caller that is - not the recorded holder, or whose epoch does not match, refuses - `control_not_held` and changes nothing. + not the recorded holder, whose epoch does not match, whose lease is not + `held`, or whose deadline has elapsed refuses `control_not_held` and changes + nothing. Release requires **no live attachment**: it must remain possible + after a dormant session's attach refuses and on any writable exit path where + the attachment has already ended. - **Renewal is a branch of `session.acquire_control`, and it has to be stated because the refusal rule would otherwise swallow it.** Acquire from the connection that **is** the recorded holder of a lease that is `held` and unexpired is a **renewal**: the deadline moves to the full term from the admission instant, the **epoch does not change**, and the result carries - that same `writer_epoch` with the new `expires_in_ms`. Acquire from any + that same `writer_epoch` with the new `expires_in_ms` and `renewed: true`. + A fresh grant omits `renewed`. Acquire from any other connection while such a lease exists refuses `control_held`. The two branches are told apart by the connection identity alone — acquire carries no epoch on the wire, and needs none, because the holder is recorded against @@ -242,14 +859,14 @@ the local store's writer marker, unchanged. the holder" without saying which clause a holder's own acquire took. Renewal is also implicit on any admitted mutation, which extends the deadline the same way and likewise never changes the epoch. -- Every existing-session mutation in generation 2, including +- Every existing-session core mutation in generation 2, including `session.resume`, `session.prompt`, `session.steer`, `session.follow_up`, `session.abort`, `session.respond_interaction`, `session.admit_resources` and `session.activate_skill`, carries `writer_epoch` — a **required** binary identity of at most 64 bytes, exactly - as ADR 0032's request table fixes it, together with - `session.release_control`, which is lease-authorized in the same way though - it starts no core call. A request of those nine that omits it is malformed + as ADR 0032's request table fixes it. `session.release_control` carries the + same required field although it starts no core call. A request of those + eight mutations, or a release, that omits it is malformed and answered with ADR 0023's `invalid_request` (`0023-…-technical.md:304-307`), never with `control_not_held`: the gate is not reached, because there is nothing well-formed to put through it. The daemon admits it only if the sending connection is the @@ -258,9 +875,10 @@ the local store's writer marker, unchanged. connection holds a live attachment for its pinned session, except that a verified dormant session's `session.resume` may precede attach under that connection's held lease. The check and core handoff are serialized against - lease transitions for the session. + lease transitions for the session. Release uses the same serialized check + without the attachment condition. - **Every way that gate can fail answers one code, `control_not_held`, and it + **Every way either gate can fail answers one code, `control_not_held`, and it says nothing about which condition failed.** The gate has five conditions — holder connection, epoch equality, `held` state, unexpired deadline, live attachment for the pinned session — and an earlier revision required each of @@ -278,7 +896,7 @@ the local store's writer marker, unchanged. carry no epoch and pass no **lease** gate; they still take the relay permit, and attach takes a relay ticket under the rule above. - **Five conditions, six cases**, and the mapping is written out so the two + **The core-mutation gate has five conditions and six cases**, and the mapping is written out so the two numbers stop reading as a disagreement: | Case | Condition it fails | @@ -294,6 +912,11 @@ the local store's writer marker, unchanged. condition it constructed — and assert that all six produce the **same** code and the same fields on the wire, which is what stops a later revision from helpfully differentiating them. + Release has the first four conditions only. Its separate witnesses prove a + non-holder, stale epoch, non-held state and expired term all receive the same + refusal, while acquire of a dormant session followed by `session.attach` + refusing `session_dormant` can still release successfully with no live + attachment. - `session.create` has no `writer_epoch` because the session lease does not exist. It creates an uncontrolled session, and creation never implicitly grants control. The caller must acquire control explicitly and use the @@ -305,7 +928,9 @@ the local store's writer marker, unchanged. sending connection is the holder, the epoch matches and the connection holds a live attachment for its pinned session. - **Only an explicit release releases early.** A successful - `session.release_control` from the holder frees the lease at once. Every + `session.release_control` from the holder frees the lease at the relay's + `result` CAS; its success reply waits for the daemon-owned mirror clear and + exact settlement acknowledgement. Every other way a connection ends — an orderly close, an EOF, a killed client, a severed socket — leaves the lease to expire on its term. @@ -386,33 +1011,190 @@ is itself command authority. Tests prove: exactly one controller with observers within the ADR 0032 bounds; a stale epoch, copied current epoch, non-holder connection, released state expired state and a holder lacking a live attachment each refused before core admission with the current -controller unaffected; a lease transition racing command admission preserves -this order; every ticketed call has both its retained row and monitored task -before the sender receives `admitted`; attach's task uses the connection as -stable holder; killing that task before a result makes the relay and daemon -fail-stop; a cut answers immediately, carries pre-cut calls to their real -results, and refuses every post-cut permit; the expiry linearization above, with a mutation blocked inside +controller unaffected; release applies its four-condition gate without an +attachment condition, including dormant acquire, failed attach, successful +release and immediate acquisition by another connection; a lease transition racing command admission preserves +this order; every ticketed call first has its retained +`{connection_incarnation, request_slot, request_sequence}` origin row, a lease +mutation binds its waiting worker before crossing to the owner, and any +activation or attachment charge is bound by the registry before the exact +primary is promoted. Exact repeats become waiter origins and start no second +task. A promoted primary records its task pid and monitor, with task start +ordered before the sender receives `admitted` — a +fast task may already have queued its result, so liveness at delivery is not +asserted; attach's task uses the connection as +stable holder; killing that task before a result and before the relay's +`quiescing` transition makes the relay and daemon fail-stop. Four orderly-stop +cuts prove the phase distinction: after the relay has acknowledged +`quiescing(drain_id)`, an injected hold in the relay task itself is killed by the +seal and returned unresolved while operator stop succeeds rather than becoming +`relay_lost`; in the paired case the relay consumes that task's no-result `DOWN` +before it processes the quiescing transition and becomes `relay_lost`; an attach pending through quiesce is reaped by +`seal_after_quiesce`, then holder `DOWN` and runtime teardown clear its +transaction and charge; and a real result queued before task `DOWN` +wins terminal disposition rather than abandonment. One healthy seal reaps the +maximum 16,384 promoted tasks within the selected teardown bound; a second with +the relay suspended proves the shared deadline atomically latches `relay_lost`, +starts the fail-stop watchdog, sends untrappable `:kill`, awaits no out-of-phase +reap and emits no operator-stop success. Reconnect churn cannot exceed +that population because a dead incarnation remains a charged closing slot until +it has no nonterminal origin. Owner `DOWN` is forced while a lease mutation is +still `pending_ticket`, while its worker is `queued` and after promotion. The +first two cuts claim `owner_lost`, kill and reap any worker, start no core task +and complete exactly the holder close or non-holder correlated refusal selected +by mirror classification; the promoted cut keeps the relay task to its real +result. Each drains its predecessor ticket set and eventually permits a +successor grant. Every acquire/release carries its permit ID and forced cuts before +the `pending -> executing` CAS, after CAS before owner mutation, with fresh-owner +start queued behind freeze, after spawn before reply, after mutation before the +mirror request, and with mirror request before and after freeze prove one +terminal disposition. Acquire and release each prove all three permit orders: + permit before cut and claim before the absolute deadline settles normally; cut +before permit refuses; deadline before claim wins `shutdown_cancelled`. A paused +acquire and release are each killed before the exact-owner claim and after it. +For a holder origin, both cuts retain `owner_lost` until pop classification, +suppress the correlated form and produce only the uncorrelated close. A +non-holder acquire or release receives exactly one correlated refusal and +remains open. A separate cut kills the existing owner after the relay +acknowledged a pending permit with that exact immutable actor binding but +before the owner claims it, proving `owner_lost` is selected without actor +guessing and the row settles without leaking. Renewal is also killed after +claim but before its direct result in +both signal orders: a result sent before owner `EXIT` wins `result`, while the +relay consuming exact-owner `DOWN` first wins `owner_lost`. Release's separate +settlement witness kills the owner before `release_proposed`, after the proposal +but before the relay result CAS, after result wins but before mirror clear, and +after clear but before the correlated reply. It disconnects the holder after +`release_proposed` but before the result CAS, proving the relay retains +`settling(connection_lost, release_ref)`, the exact cancellation restores +`held` with the original deadline before terminalization, no success is sent, +and ordinary expiry later permits takeover without a stuck `release_pending`. +It also disconnects after result wins before mirror clear and after clear before +the success attempt, proving result-first settlement still clears the mirror, +terminalizes the permit and frees the lease even when its reply is lost. It +queues each matching result, cancellation and clear acknowledgement around +owner `DOWN`: owner death before cancellation acknowledgement uses the +exact no-reply supersede and then ordinary pop/classification, while +acknowledgement first restores `held` before the later owner-loss path. An +owner restoration acknowledgement queued before `owner_restore_deadline` but +consumed at or after it is cleanup-only, and a nonanswering owner is killed at +that same instant; both begin the no-reply supersede and ordinary owner-loss +path without leaving `release_pending`. The supersede acknowledgement is then +forced just before and at or after `release_settlement_deadline`: the first +terminalizes, while the latter is cleanup-only after `relay_lost`. Matching +cancellation and result-settlement acknowledgements are forced at the same +second cut. A missing or malformed relay settlement also selects `relay_lost`. +Separate cut crossings overtake each serving instant and prove the exact row +joins the fixed admission/freeze cleanup without a private extension. If it is +still settling at the admission deadline, the barrier returns its exact tagged +settling-acquire, settling-release or pre-proposal settling-owner-loss +descriptor. Forced acquisition `result` and `connection_lost`, release +`result`, restored `connection_lost`, unresolved `connection_lost` and +`owner_lost` rows each complete their specified no-output cleanup before +`freeze_deadline`; a missing required daemon release record, wrong tag and +deadline crossing select the named relay or registry fatal class without +beginning core quiesce. Fresh executing acquisition is frozen before and after +provisional install and must cancel or remove that exact row before child reap; +existing-owner acquire and pre-proposal release are held across freeze in both +result-versus-stop and owner-`DOWN`-versus-pop orders. The exact mirror is absent, +every claimable origin has a terminal no-output disposition, and a promoted +mutation remains on its real-result path before quiesce. An owner-loss winner preserves +the mirror and selects exactly the classified refusal or close; a result winner +clears the mirror before rendering the correlated success, makes a later pop +absent and never emits the uncorrelated form. Every cut leaves no stale mirror +or nonterminal release permit. A separate +existing-owner holder-change case consumes the grant report and install +acknowledgement, then forces owner `DOWN` before and after the daemon's result +CAS: `owner_lost` first resolves the mirror `cancelled`, waits for its exact clear +acknowledgement, sends one correlated refusal and leaves the connection open; +result first resolves `granted`, then the owner-loss path closes the exact +promoted holder once. A fresh +acquire executed by the daemon actor is separately proved not claimed merely +because its provisional child dies: child `DOWN` before a report exact-clears +the provisional mirror and makes `owner_lost` win, while a grant report before +`DOWN` is resolved first by same-sender order and makes the later death a +granted-owner loss. A pre-cut acquire and release each claim immediately +before the absolute instant, with relay freeze forced before and after the +daemon's timer message; idempotent `freeze_lease_ops` returns the same complete +tagged `shutdown_admitted`, settling-acquire, settling-release and +settling-owner-loss descriptor set in both orders. Renewal, existing-owner +acquire/release and fresh acquire each force actor-result versus atomic freeze in +both relay-mailbox orders: result first enters the exact settling protocol, while +freeze first terminalizes `shutdown_admitted` and makes the late result +cleanup-only. One disposition exists per permit without scanning the daemon +owner map. A paused +artifact read that claims and dispatches before the cut remains `executing` +across the admission deadline and quiesce, then the step-3 peer close kills it +and wins `connection_lost` exactly once; its paired pause before the claim loses +`shutdown_cancelled` at the deadline and never dispatches. Connection loss while +a mutation worker is queued behind an earlier ticket kills and reaps that +worker, terminalizes its exact queued origin and starts no core task; the same +loss while a lightweight worker is blocked at `:infinity` kills and reaps it +without killing the daemon or lease-owner actor named separately in the permit. +Separate +owner-start and mirror-ack cases queue the continuation ahead of the timer but +cross the monotonic instant, proving no grant or mirror success after it. At the admission bound the owner enters +`lease_ops_frozen`: pending rows become `shutdown_cancelled`, executing +non-lease rows remain tracked to result or step 3, existing-owner +actors or fresh-acquire provisional children are killed and reaped and +terminally recorded without pretending their mutation rolled back, while the +daemon owner survives its fresh-acquire case; queued owner/mirror work becomes +`shutdown_admitted`, and a pending mirror kills the exact registry and latches +`connections_lost`. Idle and granted owners remain through quiesce. Only after +every connection and request worker is down does the second `tearing_down` +barrier freeze and collectively sweep that remaining set; no owner or mirror +exists afterwards. The expiry linearization above, with a mutation blocked inside core across the deadline settling under its own lease while the eligible takeover waits and is granted only after it resolves, the holder's next mutation refused at the deadline, the acquiring request refusing with `control_pending` when its own deadline elapses first, the holder's connection disconnecting while its mutation is in flight, and the lease owner failing while a mutation is in flight — in every case exactly one of settle or -refuse, never both, and no epoch reused; takeover only after release or expiry -with a fresh epoch minted before the successor's first command; the three ways +refuse, never both, and no epoch reused; live-owner takeover only after release +or expiry. Post-owner-loss successor start additionally waits for exact +dead-owner pop, classification acknowledgement and terminal holder-close or +correlated-refusal settlement, while its first grant waits for every retained +predecessor ticket and retirement completion. Either route mints a fresh epoch +before the successor's first command; the three ways a controller stops holding proved separately, because only one of them is early and the transport cannot tell the other two apart — an explicit -`session.release_control` frees the lease at once, while an EOF from a politely +`session.release_control` linearizes release at the relay's `result` CAS and +reports success only after mirror-clear settlement, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after it in both cases; a controller killed mid-run fenced after takeover, its late commands refused; a lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection is sent `control_owner_lost` and closed with its attachment, its observers stay -attached on their own connections, the relay retains the -outstanding ticket, the replacement owner's first grant waits until it -settles, and the previous holder's delayed command is refused on both the -holder and the epoch check; +attached on their own connections, the replacement owner does not start until +the pop, classification and terminal-notification barrier completes, the relay +retains the outstanding ticket and the replacement owner's first grant waits +until it and retirement completion settle, and the previous holder's delayed +command is refused on both the holder and the epoch check; +at a population of 512, a retiring predecessor held after intent +acknowledgement keeps its slot and no successor pid exists, an unrelated 513th +acquisition refuses, and exact predecessor `EXIT` atomically transfers that one +slot to the queued same-session `starting_waiting_pop` reservation before any +spawn; the full routing-and-notification barrier then permits that spawn, so the +live process count never reaches 513; +mirror-publication cuts killing a lease owner before it sends the daemon +request, after that request reaches the daemon but before the registry ack, and +after ack before the daemon replies; registry suspension while Store loss and +`SIGTERM` are consumed; registry death during install; a queued apply at the +five-second deadline; a late stale ack; and an old exact clear racing a +successor install — proving the linked daemon owner remains responsive, defers +an ordered owner `EXIT`, atomically latches `connections_lost` and kills the +registry on unresolved timeout without an unnamed reap wait, emits exactly one +classification or owner outcome, and preserves no continuing daemon in which a +stale row could authorize routing; +fresh-owner and existing-owner takeover grants each force connection `DOWN` +before and after the permit result CAS. Registry-close-before-relay-`DOWN` +makes an exact not-live install refusal select `connection_lost` and reap the +proposal; loss-first leaves no provisional row, child or visible epoch, while +result-first promotes the exact row even after the slot becomes `closing` and +leaves a real lease whose reply may be lost. Both wait for the exact registry +resolution acknowledgement, and every unexpected refusal or timeout selects +`connections_lost` rather than inferring success; an abort from the new controller cancelling work dispatched under the old controller's command with a truthful cleanup outcome; an observer never acquiring authority @@ -425,6 +1207,21 @@ prompt, proved in both orders, with the prompt refused while either is missing; a dormant session acquired by ID, then resumed with epoch and attached. +Each of the five lifecycle barriers is also proved independently: `cut` under +the transport-cut deadline; `freeze_lease_ops` and `quiescing` under their fresh +five-second deadlines; and `seal_after_quiesce` and `tearing_down` under the +remaining shared teardown deadline. For every action, the exact correlated +acknowledgement advances once; stale and wrong-reference acknowledgements are +ignored; an exact malformed response and a suspended relay atomically latch +`relay_lost`, notify the sentinel, send untrappable `:kill` and enter fail-stop +without awaiting an out-of-phase reap; and another owned component `EXIT` while +the barrier is pending keeps the precedence of the first fatal class. An exact +acknowledgement consumed just before the monotonic instant succeeds, while the +same acknowledgement consumed at or after it is cleanup-only. A failed cut, +freeze or quiescing barrier starts no core quiesce; a failed seal or +tearing-down barrier reports no operator-stop success. Every later relay `EXIT` +is cleanup-only under the 35-second fail-stop watchdog. + ### Alternatives Placing the lease in core was rejected because the vision keeps collaboration @@ -454,4 +1251,5 @@ daemon removes the lease with it; no journal or file depends on it. Acceptance binds this complete pair at the exact candidate the maintainer names in the governance record. Its evidence and compatibility claims remain -unproved until the tests the M5 plan maps to Outcome 3 exist and pass. +unproved until the tests the M5 plan maps to Outcome 3 exist and pass, and +Outcome 5 closes against those same bytes. diff --git a/docs/adr/0033-collaboration-controller-lease-and-takeover.md b/docs/adr/0033-collaboration-controller-lease-and-takeover.md index d46a3447f..02efe5662 100644 --- a/docs/adr/0033-collaboration-controller-lease-and-takeover.md +++ b/docs/adr/0033-collaboration-controller-lease-and-takeover.md @@ -7,7 +7,7 @@ Technical depth: [Collaboration mechanics](0033-collaboration-controller-lease-a - **Date:** 2026-09-14 - **Decision owner:** Maintainer - **Supersedes:** nothing; the core keeps the vision §11.6 rule that it mandates no controller lease -- **Prerequisite for:** M5 Outcome 3, accepted before any admission check is +- **Prerequisite for:** M5 outcomes 3 and 5, accepted before any admission check is written — that is, before M5's workstream 4 @@ -42,7 +42,7 @@ fixed. A connection may acquire control of any session that durably exists — which the daemon establishes by asking core its read-only existence query, not by attaching or resuming to find out — by session ID, before or after it attaches to that session; what is fixed is -that no existing-session mutation is admitted until the lease is held by the +that no existing-session core mutation is admitted until the lease is held by the sending connection, its epoch matches, and — with the single exception of `session.resume` on a verified dormant session — that connection holds a live attachment for the pinned session. So a newly created session is driven by @@ -50,14 +50,20 @@ attaching and acquiring in either order and then sending the first command with the granted epoch, and a known dormant session is driven by acquiring by ID, resuming with the granted epoch and attaching. A controller renews its lease while it lives and releases it early only by -sending `session.release_control` and having it succeed; a lease that is not +sending `session.release_control` and having it succeed. Release checks the +holder, epoch, held state and unexpired term but requires no attachment, so a +controller can relinquish a dormant session after attach refuses; a lease that is not renewed expires. Nothing about how the connection ended shortens the term, because over a Unix-domain socket the daemon cannot tell a polite close from a killed client — both are EOF — so only a message the client actually sent can -mean "I am done". Takeover is explicit: an +mean "I am done". Takeover is explicit: while the lease owner remains live, an observer asks for control and receives it only when the lease is released or -expired, and the grant mints a new writer epoch before the new controller's -first command can be admitted, so a controller that was killed mid-run and +expired. If the lease owner itself fails, a later acquisition starts no fresh +owner until the exact dead-owner pop, classification acknowledgement and +terminal holder-close or correlated-refusal settlement complete. Its first +grant additionally waits until every retained predecessor ticket and retirement +completion settles. Every grant mints a new writer epoch before +the new controller's first command can be admitted, so a controller that was killed mid-run and comes back late is fenced by its stale epoch. The writer epoch is an opaque value minted fresh for every grant and never reused, so a stale epoch from any earlier tenure, including one issued before the lease owner or the whole @@ -83,22 +89,72 @@ deadline passes while core is still deciding; at the deadline the holder gains nothing further and every new mutation of its own refuses; and a takeover becomes eligible at the deadline but is granted only once those in-flight mutations have resolved. That adds no grace, because the expired holder can only finish -what it had already begun. Writer exclusion between two daemons on one -state root stays the local store's writer marker, unchanged. +what it had already begun. Runtime-Control exclusion between two daemons on one +state root uses the shared crash-reclaimable host placement lock accepted ADR +0008 requires; the local Store's unchanged writer marker remains physical +Store-writer exclusion. One fixed admission relay makes that ordering survive a lease owner's death and gives shutdown one cut. Every post-initialize method request linearizes there. The eight lease-authorized core mutations, `session.create` and `session.attach` also -take retained tickets: the relay records the ticket and starts its monitored -core task **before** it answers that the request was admitted. Attach's task +take retained tickets: each connection first installs a bounded request-slot +row at the relay. A lease owner promotes an ordinary mutation; the connection +registry first binds any activation or attachment reservation for create, +activation-capable resume and attach, then promotes the exact primary or records +an exact duplicate as a waiter. The relay starts each primary's monitored core +task **before** it acknowledges promotion; a waiter starts no task. Attach's task uses the connection pid as an explicit stable holder, so relay execution does not transfer attachment lifetime to the task. A relay cut acknowledges as -soon as it closes admission; calls admitted before it may finish, calls after -it refuse, and ticket settlement is the drain's separate bounded wait. Relay +soon as it closes admission; calls admitted before it may finish inside the +separate bounded wait, whose fixed `admission_wait_ms` candidate value is +selected from the maximum 16,384-origin/512-connection witness and recorded with +its closure conditions; pending lightweight permits are cancelled at that +deadline, as are unpromoted ticket rows; executing non-lease calls remain tracked to result or connection +teardown, and executing lease calls receive their exact shutdown disposition; +every call after the cut refuses. Any frozen pre-cut permit may claim before the +shared admission deadline, but only acquisition may start an owner. Immediately +before core quiesce the relay enters `quiescing(drain_id)`; after successful +quiesce a teardown-bounded seal preserves real results and explicitly abandons +the remaining unresolved ticket IDs before teardown. At most 512 provisional +(including aborting), live-or-closing accepted slots times 32 request rows bound +the relay to 16,384 origins and no more primary tasks. At the admission deadline +a lease-operation barrier rejects or ends every uncompleted start, mirror and +release-settlement operation; after connections close, a second mailbox barrier freezes the +remaining idle or granted owner set that teardown sweeps, so no owner or routing +mirror appears behind it. Relay loss is daemon-fatal because no process may guess what its missing ticket set contained. +A lease-owner failure remains session-scoped in every owner state. The linked +daemon owner serializes every exact mirror install, clear and dead-owner pop into the connection +registry on the lease owner's behalf; the lease owner never writes that mirror +directly. Signal ordering therefore puts a sent install ahead of that owner's +later exit. After resolving that operation, the daemon atomically pops only the +dead pid/incarnation's row and returns the exact holder it must close before a +successor install may run; a stale pop cannot erase the successor. The relay +also classifies every acquire, release or lease-authorized mutation that had no +visible result. An origin on the returned holder receives only the uncorrelated +`control_owner_lost` close. Any other claimed acquire or release, or a pending +or queued mutation claimed before promotion, receives the correlated +request-shaped refusal and its connection stays usable. A promoted +mutation remains relay-owned until its real core result or shutdown settlement, +while a mutation that had not reached core starts no task. A free or retiring +owner with no such operation has nobody to notify. In every case successor +start waits for mirror pop, classification acknowledgement and terminal +holder-close or correlated-refusal settlement. Its first grant additionally +waits for every predecessor ticket and retirement completion; the relay then +releases the bounded transient rows. + +Starting-waiting-pop, starting, live and retiring lease-owner rows share one +512-slot count. A +retiring predecessor keeps its slot until exact process exit; a same-session +successor is queued and receives that slot only when the daemon consumes the +exit, while an unrelated 513th owner is refused. A holder-changing acquisition +is provisional until its permit result wins: connection loss first clears the +provisional route and makes no grant, while result first promotes the exact +route even when the connection closes before the reply. + **Alternatives rejected.** Putting the lease in core was rejected because the vision keeps collaboration policy above core and another host may choose a different rule. Last-writer-wins without an epoch was rejected because a @@ -111,21 +167,25 @@ nothing needs. A counter-based epoch scoped to the daemon incarnation was rejected on 2026-09-14 because a lease-owner restart under the same incarnation would mint values already issued. Restarting a failed lease owner beneath live sockets was rejected on 2026-09-20 because it would claim a lease -record it cannot reconstruct. The fixed admission relay retains only the -tickets for calls it started, never the lease; its loss is daemon-fatal rather +record it cannot reconstruct. The fixed admission relay retains pending, +waiting and promoted request origins, including tickets for calls it started, +but never the lease; its loss is daemon-fatal rather than reconstructed, so the ticket ledger needs no durable record. -**Implementation and milestone-closure evidence.** This is a trust claim, so its class is +**Implementation and milestone-closure evidence.** Outcome 5's integrated +controller-kill and takeover workflow waits on this decision as well as Outcome +3. This is a trust claim, so its class is negative tests on real processes plus a security reading of the admission path: every refusal — stale epoch, copied current epoch, non-holder connection, released lease, expired lease, holder without a live attachment, observer abort — proved before core admission and before any session write, a controller killed mid-run fenced -after takeover, a lease owner killed while a mutation is in flight taking neither the daemon -nor any other session down — its controller's connection sent -`control_owner_lost` and closed, -its observers kept, and the replacement's grant held until the relay's -outstanding ticket settles — and a daemon +after takeover, a lease owner killed before and after a mutation is promoted +taking neither the daemon nor any other session down — an unpromoted operation +receives exactly its classified refusal or holder close and starts no core task, +a promoted task settles to its real result, its observers stay, and the +replacement's grant is held until both populations and the owner-loss +notification barrier settle — and a daemon restart leaving every session uncontrolled with every earlier epoch refused. No durable record changes, so no migration or rollback evidence is owed. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md index be51eb4ef..9284907df 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel-technical.md @@ -16,6 +16,18 @@ mode `0600` inside it, and a control pipe pair to the guard shell. Only the parent VM and the one child ever hold either end, and both are removed when the invocation's guard completes its cleanup. +This decision narrowly supersedes ADR 0019's statements that the environment +variable is the invocation's sole credential source, that the ready sender +resolves that variable, and that the sender must be raw-spawned and owned only +by the guardian. Host composition now consumes the variable once, the ready +sender resolves the composition-bound token through custody, and managed +guardian/sender processes are direct temporary `owner_workers` children. The +sender's supervised initial call and closure remain token-free, so they do not +carry the key in a crash-reportable child argument. Direct mode retains ADR +0019's raw linked-and-monitored sender. +ADR 0019's private channel, launch-time environment enumeration and scrubbing, +failure teardown, and forensic-memory disclaimer remain in force. + The credential frame on that socket keeps the shape it has today. The codec carries an eight-byte header — `LP`, version 2, a closed kind byte and a length — and the `credential` kind admits exactly the two members `nonce` and @@ -31,36 +43,164 @@ is where its second member comes from. ### Ordering -The order is fixed and is the reason the credential is not folded into an -earlier frame: - -1. The parent opens the namespace and the listening socket, then spawns the - carrier and guard with `env -i` and a fixed `PATH`, passing the namespace, - the nonce, the cleanup grace, the interpreter and worker paths, the socket - path, the build manifest digest and the deadline as arguments. No - credential is among them. -2. The parent writes `bootstrap::` on the control pipe; the - guard answers `ready::::` and execs the - worker, again under `env -i`. -3. The parent accepts the socket and sends the `bootstrap` frame: nonce, - codec version and build manifest digest. -4. The child answers with a `ready` frame that must equal that payload - exactly. Until this point the child has proved nothing, and no credential - exists anywhere in the invocation. -5. Only then does the guardian spawn the one-send process with a closure that - contains only the tracing capability and guardian pid. That process installs - its group-leader sink and both trace exclusions, then acknowledges the - completed exclusion. Only after that acknowledgement does the guardian send - it the token and registry handle in one message. The process resolves the - token and sends the `credential` frame. -6. The `invocation` frame follows, carrying the request, its canonical bytes - and its staged digest. Possible delivery begins here, not before. - -A child that fails step 4 — a wrong manifest digest, a wrong nonce, a codec -version it does not speak, or a deadline that expires while it is still -booting — never reaches step 5. That is the property the two existing -bootstrap-refusal cases assert, and it is why the credential is not carried by -the step-3 frame. +The managed order is fixed and is the reason the credential is not folded into +an earlier frame: + +1. Before opening a namespace, starting a Port or receiver, installing a sink, + asking for trace exclusion, routing a token or performing any provider + action, the callback preallocates distinct `guardian_ref` and `sender_ref` + values plus the guardian's `stop_reference`. +2. A linked start proxy asks Core's `owner_workers` supervisor to start the + guardian. Its initial argument is exactly + `{guardian_ref, callback_owner_pid, stop_reference}`. The guardian monitors + the callback owner, sends exactly + `{:guardian_started, guardian_ref, guardian_pid}` to that expected pid, and + waits inert. Owner loss, a wrong reference or a wrong pid makes it exit + without starting any helper or provider action. Independently, the proxy + catches a starter refusal or exit and sends exactly either + `{:start_proxy_result, :guardian, guardian_ref, proxy_pid, + {:ok, guardian_pid}}` or + `{:start_proxy_result, :guardian, guardian_ref, proxy_pid, + {:error, :unavailable}}`. The callback requires both + that exact proxy result and the exact child acknowledgement in either mailbox + order. As soon as either matching message first discloses `guardian_pid`, the + callback installs a monitor on that exact child. Child `DOWN` before the + ownership transfer completes is `:unavailable`. The callback consumes the + proxy's normal `DOWN` before it continues. +3. With that guardian monitor still installed, the callback calls + `ProviderLifetime.register(guardian_pid, stop_reference)`, and accepts only + `{:managed, retainer_pid, cleanup_grace_ms}` with the exact documented + types. It sends exactly + `{:authorize_guardian, guardian_ref, callback_owner_pid, retainer_pid, + cleanup_grace_ms, sender_ref}`. The guardian checks the reference and + callback pid and installs a monitor on `retainer_pid` before it flushes the + callback-owner monitor, then returns exactly + `{:guardian_authorized, guardian_ref, guardian_pid}`. The + callback receives that acknowledgement, then demonitor-flushes its child + monitor because the retainer monitor now owns guardian lifetime, before it + starts the sender. From + then on the guardian must accept and + acknowledge Core's exact `:loopex_provider_resource_stop` request even while + sender start, adoption or provider bootstrap is still pending. +4. A second linked start proxy asks the same supervisor to start the sender. + Its initial argument contains only `sender_ref`, the callback owner pid, the + guardian pid and the tracing capability. It contains no token, registry + handle, socket, nonce, request or credential. The sender monitors the + callback owner, sends exactly + `{:sender_started, sender_ref, sender_pid}` to that expected pid and waits + inert. Its proxy uses the same protocol with `:sender`, `sender_ref` and + sender pid. The callback again requires both exact answers and reaps the + proxy before authorization. As soon as either matching answer first + discloses `sender_pid`, the callback monitors that exact child; child `DOWN` + before adoption completion is `:unavailable`. The guardian proxy is gone before the sender + proxy can exist. A wrong reference, kind, proxy pid, child pid or result + shape is `:unavailable` and reverse-cleans any child already acknowledged. +5. While its scope and the authorized guardian are still live, the callback + sends exactly + `{:authorize_sender, sender_ref, callback_owner_pid, guardian_pid}` to that + exact sender. The sender checks both pids, links to the guardian and sends + `{:sender_adopt, sender_ref, sender_pid}`. The guardian checks the expected + reference and pid, installs a sender monitor and replies exactly + `{:sender_adopted_by_guardian, sender_ref, sender_pid, guardian_pid}`. Only + then does the sender flush its callback-owner monitor and send exactly + `{:sender_adopted, sender_ref, sender_pid}` to the callback. + It remains parked, without performing exclusion or starting its sink. Only + after the callback receives that acknowledgement does it demonitor-flush its + sender monitor — the guardian has already installed its own — and send the guardian its full + initialize message, including the request/configuration, opaque token and + registry handle but no credential bytes. The sender still holds no token, + registry handle, socket, nonce, request or credential. +6. The guardian opens the namespace and listening socket, then starts ADR + 0019's carrier and guard with `env -i` and a fixed `PATH`, passing the + namespace, nonce, cleanup grace, interpreter and worker paths, socket path, + build-manifest digest and the existing absolute invocation deadline. No + credential is among them. The parent writes + `bootstrap::` on the control pipe; the guard answers + `ready::::` and execs the worker, again under + `env -i`. +7. The guardian accepts the socket and sends the `bootstrap` frame: nonce, + codec version and build-manifest digest. The child answers with a `ready` + frame that must equal that payload exactly. Until this point the child has + proved nothing, and no credential has entered the invocation's provider + process tree or private channel. +8. Exact readiness lets the guardian send exactly + `{:begin_bootstrap, sender_ref, guardian_pid, sender_pid, absolute_deadline}` to the parked + sender. The sender validates the reference, both pids and that absolute + instant on receipt, retains the instant, and rechecks + `now < absolute_deadline` immediately before it installs both trace + exclusions. It drains every pre-clear trace signal, rechecks the instant + immediately before it spawns and installs its group-leader sink from the + untraced process. The sink is linked for abnormal termination and also + monitors the exact sender so a normal sender exit ends it. The sender + verifies both pids clear and sends exactly + `{:bootstrap_result, sender_ref, sender_pid, guardian_pid, :ok}`. An + immediate exclusion or sink-installation refusal uses the same tuple with + `{:error, :unavailable}`. A matching binding with any other result fails + closed as `:unavailable`; a wrong reference or pid is ignored and cannot + release credential context. +9. Only after validating that acknowledgement and rechecking the retained + instant does the guardian send exactly + `{:credential_context, sender_ref, guardian_pid, sender_pid, token, + registry_handle, accepted_socket, invocation_nonce}`. The sender + revalidates the reference, both pids and its retained deadline on receipt, + then rechecks the instant immediately before it performs only the registry + lookup. It parks with the returned custody reference and sends exactly + `{:credential_phase_result, sender_ref, guardian_pid, sender_pid, + :registry, :ok}`. An immediate registry refusal uses the same tuple with + `{:error, :unavailable}`. The guardian revalidates every field, the allowed + result for that phase and the absolute instant + before replying exactly + `{:credential_phase_continue, sender_ref, guardian_pid, sender_pid, + :registry, absolute_deadline}`. The sender validates the unchanged retained + deadline, rechecks it on receipt and rechecks it again immediately before + the permitted call; only then does that continuation permit custody + resolution. The sender validates the exact custody reply, parks + while it alone holds the returned bytes, and sends the exact phase-result + tuple with `:custody, :ok`, or with one normalized allowed closed-set error; + neither that message nor the guardian's matching exact continuation carries + the custody reference or bytes. That continuation includes the same absolute + deadline and permits only the `credential` frame write under the bound nonce + after the sender's receipt-time and immediate-pre-write rechecks. After a + successful write the sender drops every credential-bearing logical reference + and tail-calls a final wait whose arguments and state are non-secret. That + wait sends the exact result tuple with `:credential_frame, :ok` and parks; an + immediate write failure instead sends normalized + `{:error, :unavailable}`. Only the + guardian's matching exact continuation, again carrying the same deadline, + permits the next step. A stale, mismatched or out-of-order tuple is ignored + and then refused by the unchanged deadline; it cannot advance the sender. +10. The final `:credential_frame` continuation permits only successful sender + exit. The sender validates the unchanged deadline, rechecks it on receipt + and immediately before that transition, and exits normally from its + already non-secret final wait. The guardian consumes the exact normal sender + monitor `DOWN`, rechecks the same instant, then starts its generic phase-send helper + for the `invocation` frame carrying the request, its canonical bytes and its + staged digest. Possible delivery begins here, not before, and the + credential sender never receives the request. The same three phase gates + and tuple bindings govern the raw guardian and sender in Direct mode. If + `:begin_bootstrap`, credential context or any continuation is consumed at or + after the retained instant, the sender starts no next phase, scrubs any + custody bytes and exits with the fixed non-secret `:credential_deadline` + reason. The guardian + reports `:timeout` only after its own clock confirms expiry and starts no + invocation helper. + +The phase-result union is closed: `:registry` permits only `:ok` or +`{:error, :unavailable}`; `:custody` permits `:ok`, custody-originated +`:missing`, `:expired` or `:unavailable`, and sender-originated `:oversized` +after its byte-bound check; custody itself may not originate `:oversized`; and +`:credential_frame` permits only `:ok` or `{:error, :unavailable}`. The sender +normalizes a producer's answer and performs the size check before sending that exact ref/pid/phase-bound +tuple. No phase result or continuation carries a custody reference or +credential bytes, and any other result shape fails closed as `:unavailable`. +An error result ends the sequence and never receives a continuation. + +A child that fails step 7 — a wrong manifest digest, a wrong nonce, a codec +version it does not speak, or an expired deadline — never reaches step 8. A +guardian or sender that loses authorization before adoption never reaches step +6. Those are separate properties: the managed-start witnesses prove inert +abandonment, and the existing bootstrap-refusal cases prove no credential is +sent before child readiness. ### The token, routing registry, custody process and tracing capability @@ -89,9 +229,11 @@ a **struct**, not a binary: — sixteen random bytes under a tagged name, carrying no structure the adapter interprets and no authority of its own. It is not the credential, it does not name a module, and it cannot be resolved by anyone not already holding the -host's registry. The registry **refuses anything that is not that struct**, -and an option carrying anything else is refused as invalid before any child is -spawned. +host's registry. The registry accepts only the exact runtime map shape: +`map_size(token) == 2` with keys `[:__struct__, :id]`, the named struct tag and +a sixteen-byte `id`. A forged struct-shaped map with any extra key is +malformed. An option carrying anything else is refused as invalid before +routing or child creation. **A bare binary was the earlier shape, and it could not be validated.** That revision called the token an opaque binary of at most 256 bytes from ADR @@ -101,7 +243,7 @@ many credentials are alphabet-clean and under 256 bytes. There is no content test that separates a token from a secret. A struct separates them by type: credential bytes never arrive as `%CredentialToken{}`, so the refusal is a pattern match rather than a judgement, and a credential accidentally passed as -a token is refused at composition instead of being routed. +a token is refused by adapter preflight before routing or child creation. **One token per composed model configuration, bound at composition.** That is the whole of what this decision fixes, and it is narrower than an earlier @@ -122,8 +264,9 @@ same thing from its side and is Proposed and deferred. **Every later use of "per-invocation" in this pair qualifies the resolution.** On each call the sender routes the token through the handle, receives the -custody process's reply, writes the frame and dies; the bytes exist in the -parent only in that process, only for that write. Two invocations resolve +custody process's reply, writes the frame and dies; outside the host's custody +process, the bytes enter adapter-side parent code only in that sender and only +for that write. Two invocations resolve independently and concurrently, and a rotation between them is visible to the second. @@ -169,7 +312,7 @@ for. **How the sender reaches it, given what `complete/3` actually receives.** The callback takes three arguments and no more — `module.complete(request, options, progress)` is the exact call the coordinator makes — so a token in -the per-invocation configuration names *which* credential but says nothing +the composition-time model configuration used for the invocation names *which* credential but says nothing about *where* to ask. Those are two different things and this pair keeps them separate: @@ -190,9 +333,15 @@ separate: the live pid `start_edge/2` returned. That reference is composition data, never durable and never public, and it is what the runtime hands the adapter at dispatch. The credential registry handle is the same class and - is written the same way — `%Loopex.LLM.ReqLLM.CredentialRegistry.Handle{}` - wrapping that live reference, so the value is self-describing at a glance - and cannot be mistaken for anything else in an options list. + is written the same way — + `%Loopex.LLM.ReqLLM.CredentialRegistry.Handle{pid: local_pid, + incarnation: <<_::128>>}`. Validation requires `map_size(handle) == 3`, exact + keys `[:__struct__, :pid, :incarnation]`, the named struct tag, a pid on the + current node, a sixteen-byte incarnation and a live process at composition; + `route` sends `{:route, incarnation, token}` and an incarnation mismatch is + `:unavailable`. The later process-death race is still handled by the call. + The tagged value is self-describing at a glance and cannot be mistaken for + anything else in an options list. An earlier draft made it a *runtime-scoped registered name*. That is withdrawn: a registered name on the BEAM is VM-global whatever it is called, @@ -214,7 +363,42 @@ separate: call to the registry process. It returns *where to ask*, never bytes; `:unavailable` covers a token with no row and a registry that is gone — from the sender's side those are one fact, and neither is recoverable by - asking again. + asking again. The accepted reply set is exact: `{:ok, custody_ref}` is + accepted only when the reference passes the validator below, and + `{:error, :unavailable}` is the registry's only accepted refusal. Every + other registry reply becomes `:unavailable`, including another in-set atom + such as `:missing`, `:expired`, `:timeout`, `:oversized`, `:no_token` or + `:invalid_token`, an arbitrary atom or tuple, and a malformed or extra-key + successful reference. This producer check prevents a host-authored registry + reply from selecting another component's private classification. + + A configured token requires a `%CredentialRegistry.Handle{}` whose fields + pass the handle validator. A missing handle or any other term refuses host + composition before an invocation can start. A structurally valid handle whose + process later dies is the runtime `:unavailable` case. A route reply shaped as + `{:ok, custody_ref}` still normalizes to `:unavailable` unless `custody_ref` + passes the custody-reference validator; host-authored successful terms never + pass through as reasons. + + The one accepted private shape is exact: + + ```elixir + %Loopex.LLM.ReqLLM.CredentialCustody.Ref{ + pid: local_pid, + incarnation: <<_::128>> + } + ``` + + The registry stores that struct as its routing row. Validation requires + `map_size(ref) == 3`, exact keys `[:__struct__, :pid, :incarnation]`, the + named struct tag, a pid on the current node, a live process at the check, and + a sixteen-byte incarnation. The sender calls the custody protocol with that + incarnation; `GenServer.call` supplies request/reply correlation. A process + exit, incarnation mismatch or malformed reply is `:unavailable`. The liveness check is + not treated as a guarantee — custody may die immediately afterwards, and the + guarded call handles that race. The shape is composition-private, never + durable or public, and gives the malformed-route proof a positive contract + to compare against. **A registry that is merely slow is not one of them**, and an earlier revision blurred the two by putting "does not answer" in this list. Silence @@ -256,9 +440,13 @@ implementation states and proves its own: the reference CLI, the app-server host and the M5 daemon read `Loopex.LLM.ReqLLM.credential_variable/0` exactly once, where they compose the runtime, delete that name from the VM's environment in the same step, hold the bytes in one host-owned custody process -registered under the runtime reference rather than a global name, whose -`format_status/1` redacts its state, and register its token in the routing -registry. The real-provider lane composes the same way. Nothing in the adapter +registered under the runtime reference rather than a global name, and register +its token in the routing registry. Both host processes implement the same +defensive `format_status/1` shape as core's `OwnerGroup`: they replace +`state`, `message` and `reason` with fixed redacted atoms and replace `log` +with `[]`. Custody needs that protection for the credential bytes; the registry +needs it for its opaque tokens and custody references. The real-provider lane +composes the same way. Nothing in the adapter depends on that arrangement, and a different host may keep the bytes anywhere it can defend. @@ -273,27 +461,31 @@ way. That is the whole recovery story, and it is deliberately the shortest one available: a mechanism that could restore a credential after its custodian died would be a mechanism that had kept a second copy somewhere. -**Exactly one credential-bearing transfer exists in the parent, and it is -named.** An earlier draft said the value never appears in a message while also +**Exactly one credential-bearing BEAM message exists from the adapter edge +inward, followed by one private-channel frame to the child, and both are +named.** Host-owned composition moving the environment input into +custody, and later host-owned rotation replacing it there, are outside this +count. An earlier draft said the value never appears in a message while also putting custody in a long-lived process the sender asks — which cannot both be true, because answering is a message. The contract is a permission with a boundary, not an absolute: -- The **only** permitted credential-bearing transfer in the parent is the +- The **only** permitted credential-bearing BEAM message into or within the adapter is the custody process's reply to the sender's `resolve` call, carrying `{:ok, %{credential: bytes}}` — **keyed**, for the redaction reason below — to the one sender process that asked. It is bounded by the same 1..65,536-byte rule as the frame, it is never logged, never forwarded, and never held after the frame is written. The registry lookup that precedes it carries no credential, so the token's journey through the registry adds - no second place a secret can be seen. -- It is deliberately the same class of act as the credential frame write: one + no second parent-VM message in which a secret can be seen. +- The sender then performs the one required credential-bearing frame write on + the child's private socket. It is deliberately the same class of act as the custody reply: one short-lived process receives the bytes, uses them once, and dies. ADR 0019 already protects that process — the sender installs its own group-leader sink so no IO request can carry anything out of it, it is unregistered, and it reports only an atom or a `{:error, atom}` pair to the guardian. -- **What keeps credential bytes out of a trace: one core call that does two - things.** ADR 0030 requires the key-bearing call to be excluded by match +- **What keeps credential bytes out of a runtime-managed sender's trace: one + core call that does two things.** ADR 0030 requires the key-bearing call to be excluded by match specification *before* delivery (`0030-…-technical.md:33-35`). That is necessary and it is not sufficient, and this pair states both halves together rather than replacing one with the other: @@ -326,12 +518,33 @@ boundary, not an absolute: could run. Ordering inside the body cannot fix an exposure that happens at the boundary into it. - **So the bridge spawns a token-free bootstrap process.** What is spawned - holds **no token, no registry handle and no credential** — nothing but the - capability reference it needs to exclude itself and the pid to report back - to. Its body does one thing first: establish its exclusion, synchronously, - and confirm it. **Only then** does it receive the token and the registry - reference **by message**, and only then does it resolve and write the frame. + **So the bridge starts and adopts a token-free parked sender.** Its initial + supervised argument holds **no token, no registry handle, no channel context + and no credential**. It contains only the exact sender start reference, + callback-owner pid, guardian pid and tracing capability. Guardian and sender + remain plain recursive Task functions rather than GenServers: Task reporting + can render their token-free initial arguments, while later token, handle and + credential messages are consumed into loop locals rather than retained as a + reportable GenServer state. The complete Task/supervisor-report witness below + guards that implementation choice. Before provider + launch the sender completes its non-secret managed-start authorization, + links to the guardian, obtains the guardian's monitor acknowledgement, drops + its temporary callback monitor and parks. Exact provider readiness releases + it with + `{:begin_bootstrap, sender_ref, guardian_pid, sender_pid, absolute_deadline}`. + It validates and retains that instant, rechecks it, establishes its exclusion + synchronously and confirms success with + `{:bootstrap_result, sender_ref, sender_pid, guardian_pid, :ok}`. Immediate + exclusion or sink-installation failure returns the same bound tuple with + `{:error, :unavailable}`. **Only after the guardian validates exact success + before the deadline** does the sender receive the exact `:credential_context` tuple containing the + same binding, token, registry reference, accepted socket and invocation nonce, + and only then does it enter the three guardian-gated phases for registry + lookup, custody resolution and frame writing. Each phase returns its exact + producer-scoped result and parks before the next one. Every continuation + repeats the retained deadline; the sender rechecks it on receipt and again + immediately before the permitted operation. Neither a result nor a + continuation carries credential bytes. A message sent to an already-excluded process is not a traced call, so nothing the tracer can see ever carries the token. @@ -342,8 +555,10 @@ boundary, not an absolute: pass by tracing nothing. **The core API takes both inputs, and the adapter supplies the function - list.** The bootstrap process — which becomes the sender once it has the - token — calls, **before it receives anything**: + list.** The parked process — which becomes the credential sender only after + exact readiness — calls, after its non-secret authorization, adoption and + exact `:begin_bootstrap` tuple but **before it receives any token, registry + handle, socket, nonce or credential**: ```elixir Loopex.Trace.exclude_self(capability, functions: [{module, function, arity}]) @@ -362,7 +577,7 @@ boundary, not an absolute: functions belongs to the component that has them, which is this adapter, and it is listed below. - It returns `:ok` once the caller is excluded from **every** live trace + In managed mode it returns `:ok` once the caller is excluded from **every** live trace session and recorded as excluded for every future one. Only then is the token sent to it, and only then does it route the token, receive the credential and write the frame. Nothing @@ -385,9 +600,10 @@ boundary, not an absolute: So the token is covered by **redaction**, not by exclusion, and this pair says which rather than letting the absolute claim imply otherwise: - - the **credential bytes** never appear in any trace message, because the - sender excludes itself before it holds them — that is the claim above, and - it is unqualified; + - the **credential bytes** never appear in an adapter-sender trace message + after exclusion, because the sender excludes itself before it holds them. + Host-owned custody and composition transfers are outside this adapter + claim, as the transfer boundary above already states; - the **token** may appear in a raw trace message for `complete/3`, and what keeps it out of an **entry** is `Loopex.Trace.Entry`'s credential redaction — which today does not reach it. @@ -430,6 +646,27 @@ boundary, not an absolute: sink to redact — which is the property ADR 0030 asks for, reached for the callees as well as for the named calls. + Clearing the flags is necessary but is not the acknowledgement barrier. A + raw signal emitted before the clear may still be in flight, and the current + tracer also retains a call start in `state.calls` until its matching return. + Clearing a sender suppresses that return and would strand the row. M5 closes + both gaps in `Loopex.Trace`: level `:calls` retains no start time because its + match specification requests no return; `:returns` and `:arguments` monitor + every pid represented in the pending-call map, remove the monitor when the + last key is taken, and purge every key for that pid on confirmed `DOWN`. + Session destruction demonitor-flushes the retained monitors with the rest of + the session state. + + Managed exclusion adds the live-process cut. After clearing the sender's + flags, the Trace process calls `:trace.delivered(session, sender_pid)` and + records the returned reference instead of blocking its `GenServer` callback. + It continues reducing raw trace messages. Only when it consumes the matching + `{:trace_delivered, sender_pid, ref}` does it purge that pid's remaining call + keys and acknowledge the exclusion to `Control`. The guardian's one deadline + bounds this asynchronous barrier too. Thus every pre-clear signal is reduced + before acknowledgement, no post-ack signal arrives, and no call row whose + return was suppressed remains behind. + **The VM does not make it sticky, and neither the tracer nor a pid in options can hold it.** The same probe shows a later `:trace.process(session, pid, true, …)` re-enabling the process, so the @@ -450,12 +687,24 @@ boundary, not an absolute: So the exclusion is reached through a **capability**, and remembered in a process that outlives the tracer: - - **The capability is a host-owned process reference in model options**, the - same class as the credential registry handle beside it and as the + - **The capability is a tagged host-owned process reference in model + options**: + `%Loopex.Trace.Capability.Handle{pid: local_pid, + incarnation: <<_::128>>}`. Validation requires `map_size(handle) == 3`, + exact keys `[:__struct__, :pid, :incarnation]`, the named struct tag, a + local live pid and sixteen-byte incarnation. The capability starts unbound. + Its first successful `bind(handle, runtime)` stores exactly that runtime + identity; repeating the same bind is idempotent, while a different runtime + refuses `:capability_already_bound` without changing the first binding. + Composition succeeds only after binding the exact runtime token, and later + exclusion messages carry the incarnation. The shape is the same private + class as the credential registry handle beside it and as the executor's `reference:`. The host starts it before the runtime, as it already starts the registry and custody process, and hands it the runtime reference after runtime start but before the composition owner reports - success to its caller. A failed bind is a failed composition and unwinds + success to its caller. A failed or cross-runtime bind is a failed + composition before runtime use, child creation, token routing or custody + access and unwinds the runtime, capability, custody and registry in reverse order. It holds no membership and makes no decision; it exists because options are built before the runtime and something has to bridge that order. @@ -479,13 +728,67 @@ boundary, not an absolute: session selection rather than from a stale captured pattern. A set without counts would either leak the clear forever, restore while another sender still relied on it, or overwrite a host's selected pattern. - - **And starting a session is serialised against installing an exclusion.** - Both are `Control` operations, so both run in its process, one at a time: - a session cannot be created between a sender's flag going on and its MFA - clear being recorded. Without that, a session starting in that window - traces a sender that had already excluded itself. The witness starts a - session concurrently with an exclusion, many times, and asserts the - tracer receives nothing from the sender in either order. + - **Starting and stopping a trace session are serialised against installing + an exclusion, and strong-handle ownership is singular.** M5 reroutes + `Loopex.Runtime.trace/2` and matching stop through `Control`; they no longer + call `Trace.start_session/3` directly. Control uses an asynchronous, + reference-tagged request/ack handshake, never a nested call into Trace. It + sends the current excluded-pid set, ref-counted MFA union and exclusion + version, remains available to `post_commit`, `current_owner` and later + exclusions, and replies to the trace caller only after Trace acknowledges + the current version. + + Trace alone holds each full handle returned by `:trace.session_create/3` + in its process state and never sends or copies that value. It splits the + weak `{name, id}` element from that exact newly created full handle and + sends only the weak element to Control; it never finds the session by name + in `:trace.session_info(:all)`, where another runtime may have the same + `:loopex_trace` name. Control retains normalized configuration and selected + MFAs plus that weak identity, which does not keep the session alive, and + monitors the exact Trace pid. A + version change while start is pending sends the delta and requires another + acknowledgement before publication. The internal acknowledgement may carry + the weak identity, normalized configuration and selected MFAs, but Control + preserves the existing experimental embedded API: `Loopex.Runtime.trace/2` + still returns its present `{:ok, session_description}` shape and trace stop + and status retain their present shapes. Explicit stop makes Trace destroy + its full handle and acknowledge absence before Control drops the retained + weak identity and selection. + + Trace replacement has a registration handshake because supervisor start and + delivery of Control's monitor `DOWN` are not ordered. A new Trace announces + its exact pid and incarnation to Control and stays idle. If Control still + records the predecessor pid, it either proves that exact pid dead, + demonitor-flushes it and performs the same loss transition, or queues the + hello until that exact `DOWN`; if the `DOWN` arrived first, it consumes the + already-recorded loss and accepts the hello. Only then does Control send the + retained weak identities, configuration, selected MFAs, live excluded pids, + ref-counted MFA union and version. The replacement is pending rather than + current until its acknowledgement, and trace start and status publish + nothing from it meanwhile. + + The last full handles die with the predecessor Trace. Before creating a + replacement session the new process checks the exact old weak identity in + `:trace.session_info(:all)`. When absent it skips destroy. When present it + calls `:trace.session_destroy(old_weak)` and accepts `true`; it normalizes a + racing `false` or `ArgumentError`/`:badarg` only after a fresh all-session + query confirms that exact weak identity is now absent. Any other error, or a + still-present identity, fails replacement. It then creates the replacement, installs every + retained exclusion at the current version and acknowledges. Control + publishes or replies only after that acknowledgement. Caller death cancels + only its pending reply, not the lifecycle operation. + + This ordering prevents a session from being created between process + exclusion and MFA clearing. The witness races start with exclusion in both + mailbox orders, races stop with the last sender exit, and proves Control + never receives a full handle. The test forces both mailbox orders — old + `DOWN` before replacement hello and replacement hello before old `DOWN` — + and in each observes exactly one current Trace monitor and one full-handle + owner after acknowledgement, no start or status publication before it, and + no lookup by the shared session name. Killing Trace while the test retains + only the weak handle makes the old weak identity disappear before the + replacement publishes; a non-excluded control process proves the + replacement is live. - **The set is leak-free and proportional rather than bounded**, and the distinction is worth the word: nothing caps it, because nothing may refuse a sender. What holds is that every entry has an owner whose `DOWN` @@ -497,10 +800,11 @@ boundary, not an absolute: forever, which is a leak measured in invocations; senders are short-lived by construction, so the set returns to its baseline — normally empty — as they exit. - - **A new trace session consults the set.** When the tracer starts a session - it skips every pid Control holds, the same place `excluded?/3` already - excludes the tracer and the dispatcher by role (`trace.ex:411`), and a - tracer that has just restarted asks Control rather than starting empty. + - **A new trace session consults the set.** Control-mediated start supplies + every retained pid and MFA exclusion to a new or replacement tracer, so the + session skips every pid Control holds, the same place `excluded?/3` already + excludes the tracer and dispatcher by role (`trace.ex:411`); a restarted + tracer never starts from an empty private snapshot. - **A `Control` restart is a runtime-wide event rather than a tracing continuation.** `Control` is a `:permanent` child under `:rest_for_one` and is the **second** of the root's seven children @@ -508,28 +812,210 @@ boundary, not an absolute: the set — and also restarts **every child after it**: the worker task supervisor, the owner-group and session dynamic supervisors, the event dispatcher and, last, the tracer (`:73`, `:74-77`, `:78-81`, `:82-85`, - `:86-89`). That ends every live trace session, and it also ends every - live **session coordinator** and sender owner. Destroying each trace session - removes that session's process flags; they do not persist after session - destruction. The downstream restart also kills the senders those flags - protected, so no credential-bearing sender crosses the loss while - `Control`'s retained set is empty. A later sender excludes itself anew. A + `:86-89`). Trace is the sole holder of every full strong session handle, so + stopping it releases those last strong handles even if its `terminate/2` + callback is bypassed; Control retains only weak identities. The replacement + destroys an old weak identity or confirms its absence before it publishes a + new session. The same restart ends every session coordinator. + M5 also extends `Loopex.Runtime.ProviderLifetime` with an opaque supervised + child starter threaded through the coordinator's provider-call scope. In a + managed call, `ProviderBridge` starts both its guardian and its parked + credential sender as direct `restart: :temporary, shutdown: :brutal_kill` + children of that owner group's existing `owner_workers` Task.Supervisor. + Only those two members of the **adapter bridge tree** are direct managed + children; core's existing provider-call guard and permit-gated provider worker task are already + direct children of the same supervisor (`session_coordinator.ex:2834-2855`). The guardian continues to start + and own ADR 0019's socket receiver and generic phase-send helpers; the + guardian permits at most one socket receiver and at most one generic + phase-send helper live at a time; the credential sender starts and owns + exactly one group-leader sink. The registered guardian calls `Port.open/2` + and owns that Port; the Port's direct OS image is ADR 0019's carrier, the + carrier starts the independent OS guard, and the guard starts and owns the + provider BEAM. Links and + monitors end those raw helpers when their direct owner ends. Managed mode + has at most one transient linked start proxy at a time; Direct mode has + none. + `OwnerGroup.terminate/2` synchronously stops that supervisor, which kills + and awaits both children before the root can restart through to Trace last. + Managed start is a two-gate operation-ID handshake rather than a blocking + `Task.Supervisor.start_child/3` call from the provider callback. The callback + preallocates distinct `guardian_ref` and `sender_ref` values plus the + guardian's `stop_reference`. The guardian child argument is exactly + `{guardian_ref, callback_owner_pid, stop_reference}`; no request, + configuration, deadline, token or registry handle is present. It uses one linked proxy at a time, so at most + one transient start proxy exists for the invocation. A materialized child + monitors the callback owner, sends exactly + `{:guardian_started, guardian_ref, guardian_pid}` to that expected pid, and + waits inert. Owner `DOWN`, cancellation, a mismatched reference or a wrong + pid makes it exit without side effects. + + The linked proxy catches a refusal or exit from the supervised-start call + and returns the exact tagged result + `{:start_proxy_result, :guardian, guardian_ref, proxy_pid, result}`, where + `result` is exactly `{:ok, guardian_pid}` or `{:error, :unavailable}`. The + callback monitors the proxy and requires that result plus + `{:guardian_started, guardian_ref, guardian_pid}`; either may arrive first, + but both pids and the reference must match. As soon as the first matching + message discloses the child pid, the callback monitors that child too; an + exact child `DOWN` before transfer completion is `:unavailable`. It then consumes the proxy's + normal `DOWN` before Core registration. A proxy `DOWN` without its result, + an unexpected result or a mismatch is `:unavailable` and reverse-cleans an + acknowledged child. The sender proxy repeats the same protocol with kind + `:sender`, `sender_ref`, sender pid and `:sender_started`; the first proxy is + therefore gone before the second can exist. + + After the guardian acknowledgement, the callback keeps that child monitor + and calls `ProviderLifetime.register(guardian_pid, stop_reference)`. It accepts + only `{:managed, retainer_pid, cleanup_grace_ms}` with a live pid and valid + period, then sends exactly + `{:authorize_guardian, guardian_ref, callback_owner_pid, retainer_pid, + cleanup_grace_ms, sender_ref}`. The guardian checks the reference and + callback pid and installs the retainer monitor before it drops and flushes + the callback-owner monitor, then returns exactly + `{:guardian_authorized, guardian_ref, guardian_pid}`. The callback + receives it, then demonitor-flushes its guardian monitor because the + retainer monitor is installed, before starting the sender. From that point the guardian implements + Core's correlated `:loopex_provider_resource_stop` request and acknowledgement + even if no sender or provider child exists yet. Its first gate is then + complete. + + The callback next starts the sender with only `sender_ref`, its own pid, the + guardian pid and the tracing capability. The sender returns exactly + `{:sender_started, sender_ref, sender_pid}` to that expected callback. The + callback installs a monitor on the exact sender as soon as either the + matching proxy result or sender acknowledgement first discloses it; sender + `DOWN` before adoption completes is `:unavailable`. The + callback then sends exactly + `{:authorize_sender, sender_ref, callback_owner_pid, guardian_pid}` only + while both its scope and the guardian remain live. The sender checks both + pids, links to the guardian and sends + `{:sender_adopt, sender_ref, sender_pid}`. The guardian validates both + fields, installs the sender monitor and returns exactly + `{:sender_adopted_by_guardian, sender_ref, sender_pid, guardian_pid}`; only + then does the sender drop and flush its callback-owner monitor and return + exactly `{:sender_adopted, sender_ref, sender_pid}` to the callback. + Receipt of that acknowledgement completes the second gate. The callback + demonitor-flushes its sender monitor only then, because the guardian has + already installed its own. The sender + remains parked. Only now does the callback send the + guardian the full initialize message, including the request/configuration, + opaque token and registry handle but no credential bytes. Ordinary callback + completion no longer governs either process: the retainer governs the + guardian, the guardian's link and monitor govern the sender, and both remain + direct temporary `owner_workers` children. + + Immediate guardian proxy/result, child acknowledgement, Core registration, guardian authorization, sender + start or adoption failure is `:unavailable`; partial children are stopped in + reverse order and managed mode never falls back to raw spawn. Raw spawn + remains only for explicitly unmanaged calls. A live `owner_workers` that + never answers either start is an owner-group/runtime liveness failure: the + transfer is incomplete and the adapter's sender clock is not armed. The + proxy may wait at `:infinity`; scope or owner-group teardown kills the + authorization owner and proxy, and Core can stop an already registered + guardian through its installed stop protocol. A queued child that + materializes later sees callback-owner `DOWN` and exits inert. The contract + does not misreport such a stall as adapter `:timeout`. + + Once both gates complete, the callback's initialize message carries the + same absolute invocation deadline allocated before either start; no step + resets it. The guardian checks it before launch and, if it has elapsed, + performs reverse cleanup and reports `:timeout`. Otherwise the guardian + launches ADR 0019's tree. Only exact provider-child readiness lets it send + `{:begin_bootstrap, sender_ref, guardian_pid, sender_pid, absolute_deadline}` to the parked + sender; any pre-ready refusal, deadline or guardian death releases nothing. + The sender validates the reference, both pids and retained deadline, + rechecks the instant before exclusion and again immediately before sink + installation, and replies with the exact union + `{:bootstrap_result, sender_ref, sender_pid, guardian_pid, result}`, where + `result` is only `:ok` or `{:error, :unavailable}`. Only after the guardian + validates exact success before the deadline may it send + `{:credential_context, sender_ref, guardian_pid, sender_pid, token, + registry_handle, accepted_socket, invocation_nonce}`. The sender validates + all three binding fields and its retained deadline on receipt, then + rechecks the instant immediately before it routes the token. Registry + lookup, custody resolution and credential-frame write are + three separately parked phases. After each, the sender sends the exact + non-secret `{:credential_phase_result, sender_ref, guardian_pid, + sender_pid, phase, result}` tuple. The result union is producer-scoped as + fixed above, and an error never receives a continuation. Only the + guardian's exact matching `{:credential_phase_continue, sender_ref, + guardian_pid, sender_pid, phase, absolute_deadline}`, issued after its own + deadline check, permits the next phase. The sender validates the unchanged + instant, rechecks it on receipt and again immediately before the permitted + operation. The `:custody` result and continuation carry no custody + reference or credential bytes. After a successful credential-frame write, + the sender drops all credential-bearing logical references and tail-calls a + non-secret final wait before sending its `:credential_frame` result. The + final continuation permits only normal sender exit; only exact normal sender `DOWN` and a + fresh guardian deadline check permit the guardian's generic helper to send + the invocation frame. A wrong reference, pid, phase or deadline, or a stale + replay, is ignored and then refused by the unchanged deadline. A matching + current-phase tuple with a malformed result or a producer-forbidden atom is + immediate `:unavailable`. If the sender consumes credential context or a + continuation at or after the retained instant, it starts no next operation, + scrubs any custody bytes it still holds and exits with fixed non-secret reason + `:credential_deadline`; the guardian does not classify `:timeout` until its + own clock confirms expiry. Only the expected normal sender `DOWN` in the + final-exit state may advance to the invocation helper. Any other sender + `DOWN` observed before the guardian's clock reaches the deadline — abnormal, + killed, `:credential_deadline`, or normal in any earlier state — maps to + `:unavailable`, tears down the sink and provider tree, and starts no + invocation helper. A `DOWN` observed after the guardian confirms expiry + maps to `:timeout` regardless of its process reason; no raw sender reason + crosses the adapter boundary. The sender + explicitly keeps + `trap_exit` false for its lifetime; the guardian traps exits and separately + monitors the sender for classification. A monitor in + the sender would be insufficient because `DOWN` could wait in its mailbox + behind the infinite call, while an abnormal guardian exit propagates through + the link and terminates the non-trapping sender immediately. `:kill` reaches + the sender as `:killed`, which would be trappable, so the false flag is the + required invariant rather than the exit reason. Normal linked exit would be + ignored; every normal guardian cleanup therefore explicitly stops and awaits + the sender before the guardian returns. Guardian abnormal death ends a + parked sender or one blocked in sink installation, clears its exclusions + through Control's sender monitor and writes no frame. The sink is + non-trapping and linked to the sender for abnormal or kill propagation; it + also monitors the exact sender and exits on `DOWN`, so ordinary sender + success cannot leave it alive. Direct supervisor siblings + alone would not provide that relation. Explicit stop destroys each strong + trace-session handle and acknowledges its absence, and no credential-bearing sender + can cross the loss while `Control`'s retained set is empty. A later sender + excludes itself anew. A sender whose `exclude_self/2` call finds the capability or `Control` immediately unreachable fails `:unavailable` before it receives the token; one whose call remains unanswered is killed by the guardian at the invocation deadline and reports `:timeout`. - **It fails closed under the guardian's one deadline.** `exclude_self/2` + **It fails closed under one deadline per mode.** `exclude_self/2` returns only once both exclusions are installed. Its call has no independent - timeout and uses no hidden `GenServer.call/2` default: the guardian's existing - invocation deadline bounds bootstrap, exclusion, resolution and the frame - write together. If the capability or `Control` is immediately unreachable, + timeout and uses no hidden `GenServer.call/2` default. The absolute invocation + deadline allocated before managed start is never reset. Once the managed + guardian is registered, the sender adopted and the guardian initialized, + that same instant bounds provider launch and readiness, sender release, + exclusion, registry routing, custody resolution and frame write together. + Direct mode has no Core registration or adoption gate: its raw guardian + carries the request's same pre-launch absolute instant through inherited + session clearing, sink installation, registry routing, custody resolution + and frame write. In either mode, a timer only prompts evaluation: before the + guardian accepts a provider-ready frame, bootstrap result or phase result, + and before it emits credential context or the next continuation, it rechecks + monotonic `now < deadline`. The sender independently rechecks the carried + unchanged instant when it consumes `:begin_bootstrap`, credential context or + any continuation and again immediately before the permitted operation. A + result or continuation queued before the timer but consumed at or after the + instant loses to `:timeout`; mailbox order and sender suspension cannot extend + the call. + If the capability or `Control` is immediately unreachable, the sender refuses `:unavailable` before it receives the token. If exclusion is merely slow or remains unanswered, the guardian kills the sender at the - invocation deadline and reports `:timeout`. A tracer restart destroys its - sessions; while the tracer is absent, `Control` can record the sender and MFA - set for the replacement session. The sender never proceeds on an unconfirmed - exclusion. + invocation deadline and reports `:timeout`. A tracer restart drops its sole + strong handles; the production replacement confirms Control's weak old + identities absent before publishing new sessions. The defensive destroy + branch exists for a present identity and is exercised only by the explicit + forbidden-extra-strong-handle fault fixture described below. While Trace is absent, + `Control` can record the sender and MFA set for the replacement session. The + sender never proceeds on an unconfirmed exclusion. **The capability is mandatory wherever a credential token is configured, and an absent one refuses.** An earlier revision of this pair let an @@ -558,6 +1044,66 @@ boundary, not an absolute: was: a case in which the credential would have been resolved in a process a session may have been tracing. + **The accepted direct `complete_prompt/3` path is a separate no-runtime + mode.** The helper constructs a private `%TraceCapability.Direct{}` itself; + a caller cannot select that tag in runtime model options. It carries no + runtime reference and is accepted only with `ProviderLifetime.unmanaged`. + Its raw sender may inherit a Loopex session's `set_on_spawn` flags from a + traced caller even though it is outside the supervisor tree, so ancestry is + not treated as safety. The token-free sender's first phase enumerates + `:trace.session_info(:all)`, skips its `{:legacy, :default}` row, clears + itself in every non-legacy `{name, id}` with + `:trace.process(session, self(), false, [:all])`, clears the legacy tracer + separately with `:erlang.trace(self(), false, [:all])`, and verifies through + `:trace.info(session, self(), :flags)` that every still-live enumerated named + session reports no call flag and that the legacy flags are clear. A named + session destroyed between enumeration, clear and verification is safe only + after its absence is confirmed; any still-live session whose clear or + verification fails refuses the invocation before token delivery. Using only + `:erlang.trace/3` is explicitly insufficient for + named OTP trace sessions. The Direct guardian starts that sender with + `:erlang.spawn_opt(..., [:link, :monitor])`; the sender keeps `trap_exit` + false. An abnormal or `:kill` guardian exit therefore ends a sender blocked + in clear, custody or frame write, while normal guardian cleanup explicitly + stops and awaits the sender. For every still-live named session it also requests + and awaits the matching `:trace.delivered(session, self())` marker, and for + legacy tracing it awaits `:erlang.trace_delivered(self())`; sessions destroyed + during that interval must be confirmed absent. Those waits remain inside the + Direct request's pre-launch absolute deadline. From the now-untraced sender + it then spawns and + installs the group-leader sink, so the sink inherits no named-session or + legacy call flags; it verifies that fact for both pids. It then acknowledges + that local exclusion and sink installation to the guardian; only then may the guardian send the + token, handle and channel context. A later Loopex session enumerates only its + runtime-owned processes and cannot newly select this direct sender. The + bootstrap calls themselves may be traced, but their closure carries no token + or credential. A session already capable of being inherited is in that + enumeration; a session created later cannot select the raw sender because it + is outside the runtime tree. This mode does not claim protection against an unrelated host + using raw `:erlang.trace` outside Loopex's contract after the acknowledgement. + Direct mode neither clears nor restores the three adapter MFAs in a runtime + trace session: it has no `Control` capability and lies outside ADR 0030's + runtime-owned process domain. Failure to clear or verify any still-live + inherited session maps to private `:unavailable`; a session confirmed + destroyed during the clear is the successful absence case. Host-owned + custody tracing is outside the adapter boundary in this mode. The Direct + sender has no authenticated path back into a runtime Trace process to purge + state while it is alive; the generic pending-call monitor above therefore + purges its rows on sender `DOWN`, and the Direct witness reads that state back + at baseline after exit. Its linked-and-monitoring sink has the same sender + lifetime relation as managed mode, so neither normal completion nor guardian + failure can leave a sink behind. + Any capability bound to + a runtime requires the managed starter and may never use the raw fallback. + A witness invokes the existing real-provider `complete_prompt/3` case from a + runtime process carrying a live session's `set_on_spawn` flags, names the + adapter and `:gen_tcp`, proves the token-free bootstrap may be observed but + no message after the clear from either sender or sink carries the token or + canary, and proves a forged + Direct tag in runtime composition is refused. The probe runs on both + toolchain pairs and includes a named session for which `:erlang.trace/3` + alone leaves `:trace.info(..., :flags) == [:call]`. + **The MFAs this adapter supplies, exactly three.** They are the functions that hold the resolved bytes or the token, and the list is passed to `exclude_self/2` by the adapter itself: @@ -583,60 +1129,150 @@ boundary, not an absolute: `ProviderCodec` an earlier revision proposed is dropped: the process flag covers its calls without costing every other frame's tracing. - **What is kept as defence in depth**, explicitly labelled so nobody mistakes - it for the mechanism: the **keyed shape**. The three bridge functions carry - credential bytes only as a value under a credential-named key — - `receive_custody_reply/2` returns `{:ok, %{credential: bytes}}` and never - `{:ok, bytes}`; `write_credential_frame/2` takes that keyed map — so a - credential that somehow reached `Entry.render/2` would be placeholdered at - any size. It protects nothing about callees, and it is not what satisfies - ADR 0030. + **The keyed credential map is a validation and dataflow shape, not a trace + control.** `receive_custody_reply/2` returns + `{:ok, %{credential: bytes}}` and never `{:ok, bytes}`; + `write_credential_frame/2` takes that exact map. Exact means + `map_size(value) == 1` and `Map.keys(value) == [:credential]`; a success map + with any extra key is malformed and becomes `:unavailable` before a frame is + written. It makes malformed host + replies decidable and keeps the byte-bearing path closed, but it is not a + fallback if exclusion fails. ADR 0030 placeholders retain a value-derived + encoded size and SHA-256 digest; a one-byte credential is recoverable by 256 + guesses even when the literal byte is absent. Therefore **no credential byte + may reach `Entry.render/2` at all**. Keyword-key placeholdering protects only + the opaque 128-bit token while model options cross core before the sender + exists; MFA and process exclusion protect the credential. **The proof is three cases, and the first one is the one that would have caught the old design.** A trace session is configured to name - **`:gen_tcp`** explicitly, alongside `ProviderBridge` and `ProviderCodec`, + **`:gen_tcp`** explicitly, alongside `ProviderBridge` — including its private + `sink_loop/1` — and `ProviderCodec`, and a real invocation runs with a **one-byte canary** as the credential. The - case asserts the tracer receives **no raw trace message from the sender - process at all** — not for `:gen_tcp.send/2`, not for any function — while a - non-excluded control process performing the same `:gen_tcp.send/2` in the - same session **does** produce one, so the case cannot pass by tracing - nothing. The canary appears nowhere in any captured message or entry. - - The second is the default configuration: no module naming, and no entry, no - raw message and no credential byte anywhere — the adapter is in no namespace - wildcard, because `modules/1` expands `:loopex` and `:loopex_protocol` - through `:application.get_key(application, :modules)` and + case backlogs the Trace process, captures the sender's expected token-free + start entry and asserts its arguments contain only `sender_ref`, callback + owner, guardian and capability — no token, registry handle, socket, nonce, + request or credential. It observes only non-secret authorization, adoption + and exact `:begin_bootstrap` tuple before the exclusion. After the exclusion + acknowledgement, the tracer receives **no further raw message from that + sender pid** — including none for `:gen_tcp.send/2` — while a non-excluded + control process performing the same `:gen_tcp.send/2` in the same session + **does** produce one, so the post-exclusion negative cannot pass by tracing + nothing. A pre-clear bootstrap call held in the backlog is consumed before + the acknowledgement, no raw message arrives after it, and the sender has no + pending-call key then or after exit. During the real invocation the case captures every IO request and proves none + carries the credential. After token delivery it separately sends a clearly + non-secret IO canary through the sender's installed group leader. That proves + the sink path is live, both sender and sink pids have no inherited trace flags, + neither produces a raw trace message for the IO canary, and no host Logger + output receives it. Outside the one permitted custody reply, the credential + canary appears in no captured raw trace message, rendered entry or IO request. + + The second is the default configuration: no module naming, and no entry or + raw message names any of the three bridge MFAs, while no credential byte + appears in any captured raw trace message, rendered entry or IO request + outside the one permitted custody reply. The token may traverse + core in model options before a sender exists; the existing structured + redaction is what keeps that credential-adjacent value out of rendered + entries. The adapter itself is in no namespace wildcard, because `modules/1` + expands `:loopex` and `:loopex_protocol` through + `:application.get_key(application, :modules)` and `Loopex.LLM.ReqLLM.ProviderBridge` lives in `loopex_llm_reqllm`. The third is the ordering: under inherited `set_on_spawn` tracing, the - sender's entry call proves its closure contains only the tracing capability - and guardian pid. `exclude_self/2` is asserted to return **before** the - guardian sends the one message carrying the token and registry handle, and a + sender's entry call proves its exact four token-free arguments. The callback + waits for adoption completion; the parked sender does nothing until exact + child readiness supplies its bound `:begin_bootstrap` tuple carrying the + retained deadline. `exclude_self/2` and its delivery marker complete before + the sender spawns the sink; the sink is proved to inherit no trace flags, and + both exclusions plus sink installation and the exact successful + `{:bootstrap_result, sender_ref, sender_pid, guardian_pid, :ok}` finish + **before** the guardian sends the bound + `:credential_context` tuple carrying the token, registry handle, accepted + socket and invocation nonce. A session started concurrently with exclusion is asserted to produce no credential-adjacent message from the sender in either order. + The same ordering case injects `:begin_bootstrap`, `:bootstrap_result`, + credential context, every phase result and every continuation with a wrong + `sender_ref`, guardian pid or sender pid, one field at a time; phase messages + also carry a wrong phase, and continuations carry a changed deadline. It + injects malformed current-binding `:begin_bootstrap` and credential-context + tuples, a malformed current-binding bootstrap result, a proper + `{:error, :unavailable}` bootstrap result, a malformed current-phase result, + every closed atom from the wrong producer and every producer-permitted error + result. The parked sender never clears on a malformed or mismatched release, + bootstrap error never releases credential context, and a phase error never + receives a continuation. No route, custody call, frame write or invocation + helper occurs after a mismatch or error. The unchanged deadline performs + cleanup where the tuple is stale; a matching malformed or + producer-forbidden result fails immediately as `:unavailable`. Replaying + every once-valid tuple after its phase has advanced is likewise inert. This + makes the private messages part of the operation binding rather than + descriptive tags. + + The managed liveness half delays the delivery marker and therefore the Trace + acknowledgement beyond 5,000 ms under a + later guardian deadline. Releasing it after that point still succeeds, which + rules out a hidden default `GenServer.call/2` timeout; holding it through the + guardian deadline yields `:timeout`. In both cases an ordinary coordinator + operation through `Control` completes while Trace is delayed and again after + the sender is killed, proving the asynchronous handshake did not wedge the + runtime. A companion Direct pair backlogs both named-session and legacy + traffic under the request's pre-launch absolute deadline. Releasing the + markers after 5,000 ms but before that instant succeeds; holding them through + it makes the raw guardian kill and reap sender and sink and report `:timeout`. + Both observe every required delivery marker before token delivery and return + Trace pending-call state, monitors and process populations to baseline. + Four more cover what the capability is for, and each names the surface it reads and the two answers that must differ on it. **A tracer restart reconstructs the exclusion for a new session.** Surface: - the tracer's own message stream and the old session's destruction. Killing - the tracer destroys its trace sessions and removes their process flags; the - test first proves the old session is gone. The supervisor restarts the + the tracer's own message stream, `:trace.session_info(:all)` and the weak old + identity. Trace is the sole process holding the full strong handle; the test + retains only `{name, id}`, kills Trace and first proves that weak identity is + absent. The supervisor restarts the tracer, a new session starts, and a long-lived sender retained in `Control` from before the restart is asserted to produce **no** message under the new session while a - non-excluded control process in the same session produces one. A design - holding a tracer pid in options fails the first half; a case without the + non-excluded control process in the same session produces one. That production + fixture proves the ordinary absent path: the sole strong owner died, so + membership is absent and destroy is skipped. A separate fault-injection + fixture deliberately retains one forbidden extra strong handle outside + `Control` — a state production must never create — so the exact old weak + identity remains present and destroy returns `true`. Releasing that fixture + races destroy: `false` or `:badarg` is accepted only when a follow-up + all-session query proves the exact weak identity absent. Both fixtures confirm + absence before create and never give Control the strong handle. A design holding a tracer pid in options fails the first half; a case without the control process could pass by tracing nothing. - **A `Control` restart destroys the old tracing state and its downstream - senders together.** Surface: process monitors and the tracer's session list. - The case holds a sender after exclusion but before giving it the token, kills - `Control`, and asserts that the old trace session and sender both terminate - and that no credential-bearing message was ever sent. After the runtime tree - recovers, a new trace session and new sender establish a fresh exclusion and - complete normally. The case does not assert that a destroyed session's - process flags persist. + **A `Control` restart destroys the old tracing state and its managed provider + children together.** Surface: process monitors and the tracer's session list. + The adapter integration case pauses the sender after the custody reply, while + it holds a one-byte canary and before it writes the frame, then kills + `Control`. Both guardian and sender are direct temporary children of the + existing owner-workers supervisor. Their monitors must deliver `DOWN` before + the replacement tracer pid appears, proving owner-group teardown supplied the + barrier rather than process scheduling luck. The old session and sender both + terminate and the tracer captures no raw message carrying the canary. After + the runtime tree recovers, a new trace session and new sender establish a + fresh exclusion and complete normally. The case does not assert that a + destroyed session's process flags persist. + + Companion cases assert `Process.info(sender, :trap_exit) == + {:trap_exit, false}`, then kill the managed guardian abnormally while its linked sender is held in + the registry call and in the custody call. A third holds the sender inside + group-leader-sink spawn or installation after the link and guardian-monitor + acknowledgement, then kills the guardian before its deadline. Link + propagation to that non-trapping sender ends the sender and sink even though the sender has not reached + its receive loop. Control's excluded-pid/MFA state and Trace pending-call and + monitor state return to baseline. No token, registry handle, channel context, + credential frame or raw trace canary is delivered, and no sender or sink + remains. This preserves ADR 0019's abrupt-guardian cleanup even though the two + processes are direct siblings under `owner_workers`. + A normal-cleanup companion proves the guardian explicitly stops and awaits the + sender, since a normal linked exit alone would leave it alive. **The set returns to baseline and restores selected patterns.** Surface: `Control`'s excluded-pid set and the live session's selected MFA pattern, read @@ -644,9 +1280,11 @@ boundary, not an absolute: asserted non-empty while a sender is alive and empty after it exits. While excluded, the named MFA produces no raw message; after the last owner exits, the same live session again traces it according to its original selection. A - second sender keeps it excluded until that sender exits. Those observations - separate working monitors and reference counts from a set that was never - populated or a clear that permanently overwrote the host's trace pattern. + second sender keeps it excluded until that sender exits. A paired session + that did not select the MFA remains clear after the last sender exits. Those + observations separate working monitors and reference counts from a set that + was never populated, a global restore, or a clear that permanently overwrote + the host's trace pattern. **It fails closed, on every way the capability can be missing.** Surface: the invocation's own result, plus the child's record of what it received. With @@ -661,39 +1299,68 @@ boundary, not an absolute: paired with an ordinary success from a complete, live configuration, and every path asserts that the child receives no credential before exclusion is confirmed. + + The bind witness uses two live runtimes. Binding a fresh handle to runtime A + succeeds and the same bind is idempotent. Binding that handle to runtime B + refuses `:capability_already_bound` before runtime use, child creation, token + routing or custody access; runtime A remains the stored binding and a later A + invocation succeeds. The CLI, app-server and daemon composition suites each + assert the same exact-runtime behavior at their own owner boundary. - Everywhere else the earlier absolutes stand unchanged: not in guardian state, not in an exit reason, not in a crash report, not in an IO request, not in a file, not in the environment, not in argv, and in no durable or public plane. **When it is resolved.** Exactly once per invocation, inside the sender -process, between the child's `ready` frame and the credential frame — step 5 +process, between the child's `ready` frame and the credential frame — step 9 above and nowhere else. A resolved value is never cached, never reused for a second invocation, and never returned to the guardian. -**Rotation.** Per invocation, by construction: the custody process may answer -different bytes for the same token on a later call, and no layer holds a -previous answer to contradict it. The host may also rotate by pointing the -token's registry row at a new custody process, which the next invocation -follows and an in-flight one does not. A rotation that happens while an invocation -is in flight does not reach that invocation, which has already resolved; it -reaches the next one. Nothing is invalidated and no invocation is restarted. - -**The guardian enforces the deadline, not the resolver.** Resolution is -bounded by the invocation's existing deadline and by nothing else; this -decision adds no second clock and, after the maintainer's decision of -2026-09-20, it does not ask the resolver to honour one either. The callback -takes no deadline argument. The guardian already owns the invocation deadline -and already supervises the sender, so it bounds the whole resolution — the -registry lookup, the call, and the wait for a reply — and kills the sender -when the instant is reached, reporting `:timeout`. +**Rotation.** Per resolution, by construction: the custody process may answer +different bytes for the same token on any later custody reply, and no layer +holds a previous answer to contradict it. Repointing the token's registry row +linearizes at the sender's registry lookup: an invocation whose lookup has not +occurred may follow the new row even if its child is already running; one whose +lookup and custody reply completed keeps that reply for its one frame. Rotating +inside a custody process linearizes at that process's reply. Nothing is +invalidated and no invocation is restarted. + +**The guardian owns the deadline outcome; the resolver receives no clock.** +Resolution is bounded by the invocation's existing absolute deadline and by +nothing else; this decision adds no second clock and, after the maintainer's +decision of 2026-09-20, it does not ask the resolver to honour one. The custody +callback takes no deadline argument. Managed-start time consumes that deadline +and no start or ownership transfer resets it. A non-answering managed start +remains a Core owner-group liveness failure while transfer is incomplete. Once +Core has registered the guardian, the sender has been adopted and the guardian +receives its initialize message, the guardian checks the same instant +immediately. It then bounds provider launch and readiness, sender release, the +registry lookup, the custody call, the credential-frame write and the wait for +each result, killing the sender when the instant is reached and reporting +`:timeout` only after its own monotonic clock confirms expiry. + +The sender is the enforcement participant at the operation boundary. The exact +`:begin_bootstrap` tuple carries the deadline; the sender retains it and checks +it on receipt and immediately before exclusion and sink installation. It +rechecks the same instant when it receives credential context and immediately +before registry routing. Every phase continuation carries that unchanged +instant, and the sender checks it on receipt and again immediately before the +one operation the continuation permits: custody resolution, credential-frame +write, or normal exit from the already non-secret final wait. A valid message queued before the deadline but +consumed at or after it therefore loses. The sender starts no next operation, +scrubs any custody bytes it still holds and exits with the fixed non-secret +`:credential_deadline` reason. That reason is not proof of time: the guardian +still consults its own clock before classifying `:timeout`, and starts the +generic invocation helper only after exact normal sender `DOWN` and a final +pre-deadline check. An earlier draft passed an absolute monotonic instant to the resolver and relied on it to answer in time. That is withdrawn: it made every host's resolver responsible for a safety property the adapter must have whatever the host wrote, and a resolver that simply blocked would have hung the invocation -past its deadline. Enforcement belongs to the process that can act on it by -killing something. The resolver's only obligation is to answer or not. +past its deadline. Enforcement belongs to the guardian that can kill the +blocked sender and to the sender that can refuse a late release before crossing +a phase boundary. The resolver's only obligation is to answer or not. **The closed reason set, complete.** Every way resolution can fail maps to one of seven atoms, and the set is closed in both directions: nothing else is @@ -706,53 +1373,83 @@ produced, and nothing else is accepted. | `:missing` | A custody process | It has no credential for this token | | `:expired` | A custody process | It has one and considers it no longer valid | | `:oversized` | The sender | A successful reply whose bytes fall outside 1 to 65,536 | -| `:unavailable` | The tracing capability, registry or a custody process | A capability or `Control` that is immediately unreachable, a missing registry row, a gone registry, a dead custody process, a custody process that answers `:unavailable`, or **a successful reply that is malformed** — not `{:ok, %{credential: binary}}`, including a bare binary where the keyed map is required — because a reply the sender cannot read, or reads in a shape the redaction pass does not protect, is not a credential it can send | -| `:timeout` | The guardian | Exclusion or resolution had not completed when the invocation deadline was reached | +| `:unavailable` | The managed starter, credential sender or guardian, tracing capability, direct exclusion, registry, custody process or frame writer | Immediate guardian start, registration, authorization, sender start or adoption refusal; an unexpected sender `DOWN` before expiry, including normal exit outside the final-exit state; immediate sink spawn or installation failure before token delivery; a capability or `Control` immediately unreachable; a still-live Direct session that cannot be cleared or verified; a missing registry row, gone registry, dead custody process or custody `:unavailable`; a malformed successful reply; or an immediate codec/socket write failure. None falls back to raw spawning or another transport. A start that never answers remains a Core owner-group liveness failure outside this private set | +| `:timeout` | The guardian | Managed mode's unchanged deadline was already elapsed at initialize, reached during provider launch/readiness, sender release, sink installation, exclusion, registry lookup, custody resolution or frame write, or confirmed when any sender `DOWN` is consumed; or Direct mode's pre-launch absolute instant was reached during inherited-session clearing or a later step | An earlier draft left the first two unnamed and folded a malformed successful reply nowhere at all, which meant three real failures had no atom to carry. Anything returned outside this set is treated as `:unavailable`, because a host-authored term is exactly where a secret could be smuggled into a reason. -All seven atoms carry no content, so they are safe in a message, an exit -reason and a bounded diagnostic. - -**They are internal diagnostic classes, not a new public result shape.** The -seven live inside the adapter and in what the guardian records; the value -`complete/3` returns to the coordinator keeps the **existing `Loopex.Model` -refusal shape**, unchanged by this decision. A host that pattern-matches on -the adapter's result today matches the same shapes afterwards, and the atom is -what the bounded non-secret diagnostic says happened rather than a second -return contract to learn. Widening the callback's result would be a change to -an accepted port, which this decision explicitly does not make. - -**What the sender reports.** `:ok` or `{:error, reason}` from that same closed -set, never a bare `:error`. The guardian has to distinguish a custody process -that refused from one that never answered — they are different operational -faults and ADR 0029's bounded status has to say which happened — and it can, -because a refusal arrives as one of the six atoms produced below the guardian -— `:no_token` and `:invalid_token` from the adapter, `:missing` and -`:expired` from a custody process, `:oversized` from the sender, and -`:unavailable` from the tracing capability, registry or custody — while a -silence is the -guardian's own `:timeout`, the seventh. The reported reason is never the resolved value, -the token, or a host-authored string. - -**Failures.** Each is a refusal with a bounded non-secret reason, and each +The set is also producer-scoped. The registry may originate only +`:unavailable`; every other registry reply, including another in-set atom, is +normalized to `:unavailable`. Custody may originate only `:missing`, +`:expired`, or `:unavailable`; if it returns another in-set atom such as +`:timeout`, `:oversized`, `:no_token`, or `:invalid_token`, the sender +normalizes it to `:unavailable`. Those atoms remain reserved for the guardian, +sender bound check, or adapter preflight named in the table. +All seven atoms carry no content. They form a private adapter classification +set and remain observable in adapter tests; only post-spawn classes travel the +sender-to-guardian protocol. They are not put in an exit reason, +ADR 0029 child terminal, public event or operator diagnostic. + +**They are private adapter classes, not a new result or diagnostic shape.** +`ProviderBridge.complete` maps preflight `:no_token` and `:invalid_token` +before it spawns anything; the guardian maps the post-spawn classes. Every one +becomes the existing generic `Loopex.Model` refusal; +`complete/3` keeps that released shape unchanged. ADR 0029's child terminal is +also unchanged: credential resolution precedes the frame and may precede a +child terminal entirely, so this decision does not pretend its `{stage, class}` +allowlist carries these atoms. Tests observe the private guardian result under +the adapter harness before the generic mapping. Widening either public result +or accepted diagnostic would require a separate decision. + +**What the private adapter path reports.** It returns `:ok` or +`{:error, reason}` from that same closed set, never a bare `:error`. Preflight +handles `:no_token` and `:invalid_token` before spawning. An immediate managed +gate refusal reports `:unavailable`; a never-answering start remains Core's +liveness failure. After spawn, the sender +can report `:missing` or `:expired` from custody, `:oversized` from its bound +check, and `:unavailable` from immediate exclusion or Direct clearing, +registry/custody refusal, malformed replies or immediate frame-write failure. +The guardian also reports `:unavailable` for any unexpected sender `DOWN` +before the deadline; it never forwards the process reason. +The guardian owns `:timeout`: in managed mode for an elapsed initialize or +unfinished provider readiness, sender release, exclusion, registry lookup, +custody resolution or frame write; in Direct mode for inherited-session clear +or any later step that crosses the request's pre-launch absolute instant. This accounting lets the guardian +distinguish a refusal from silence without accepting a host-authored reason. +No result carries the resolved value, token or a host-authored string. + +**Failures.** Each has a bounded non-secret private reason before the guardian +maps it to the existing generic model refusal, and each leaves no retained copy of anything the resolver may have produced: | Condition | Outcome | | --- | --- | | No `:credential_token` in the configuration | `:no_token`, refused before the namespace is created and before any child is spawned | -| Malformed token — anything that is not a `%CredentialToken{}` struct with a 16-byte `id`, a bare binary included | `:invalid_token`, refused before any lookup and before any child is spawned. The struct is what makes this decidable: a credential is a bare binary, and no content test separates one from a token | -| A token is configured without a well-formed capability bound to the returned runtime | Refused at composition; no invocation or child starts | +| Malformed token — anything that is not the exact `%CredentialToken{}` map with only `__struct__` and a 16-byte `id`, a bare binary or an extra-key struct-shaped map included | `:invalid_token`, refused before any lookup and before any child is spawned. The exact struct is what makes this decidable: a credential is a bare binary, and no content test separates one from a token | +| A token is configured without an exact `%CredentialRegistry.Handle{}` map that passes field validation, including a forged extra key | Refused at composition; no invocation, namespace or child starts | +| A token is configured without an exact capability handle bound to the returned runtime, or a handle already bound to another runtime | Refused at composition; a cross-runtime bind returns `:capability_already_bound`, preserves the original binding, and starts no invocation or child and routes no token | +| The managed path refuses guardian start, Core registration, guardian authorization, sender start or sender adoption | `:unavailable`; partial children are stopped in reverse order, no provider action starts, and the adapter never falls back to raw spawning. A start that never answers is instead the owner-group/runtime liveness failure described above, outside the seven adapter atoms | +| The absolute invocation deadline has elapsed when the adopted pair is initialized, or expires before exact provider readiness | The guardian performs reverse cleanup and reports `{:error, :timeout}`; the parked sender receives no `begin_bootstrap`, token, registry handle, socket or nonce | +| The sender returns exact `{:bootstrap_result, sender_ref, sender_pid, guardian_pid, {:error, :unavailable}}` | `:unavailable`; the guardian sends no credential context and tears down the provider tree, sender and sink | +| A bootstrap or phase tuple has a wrong or stale reference, pid, phase or deadline | It is ignored and cannot advance the current operation; the unchanged deadline eventually performs cleanup. A matching current-binding result with a malformed shape or producer-forbidden atom is immediate `:unavailable` | +| A producer returns an allowed phase error | The sender reports that error in the exact bound phase-result tuple; the guardian sends no continuation and maps the normalized closed atom. No later custody call, frame write or invocation helper starts | +| The sender consumes `:begin_bootstrap`, credential context or any phase continuation at or after the retained instant | It starts no newly permitted operation, scrubs any custody bytes and exits with fixed non-secret reason `:credential_deadline`; the guardian reports `:timeout` only after its own clock confirms expiry. At the custody-to-frame cut no credential frame is written; at the final cut no invocation helper starts | +| The guardian observes any sender `DOWN` other than the exact normal `DOWN` expected in final-exit state | Before the deadline it reports `:unavailable`; at or after the deadline it reports `:timeout` only after checking its own clock. It tears down the sink and provider tree, starts no invocation helper and never exposes the sender's raw reason | | The capability or `Control` is immediately unreachable when the sender asks for exclusion | `:unavailable`, before the guardian sends the token or registry handle and before custody is reached | | Exclusion remains unanswered when the invocation deadline is reached | The guardian kills the sender and reports `{:error, :timeout}`, before sending the token or registry handle | -| A successful custody reply that is malformed — not `{:ok, %{credential: binary}}`, a bare binary included | `:unavailable`; a bare binary is refused rather than accepted, because accepting it would carry bytes in a shape the redaction pass leaves verbatim below 65 bytes | -| The registry holds no row for the token, the registry is gone, or the custody process is dead | `:unavailable`. The host recomposes; nothing is reconstructed, because the registry holds no bytes to reconstruct from | -| Custody answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}`; the invocation fails through ADR 0019's existing credential-send failure path, the guard tears the child down, and the atom becomes the bounded non-secret status ADR 0029 fixes | -| Custody answers `{:error, :unavailable}`, or anything outside the closed set | The same path, reported as `:unavailable` | -| Resolution has not completed when the guardian's invocation deadline is reached | The **guardian** kills the sender and reports `{:error, :timeout}`, distinct from every refusal; the sender's stack goes with it. A custody process that simply blocks cannot hang the invocation, because nothing depends on it noticing the time | +| Direct mode cannot clear or verify a still-live inherited named or legacy trace session | `:unavailable`, before token delivery. A session confirmed destroyed during the operation is absent and does not cause refusal | +| Direct mode reaches its pre-launch absolute deadline while clearing an inherited session, resolving custody or writing the frame | The raw guardian kills and reaps its linked-and-monitored sender and sink and reports `:timeout`; no later frame can be written | +| The Direct guardian exits abnormally or is killed while its sender is blocked in clear, custody or frame write | The link kills the non-trapping sender, the sender's link/monitor relation ends its sink, and no late frame is written. Normal guardian cleanup instead stops and awaits both before returning | +| A successful custody reply that is malformed — not `{:ok, %{credential: binary}}` with exactly that one map key, a bare binary or extra-key success map included | `:unavailable`; malformed content is refused rather than widening the one exact byte-bearing dataflow shape. Trace exclusion, not that shape, protects the bytes | +| The registry holds no row for the token, a valid handle's process is gone, the route returns anything except `{:error, :unavailable}` or one exact valid `{:ok, custody_ref}` — including another in-set error atom, an arbitrary term, or a malformed or extra-key successful reference — or the custody process is dead | `:unavailable`. The host recomposes; nothing is reconstructed, because the registry holds no bytes to reconstruct from | +| Custody answers `{:error, :missing}` or `{:error, :expired}` | The sender reports `{:error, that_atom}` privately; the guardian maps it to ADR 0019's existing generic credential-send failure and tears the child down. No ADR 0029 terminal or public diagnostic gains the atom | +| Custody answers `{:error, :unavailable}`, anything outside the closed set, or an in-set atom reserved for another producer (`:timeout`, `:oversized`, `:no_token`, or `:invalid_token`) | The same path, reported as `:unavailable` | +| Registry lookup or custody resolution has not completed when the guardian's invocation deadline is reached | The **guardian** kills the sender and reports `{:error, :timeout}`, distinct from every refusal; the sender's stack goes with it. A registry or custody process that simply blocks cannot hang the invocation, because nothing depends on it noticing the time | | Resolved value outside 1 to 65,536 bytes | Refused in the sender before the frame is written, exactly as the size check refuses today, reported as `{:error, :oversized}` | +| `ProviderCodec.send/3` or the socket fails immediately while writing the credential frame | The sender scrubs its local reference, reports `{:error, :unavailable}` and the guardian tears the child down; no raw socket or codec reason crosses the boundary | +| The credential-frame write remains pending at the invocation deadline | The guardian kills the sender and reports `{:error, :timeout}`; the one deadline covers the write as well as exclusion and resolution | | Two resolutions in flight at once | Independent **successes**. Each invocation has its own sender and resolves for itself; the adapter serialises nothing and shares nothing between them, and two answers for the same token may differ. Concurrency is not a refusal condition, and a custody process that refused concurrent callers would reintroduce exactly the serialisation this decision exists to remove | No failure is retried inside the adapter. Whether to attempt again is the @@ -760,16 +1457,43 @@ coordinator's durable decision under ADR 0018, unchanged. ### Scrub points -- **In the sender.** The sender is spawned with a token-free closure containing - only the tracing capability and the guardian pid. It installs its group - leader sink, calls `exclude_self/2`, and acknowledges the completed exclusion. - Only then does the guardian send it the token and registry handle in one - message. It looks the token up in that registry, calls the custody process it - names, receives the one permitted credential-bearing reply, validates the - size bound, writes the frame itself and reports `:ok` or `{:error, reason}` - from the closed set to the guardian, which supervises the entire sequence - against the invocation deadline. Neither the spawn closure nor any message - sent before exclusion holds the token, registry handle or credential. In the +- **In the sender.** The sender is started with a token-free argument containing + only `sender_ref`, the callback-owner pid, guardian pid and tracing + capability. It completes exact authorization and guardian adoption, drops its + callback monitor and parks. Exact provider readiness delivers the bound + `:begin_bootstrap` tuple carrying the retained absolute deadline; only then + does it call `exclude_self/2` and drain the + delivery barrier. From that untraced process it then + spawns and installs its group-leader sink; the sink inherits no trace flags, + and the sender verifies both itself and the sink clear before returning the + exact `{:bootstrap_result, sender_ref, sender_pid, guardian_pid, :ok}` tuple. + Immediate exclusion or sink failure instead returns the same tuple with + `{:error, :unavailable}`; a malformed result with the current binding fails + closed, while a wrong or stale binding cannot release anything. Only exact + success before the deadline lets the guardian send the bound + `:credential_context` tuple with the token, registry handle, accepted socket + and invocation nonce. It looks the token up in that registry and parks until + the guardian accepts its exact non-secret `:registry` phase result and replies + with the exact continuation carrying the unchanged deadline. The sender + rechecks that instant on receipt and immediately before it calls the custody + process, receives the + one permitted credential-bearing reply, validates the size bound and parks + again; the `:custody` result/continuation exchange carries no bytes. It + rechecks the unchanged instant on receipt and immediately before writing the + frame. On successful return it drops every credential-bearing logical + reference and tail-calls a non-secret final wait, which sends the exact + `:credential_frame` phase result and parks. Only the matching final + continuation permits normal sender exit. The guardian consumes that exact + normal sender monitor `DOWN`, rechecks + the deadline and only then starts the generic invocation-frame helper. An + immediate refusal sends the producer-scoped `{:error, reason}` in the exact + phase-result tuple; no error receives a continuation. If a continuation is + consumed at or after the instant, the sender starts no next operation, scrubs + any custody bytes it still holds and exits with the fixed non-secret + `:credential_deadline` reason. Neither the initial argument nor any + sender message before exclusion holds the token, registry handle, channel + context or credential. The guardian's post-adoption initialize message may + hold the opaque token and registry handle, but never credential bytes. In the parent the value exists in the custody process and, for the duration of one send, in this process's own mailbox and stack, and nowhere else — no guardian state, no exit reason and no crash report can @@ -777,10 +1501,10 @@ coordinator's durable decision under ADR 0018, unchanged. - **In the parent's environment.** The adapter performs no *credential* environment read by any route. That is the property this decision owns, and it is narrower than "no environment read at all" on purpose. - `Loopex.LLM.ReqLLM.credential_variable/0` remains as the one name the *host* - reads when it composes a runtime — the reference CLI at start, and the - real-provider lane when it names the variable in its own failure message — - and the host deletes that name once it has read it. `ProviderBridge`, which + `Loopex.LLM.ReqLLM.credential_variable/0` remains the common configured name + that the reference CLI, app-server host, daemon and direct real-provider + caller read and delete at their own composition boundary; those hosts may + also reuse the name in failure text. `ProviderBridge`, which holds the sender and the whole credential path, reads no environment variable at all. @@ -825,9 +1549,140 @@ coordinator's durable decision under ADR 0018, unchanged. ### Proofs +The new managed sender gets its own crash-report proof rather than borrowing +the provider child's cases below. The case pauses the sender after the custody +reply and forces raise, exit and kill cuts. It captures Logger output, the +Task/supervisor report and guardian result, and refutes the canary in the +initial child argument, exception/exit reason, stack, message and metadata. +For each cut, a sender `DOWN` consumed before the absolute instant maps exactly +to `:unavailable`, starts no invocation helper, tears down the sink and provider +tree, and returns their populations plus trace membership to the sampled +baselines. Paired cases hold the same `DOWN` until the instant has passed; the +guardian checks its own clock and reports `:timeout`, again with no invocation +helper and the same baselines. No case exposes the raw sender reason. A +companion assertion fixes the guardian's initial argument at exactly +`{guardian_ref, callback_owner_pid, stop_reference}`; the sender's contains only +`sender_ref`, callback owner, guardian and capability. Credential bytes arrive only after adoption, +readiness and exclusion. Companion cases force each immediate managed-gate +failure, immediate group-leader-sink installation failure, a blocked sink +installation through the guardian deadline, a still-live Direct session whose +clear/verification fails, immediate frame write failure and a blocked frame +write at the guardian deadline. They assert the closed classes above and no +token delivery before exclusion. A Direct session destroyed during clear is +the paired success case. + +Direct lifetime evidence holds the raw sender separately at inherited-session +clear, custody resolution and frame write. At each cut, abnormal guardian exit +and `:kill` promptly reap sender and sink, write no late frame and return process +and Trace bookkeeping to baseline; normal cleanup explicitly stops and awaits +both. The paired deadline case releases a clear after 5,000 ms but before the +request's pre-launch absolute instant and succeeds, then holds the same clear +through that instant and observes `:timeout` with the same baselines. + +Managed-start evidence exercises the two gates separately. First it suspends +the exact `owner_workers` before the guardian materializes, ends the calling +scope, then resumes the supervisor. A late guardian observes callback-owner +`DOWN` and exits inert; guardian, sender, start-proxy, receiver, generic +phase-send-helper, sink, Port, carrier, guard and provider-BEAM populations all +return to baseline. A second case pauses the guardian's start +acknowledgement before Core registration and kills the callback; the guardian +exits inert, with no retainer registration or provider action. A third pauses +the exact guardian-authorization acknowledgement after retainer-monitor +installation and proves the callback cannot start a sender or send initialize +until that acknowledgement arrives. Separate sender +cases pause before materialization and after start acknowledgement but before +guardian adoption, and after the guardian's adoption reply but before the +sender's adoption-complete acknowledgement to the callback, then end the scope +or kill the guardian. A late or unadopted sender exits inert; initialize is not +sent before adoption completion, and the registered guardian is stopped through +Core's exact stop protocol. No case produces a `:begin_bootstrap` tuple, exclusion, +sink, route, custody or frame work. + +Proxy evidence forces supervised-start refusal, a caught starter exit, proxy +result before child acknowledgement, child acknowledgement before proxy result, +and the three legal cross-sender orders around proxy termination: +child acknowledgement then result then proxy `DOWN`; result then child +acknowledgement then proxy `DOWN`; and result then proxy `DOWN` then child +acknowledgement. Same-sender ordering forbids proxy `DOWN` before its result. +Only matching success plus matching child acknowledgement proceeds; refusal or +proxy loss without a result maps to `:unavailable`, reverse-cleans the child, +and no second proxy starts. Separate guardian and sender cases kill the child +after each possible first disclosure and before ownership transfer; the +callback's child monitor wins `:unavailable`, so neither wait can hang before +the invocation deadline is active. Population sampling asserts at most one +proxy live, and no proxy remains before Core registration or sender +authorization. + +The paired authorized case proves ordering at each ownership cut: guardian +authorization follows `ProviderLifetime.register/2` and retainer-monitor +installation; sender authorization finishes only after guardian link, exact +adoption and sender-monitor acknowledgement. It then lets the callback return +its normal model result. The guardian remains retained through ADR 0019's +post-result cleanup wait and sender/provider cleanup remains governed by Core's +retainer path. Ordinary callback completion therefore cannot mimic +pre-authorization cancellation. Immediate refusal at any gate returns +`:unavailable`, reverses partial children and never falls back to raw spawn; a +non-answering start remains the owner-group liveness class. + +After both transfers, one case holds the sender parked and kills the guardian; +another refuses provider bootstrap before exact readiness. Both prove no +`:begin_bootstrap` tuple, exclusion, sink, token, registry, socket, nonce, custody or +frame and return every process population to baseline. Post-readiness cases +block sink installation until the unchanged absolute deadline and kill the +guardian abnormally. The first reports `:timeout`; the second promptly reaps +sender and sink and restores trace baselines. Releasing the same held operation +after 5,000 ms but before the real deadline succeeds, proving that neither +managed setup nor a hidden call timeout reset or shortened the one clock. +For provider readiness, the exact `:bootstrap_result` and every credential phase +result, paired guardian-side cases queue the bound success immediately before +the absolute instant and force both result/timer mailbox orders. A result +consumed before the instant advances once; the same result consumed at or after +it is cleanup-only and the guardian reports `:timeout`. A queued timer never +defeats a result the guardian validated before the instant, and a queued result +never extends the deadline. + +Separate sender-side pairs queue valid `:begin_bootstrap`, credential context +and each exact phase continuation before the instant. One suspends the sender +before receipt; the other lets it pass the receipt-time check and suspends it at +a test barrier immediately before the permitted operation. Both resume at or +after the instant. The sender therefore starts no exclusion, sink, registry +lookup, custody call, credential-frame write or normal final exit transition +after expiry. The `:begin_bootstrap` pre-operation form runs once immediately +before exclusion and again immediately before sink installation. In the +custody-to-frame pair it already holds the one permitted +credential-bearing reply; the pre-write suspension proves the second check +scrubs those bytes, writes no frame and exits with the fixed non-secret +`:credential_deadline` reason. At the final-continuation +cut the credential frame may already exist, but the sender is already in its +non-secret final wait. The case refutes the canary in its state, mailbox, +process dictionary and forced-crash material before the continuation, then +proves the sender's deadline exit and the guardian's own clock check prevent +the invocation helper from starting. +Every case proves that the unchanged deadline, rather than send time, governs +acceptance and that the guardian reports `:timeout` only after its own clock +confirms expiry. Each awaits cleanup and returns the sender, sink, generic +phase-send-helper and provider-tree populations plus trace membership to their +sampled baselines. + +Sink lifetime has a separate two-way witness. Ordinary sender success produces +the sender-monitor `DOWN` and returns the sink population to baseline; abnormal +or kill sender exit reaches the non-trapping sink through its link and does so +promptly. This prevents the false inference that a normal linked exit alone +would stop the sink. + +The guardian receives the valid token and registry handle in its initialize +message after its token-free supervised start; the accepted socket and nonce +remain later channel context. A case crashes it immediately after initialize, +before readiness or channel context, and captures the complete +Task/supervisor report and the owner-observed `EXIT`, and refutes fixed token +and registry-incarnation canaries in the initial argument, exception or exit +reason, stack, queued and last messages, state, metadata and log. The crash +trigger carries a fixed non-secret reason. That proof prevents the supervised +child specification from being safe while the later message path is not. + Every case below exists today in `apps/loopex_llm_reqllm/test/credential_plane_test.exs`. Each is re-pointed at -the per-invocation token — the module's `setup` and the two rotation cases +per-invocation token resolution through the composition-bound token — the module's `setup` and the two rotation cases stop writing the process-wide variable, and each fixture composes its own custody process and registry row — and each must hold with its assertion unchanged in meaning: @@ -845,6 +1700,16 @@ custody process and registry row — and each must hold with its assertion uncha | Child Logger forms and metadata | `ordinary and split actual child Logger messages cannot expose the credential`, `all actual child Logger message forms and metadata stay private`, `repeated credential bytes in actual child metadata cannot reach host channels`, `credential-bearing child metadata keys cannot reach host channels` | | Crash reports | `a provider request adapter that throws cannot put the credential in a stream-server crash report`, `a provider request adapter that exits cannot put the credential in a stream-server crash report`, `an actual child report containing its own request credential stays private`, `an actual child StreamServer termination cannot forward its credential` | +The launch-boundary witness in +`apps/loopex_llm_reqllm/test/provider_startup_boundaries_test.exs` is re-pointed +more deeply than replacing a fixture. Its observer counts custody-resolution +requests, because observing `System.get_env` after this change would make both +branches report zero and prove nothing. A child that reaches exact readiness +causes exactly one custody resolution. An actual child crash before readiness +causes zero resolutions, zero provider dispatches and no canary in diagnostics. +The case kills the real pre-entry process rather than asking a fake to return an +error. + Two of those cases also carry the child-environment witness, and it survives the re-pointing unchanged: the version-refusal case at `credential_plane_test.exs:117` and the bootstrap-refusal case at `:567` each @@ -877,7 +1742,17 @@ Six proof groups are new: reads the environment for a credential**. "During" is observed from inside the call, at the point the child reports readiness. The case composes the runtime the way a reference host does, with the variable set, and asserts - that composition returns having deleted it. + that composition returns having deleted it. Each host suite traces only the + exact composition owner pid at call level for the chosen + `System.get_env/1` call whose argument is + `Loopex.LLM.ReqLLM.credential_variable/0`; return tracing is disabled, so the + trace contains the configured name and never the returned bytes. Between the + composition entry and successful return it observes exactly one such call, + then proves the synthetic canary is in that host's custody through the + test-only custody fixture and the configured name is absent from the VM + environment. Explicit zero-read and two-read variants fail the count. The + exact-owner filter prevents another concurrent process's read from satisfying + the proof. An earlier revision also asserted that no environment value **equals** the credential in use, which is a different and much weaker claim than it @@ -932,37 +1807,95 @@ Six proof groups are new: route the allowlist does not name is refuted outright. The narrow scan is what lets an environment read return by a name the current expression does not match, which is the drift the case exists to catch. -- **Resolution failures.** One case per row of the failure table above: - absent token, malformed token, a token with no tracing capability, a failed - capability bind, an immediately unreachable capability or `Control`, an - exclusion held past the invocation deadline, a token with no registry row, a gone - registry, a dead custody process, each of the four refusal atoms, a custody - process returning a term outside the closed set (reported `:unavailable`), a - custody process that blocks past the invocation deadline (the **guardian** +- **Adapter preflight and invocation failures.** One case for every private + adapter row of the failure table above: absent token, malformed token, + managed guardian/sender start failure, an immediately + unreachable capability or `Control`, an exclusion held past the invocation + deadline, a still-live Direct session that cannot be cleared or verified and + a destroyed Direct session that clears successfully, a token with no + registry row, a gone registry, a malformed successful route reply, a dead + custody process, each of the three custody refusal atoms — `:missing`, + `:expired` and `:unavailable` — every wrong-producer in-set custody atom — + `:timeout`, `:oversized`, `:no_token` and `:invalid_token` — and a custody + process returning a term outside the closed set, all normalized to + `:unavailable`; a registry process that + blocks past the invocation deadline, and a custody process that blocks past + that deadline (the **guardian** kills the sender and reports `:timeout`, asserted **distinct** from every refusal so the guardian can tell them apart, and asserted to bound the - invocation whatever the custody process does), and a value outside the size - bound. Each + invocation whatever either process does), a value outside the size bound, an + immediate credential-frame write failure and a credential-frame write held + through the guardian deadline. Each asserts the outcome, its closed-set atom, that no child was spawned where the contract says none is, and that no message but the permitted reply, no exit reason and no crash report carries the resolved value. The two-resolutions-at-once case is a **success** case, not a refusal: both - invocations complete with their own credentials. + invocations complete with their own credentials. Paired bootstrap cases make + the sender's group-leader sink fail immediately and block past the guardian + deadline: they return `:unavailable` and `:timeout` respectively, deliver no + token and leave no sink or sender behind. + + Exact-protocol cases mutate one binding field at a time in + `:begin_bootstrap`, `:bootstrap_result`, credential context, every phase + result and every continuation; inject malformed releases and current results, + producer-forbidden atoms, every allowed error and stale once-valid messages; + and assert that only the exact current success can advance. Error results + receive no continuation. Separate forced-clock pairs queue each release + before the deadline, then suspend the sender before receipt and after its + receipt-time check but before the permitted operation; both resume at or + after expiry. The `:begin_bootstrap` pair places the pre-operation barrier + separately before exclusion and before sink installation. They assert both + checks independently, the fixed + `:credential_deadline` sender exit, and the guardian's independent clock + confirmation. The custody-to-frame case pauses with bytes held and proves + scrub without a credential frame. The final-continuation case pauses in the + non-secret final wait and refutes the canary in sender state, mailbox, process + dictionary and forced-crash material before proving no invocation helper + starts. Every case awaits cleanup and restores the sampled + sender, sink, helper, provider-tree and trace-membership baselines. + + Malformed-shape cases forge every private struct with a canary-bearing extra + key: token, registry handle, custody reference and tracing capability handle. + Each is refused by its exact key-set check before routing or child creation as + applicable, with no canary in raw traces, rendered entries, diagnostics or + results. A custody success map with an extra canary-bearing key is likewise + `:unavailable` before frame writing. + + A missing or malformed registry handle, or a missing, malformed or unbound + tracing capability, is a composition failure and is proved in each host's + composition suite below, before runtime use or child creation and with + reverse cleanup. A live registry with no row for the supplied token is an + invocation-time `:unavailable`. The composition failures do not map to one + of the seven private adapter atoms because no adapter invocation exists. + + The exclusion, blocked-registry and blocked-custody witnesses each set the + guardian deadline beyond 5,000 ms. Releasing the held operation after the + hidden default but before that deadline succeeds; holding it through the + later deadline yields the guardian's `:timeout`. Thus an implementation that + leaves any one of the three waits on `GenServer.call/2`'s default cannot pass. - **Tracing, in three cases matching the two tiers above.** Under the **default** trace configuration, a session at the `arguments` level over a real invocation produces no entry naming `route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, no raw trace - message for them, and no credential bytes or token anywhere — because the + message for them, and no credential bytes in any captured raw trace message, + rendered entry or IO request outside the one permitted custody reply. The + token can traverse core in model options before the sender exists; + the structured-entry redaction proof above, rather than sender exclusion, + keeps it out of rendered entries. The bridge calls stay absent because the adapter is in no namespace wildcard. Under a configuration that **explicitly names `:gen_tcp`**, `Loopex.LLM.ReqLLM.ProviderBridge` and - `Loopex.LLM.ReqLLM.ProviderCodec`, the tracer is asserted to receive **no - raw trace message from the sender process at all**, while a non-excluded + `Loopex.LLM.ReqLLM.ProviderCodec`, the tracer captures the expected token-free + bootstrap entry, then is asserted to receive **no further raw trace message + from the sender process after the exclusion acknowledgement**, while a non-excluded control process making the same `:gen_tcp.send/2` call in the same session is asserted to produce one — the pre-delivery property read where it holds, - and a case that cannot pass by tracing nothing. A third case asserts the - three functions exist with their exact identities and that a one-byte - canary credential appears in no captured message or entry, so neither of the - first two can pass vacuously. + and a case that cannot pass by tracing nothing. A third case asserts all + three functions exist with their exact identities and separately proves that + the 128-bit token is placeholdered under `:credential_token` before the + sender exists. It does not render credential bytes as a safety proof: the + first case must show the one-byte canary never reaches any captured raw + message or rendered entry, so neither of the first two cases can pass + vacuously or against the wrong signatures. - **The host-owned processes, proved at each host rather than in the adapter.** The adapter's test tree cannot prove a claim about the CLI's or the daemon's composition, and an earlier draft filed all three there. Each case lives @@ -971,14 +1904,25 @@ Six proof groups are new: | Host | File | Cases | Lane | | --- | --- | --- | --- | - | Reference CLI | `apps/loopex_cli/test/credential_custody_test.exs` | `reads the credential variable exactly once at composition`; `deletes the credential variable from the VM environment`; `custody state is redacted in a forced crash report`; `starts the tracing capability before the runtime and binds it before reporting composition success`; `registry, custody and capability stop on normal stop, failed start and owner loss` | fast | - | App-server host | `apps/loopex_app_server/test/credential_custody_test.exs` | the same five | fast | - | Daemon | `apps/loopex_daemon/test/credential_custody_test.exs` | the same five | fast | - - Each proves that composition reads the variable exactly once, deletes it - from the VM's environment, that the holding process's `format_status/1` - redacts its state under a forced crash report, and that the capability's - start-bind-stop lifecycle follows its host owner. The adapter's own tree keeps only what is the adapter's + | Reference CLI | `apps/loopex_cli/test/credential_custody_test.exs` | `reads the credential variable exactly once at composition`; `deletes the credential variable from the VM environment`; `custody and registry redact complete forced-crash reports`; `starts the tracing capability before the runtime and binds it before reporting composition success`; `binding the same handle to a different runtime refuses before runtime use or child creation and preserves the first binding`; `missing, malformed or extra-key registry handle refuses before runtime use or child creation`; `missing, malformed, extra-key or unbound capability refuses before runtime use or child creation`; `every such refusal reverses already-started registry, custody and capability edges`; `registry, custody and capability stop on normal stop, failed start and owner loss` | fast | + | App-server host | `apps/loopex_app_server/test/credential_custody_test.exs` | the same nine | fast | + | Daemon | `apps/loopex_daemon/test/credential_custody_test.exs` | the same nine | fast | + + Each proves that composition reads the variable exactly once using the + call-only exact-owner trace above, transfers the synthetic canary into + custody, and deletes the name from the VM's environment. It then forces custody to crash while handling a + canary-bearing rotation request and the registry to crash while handling a + canary-bearing install request. For each process it captures the whole OTP + report and owner-observed `EXIT`, and refutes the canary in the initial call, + last message, state, reason, metadata and log. The test asserts that + `format_status/1` replaced `state`, `message` and `reason` and emptied `log`, + rather than passing because no report was emitted. Each host also proves that the capability's + start-bind-stop lifecycle follows its host owner. Each also proves malformed + or missing registry handles and malformed, missing or unbound tracing + capabilities refuse before runtime use or child creation and unwind any edge + already started. Each also binds one handle to runtime A, refuses its reuse + for runtime B, proves the A binding unchanged, and completes a later A call. + The adapter's own tree keeps only what is the adapter's to prove: that it reads no environment variable for a credential and that the token and resolution contract behaves. @@ -1014,27 +1958,53 @@ The review is an acceptance point of M5 Outcome 6, read by someone other than the implementer, over the exact diff. It answers: that the token is opaque and carries no credential and no authority; that the routing registry holds routing only, with no bytes and no material a secret could be derived from; -that the spawned closure is token-free and receives the token and registry -handle only after synchronous exclusion; that the mandatory tracing capability +that the sender's exact initial argument is token-free, its managed ownership +and guardian adoption complete before initialize, it remains parked until +exact child readiness, and it receives the token and registry handle only +after synchronous exclusion; that `:begin_bootstrap` carries the retained +deadline, the exact bootstrap result union alone can release credential +context, and each producer-scoped phase result advances only through its exact +continuation carrying that unchanged instant; that the sender checks the clock +on receipt and immediately before each permitted operation, an error never +gets a continuation, and wrong, stale or malformed tuples cannot advance; that +the custody-to-frame deadline cut scrubs held bytes without a frame and the +post-write final wait retains no credential before its result or continuation; +that the final deadline cut starts no invocation helper; that an unexpected +sender `DOWN` consumed before expiry maps to `:unavailable`, the same signal +consumed after expiry maps to `:timeout` only after the guardian checks its +clock, and neither exposes the process reason; that the mandatory tracing capability starts before the runtime, binds before composition reports success and stops with its host owner on every exit path; that immediate capability loss refuses `:unavailable` while a delayed exclusion ends only at the guardian's invocation deadline as `:timeout`; that trace-session destruction removes its process flags, a tracer restart reconstructs exclusions from `Control`, a `Control` -restart kills downstream senders with the destroyed sessions, and the last MFA +restart tears down owner-workers and awaits their managed guardians and senders +before the replacement tracer starts, and the last MFA owner restores every live session's selected pattern; -that the resolved value has no path into guardian state, a message other than +that the resolved value has no path into guardian state, a BEAM message other than the one permitted reply, an exit reason, a crash report, an IO request, a file or the environment; that every row of the failure table refuses without -retaining a copy; that the guardian's deadline bounds exclusion and resolution -whatever a custody process does; that the cleanup and abandonment paths do not +retaining a copy; that managed mode allocates its absolute invocation deadline +before either start, never resets it and, after guardian registration, exact +sender adoption and initialize, applies it to provider launch/readiness, sender +release, exclusion, registry routing, custody resolution and the +credential-frame write, with `:timeout` reported only after the guardian's own +clock confirms expiry; that Direct mode carries its request's same pre-launch +absolute instant through inherited-session clearing, sink installation, +routing, custody and frame write; that an +immediate managed-gate refusal is `:unavailable` while a non-answering +`owner_workers` start is an owner-group/runtime liveness +failure outside that clock; that the cleanup and abandonment paths do not resurrect a value; that immediate loss of custody, registry or capability answers `:unavailable` rather than reconstructing or bypassing anything; that a host supplying no token is refused rather than falling back to an ambient read; and, on the host side of the boundary, that each reference implementation reads the operator's variable -once, deletes it, redacts its custody process's state, and registers a token -that carries no bytes. Its record is retained with the milestone's evidence. +once, deletes it, gives custody and registry complete `format_status/1` +redaction for state, message, reason and log, and registers a token that carries +no bytes; and that a guardian crashing after its initialize message exposes no +token or registry-incarnation canary in the complete Task/supervisor report or +owner-observed exit. Its record is retained with the milestone's evidence. ### Concurrency, as a measurement @@ -1093,10 +2063,13 @@ a condition a test may be weakened to meet. Concept: [Consequences and rollback](0034-provider-credential-handoff-over-bootstrap-channel.md#concept-adr-0034-consequences). -Adapter-internal. The `Loopex.Model` callbacks, the public protocol and its -generations, public events, snapshots, artifacts, the executor protocol and -every durable record are untouched, so no vector, schema or migration is -affected. The private codec's version and frame kinds are unchanged, and a +The `Loopex.Model` callbacks, the public protocol and its generations, public +events, snapshots, artifacts, the executor protocol and every durable record +are untouched, so no vector, schema or migration is affected. The experimental +public `complete_prompt/3` helper keeps its arity and result union but changes +its accepted options: callers compose ephemeral custody and a routing registry +and pass their token and handle; an old environment-only call refuses before +launch. The private codec's version and frame kinds are unchanged, and a child built from the same manifest digest behaves identically; the build manifest is not revised by this decision. @@ -1109,10 +2082,19 @@ normal stop, failed start and owner loss. The reference CLI, app-server host, M5 daemon and real-provider lane keep reading `LOOPEX_PROVIDER_API_KEY` where they compose, and delete it there, so an operator's setup is unchanged and the release -check's credential frame is unchanged. An embedder that relied on the adapter reading -the environment for it must pass a token instead; that is the refusal -path, not a silent fallback, and it is stated in the operator and developer -documentation the milestone updates. +check's credential frame is unchanged. The lane's accepted direct +`complete_prompt/3` call uses the adapter-created no-runtime Direct capability, +ephemeral registry/custody and unmanaged lifetime just defined; runtime model +options cannot select that mode. The direct caller/host layer in +`provider_test.exs` reads and deletes the environment value, starts that +ephemeral custody and registry, and passes only token plus handles into +`complete_prompt/3`; the helper never reads the environment or receives +credential bytes. An embedder that relied on the adapter reading the +environment for it must pass a token and registry handle instead; omission +refuses with `:no_token` before launch and never falls back. The migration is +stated in `docs/operator/runtime.md`, +`docs/developer/runtime-and-embedding.md`, and +`docs/developer/compatibility-surfaces.md`. Rollback is a coordinated code rollback of the adapter, the core trace-exclusion support and the CLI, app-server and daemon composition changes. @@ -1124,4 +2106,5 @@ rollback needs no data migration and leaves no retained trace state to repair. Acceptance binds this complete pair at the exact candidate the maintainer names in the governance record. Its claims remain unproved until the tests the -M5 plan maps to Outcome 6 exist and pass and the security review is recorded. +M5 plan maps to Outcome 6 exist and pass, the security review is recorded, and +Outcome 5 closes against those same bytes. diff --git a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md index fe7596bf5..857d48fc7 100644 --- a/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md +++ b/docs/adr/0034-provider-credential-handoff-over-bootstrap-channel.md @@ -6,9 +6,15 @@ Technical depth: [Credential handoff mechanics](0034-provider-credential-handoff - **Status:** Proposed - **Date:** 2026-09-19 - **Decision owner:** Maintainer -- **Supersedes:** nothing; refines where ADR 0019's credential-bearing - invocation reads its credential from -- **Prerequisite for:** M5 Outcome 6 +- **Supersedes:** ADR 0019 only where it says the environment variable is the + invocation's credential source, the ready sender resolves that variable, and + the sender must be raw-spawned and owned only by the guardian; managed calls + instead make the guardian and sender direct temporary `owner_workers` + children, while the supervised sender's initial call and closure are + token-free and Direct mode retains a raw linked-and-monitored sender; + ADR 0019's private-channel, first-image scrubbing, failure-teardown and + forensic-memory rules remain unchanged +- **Prerequisite for:** M5 outcomes 5 and 6 ### Context and Decision @@ -82,9 +88,48 @@ the value rather than added a registry row. An opaque token discloses nothing and stays the same shape however many credentials sit behind it. **The guardian enforces the deadline, and the resolver is not asked to.** The -custody callback takes no deadline. The guardian already owns the invocation -deadline and already supervises the sender, so it bounds the whole resolution -and kills the sender when the instant is reached. An earlier draft handed the +custody callback takes no deadline. The invocation's absolute deadline exists +before either managed start and setup never resets it. A start call that never +answers remains an owner-group/runtime liveness failure because the transfer is +incomplete and no private adapter clock can safely own it. Once Core has +registered the inert guardian, the guardian has installed the returned +retainer monitor, and the guardian has adopted the inert sender through an +exact link-and-monitor handshake, initialization begins under that same +deadline. If its instant has already passed, the guardian cleans up and reports +`:timeout` immediately. Otherwise it bounds provider launch and readiness, +sender release, trace exclusion, token routing, custody resolution and the +credential-frame write, killing the sender at expiry. Immediate guardian +start, registration, authorization, sender start or adoption refusal is +`:unavailable`. Exact child readiness releases the parked sender with +`{:begin_bootstrap, sender_ref, guardian_pid, sender_pid, absolute_deadline}`; +the sender validates and retains that instant on receipt, rechecks it +immediately before installing trace exclusion and again immediately before +installing its sink, and acknowledges only with the exact +`{:bootstrap_result, sender_ref, sender_pid, guardian_pid, result}` union, where +`result` is `:ok` or `{:error, :unavailable}`. Registry lookup, custody +resolution and credential-frame write are three parked sender phases. Each +sends the guardian exactly `{:credential_phase_result, sender_ref, +guardian_pid, sender_pid, phase, result}` and advances only on +`{:credential_phase_continue, sender_ref, guardian_pid, sender_pid, phase, +absolute_deadline}` after the guardian rechecks that same instant. The result +union is phase-scoped: registry and credential-frame phases admit only `:ok` +or `{:error, :unavailable}`. The custody phase admits `:ok`, the custody +process's `:missing`, `:expired` or `:unavailable`, and `:oversized` produced +only by the sender's byte-bound check after an otherwise successful custody +reply; custody itself may not originate `:oversized`. Every other current +result fails closed. An error result never +gets a continuation. The sender rechecks the retained instant when it receives each +continuation and immediately before the one operation that continuation +permits. It makes the same two checks on credential context before registry +routing. The custody gate carries no bytes. After a successful credential-frame +write, the sender drops its credential-bearing state and enters a final wait +whose state is non-secret before it emits the `:credential_frame` result. The +final continuation therefore permits only normal exit; after consuming that +exact normal sender `DOWN`, the guardian checks the deadline again and starts +the generic helper that sends the invocation frame. Any other sender `DOWN` +before expiry is `:unavailable` and starts no invocation helper; a deadline +exit maps to `:timeout` only after the guardian's own clock confirms expiry. +Direct mode uses the same phase gates. An earlier draft handed the resolver an absolute instant and relied on it to honour one; that is withdrawn by the same decision, because it made a safety property depend on code the adapter does not write, and a custody process that simply blocked would have @@ -96,20 +141,22 @@ is gone, resolution answers `:unavailable` and every invocation on that token refuses the same way until the host recomposes. Nothing rebuilds the secret, and nothing could: the registry holds no bytes to rebuild it from. -**Exactly one credential-bearing transfer exists into or within the adapter, -and this pair names it.** The narrower wording is deliberate: the host puts the +**Exactly one credential-bearing BEAM message exists from the adapter edge +inward, followed by one private-channel frame to the child, and this pair names +both.** The narrower wording is deliberate: the host puts the bytes into custody when it composes, and may replace them there when it rotates, and both are transfers in the parent that this pair does not govern — they are the host's, before the adapter is involved at all. What this pair governs is everything from the adapter's edge inward. -**Within that boundary the transfer is one, and this pair names it.** A host that keeps the bytes and answers a resolver call has to send +**Within that boundary the parent-VM transfer is one, and this pair names it.** A host that keeps the bytes and answers a resolver call has to send them to the process that asked; a contract saying the value is never in a message could never be implemented alongside one. So the rule is a permission with a boundary: the custody process's reply to the sender is the one -transfer — bounded, unlogged, never forwarded, never retained after the frame -is written — and it is the same class of act as writing the credential frame, -protected the same way ADR 0019 already protects that sender. The registry +credential-bearing BEAM message — bounded, unlogged, never forwarded, never +retained after the frame is written. The sender then performs the one required +credential-bearing write on the child's private socket, protected the same way +ADR 0019 already protects that sender. The registry lookup before it carries no credential, so routing adds no second place a secret can be seen. What keeps those bytes out of a trace is stated against the implementation rather than against an assumption about it, and ADR 0030's @@ -117,14 +164,15 @@ match-specification exclusion is **implemented by M5 rather than assumed present**: the adapter is in no default trace namespace, so the credential work is untraced under every default configuration; and where a host explicitly names the adapter module, -the credential-bearing functions are **excluded before a trace message is -delivered at all**, which is what ADR 0030 already requires and what M5 adds -to `Loopex.Trace` to honour. Redaction at the sink cannot serve that purpose, -because the raw call reaches the tracer first; it stays as defence in depth, -resting on a bound *shape* — those bytes always travel under a -credential-named key and are placeholdered at any size, which size alone would -not give, since the pass leaves a short binary verbatim and a credential may -be one byte. The exclusion is **by function and by process together**, in one call: the +the credential-bearing functions are **excluded before a post-bootstrap trace +message is delivered at all**, which is what ADR 0030 already requires and what M5 adds +to `Loopex.Trace` to honour. Redaction at the sink cannot protect credential +bytes: the raw call reaches the tracer first, and ADR 0030's placeholder keeps +a value-derived size and digest from which a one-byte secret is recoverable by +enumeration. Process and function exclusion are therefore the sole credential +trace control. The keyword-key redaction M5 adds is only for the opaque 128-bit +token while it crosses core before a sender exists. For a runtime-managed call the exclusion is **by function and by +process together**, in one call: the match specification ADR 0030 names, for the functions that hold the bytes, and a process-level exclusion the sender installs on itself before it resolves anything — because a function that carries the credential calls functions it @@ -133,29 +181,113 @@ adapter's own functions are patterned. M5 proves both at the tracer rather than at the sink, in a case that names `:gen_tcp` on purpose. ADR 0030 is not edited: its prose is honoured once this lands. -The spawn ordering is part of that decision. The spawned closure contains only -the tracing capability and the guardian to acknowledge; it contains no token, -registry handle or credential. The process installs both exclusions and -acknowledges them synchronously. Only then does the guardian send the token and -registry handle to it. When the last sender using an excluded function exits, +The start ordering is part of that decision. Before provider launch, Core's +managed starter first creates an inert guardian with exactly its start +reference, callback owner and stop reference, then registers it as the exact +provider resource. The guardian installs Core's returned retainer monitor, +drops its callback monitor and returns an exact authorization acknowledgement. +The callback receives that acknowledgement before starting further work, and +the guardian can already service a stop request. A second start +creates an inert sender whose initial argument contains only its start +reference, callback owner, guardian pid and tracing capability — no token, +registry handle, socket, nonce, request or credential. The sender links to the +guardian; the guardian validates its reference and pid, installs a monitor and +acknowledges adoption. Only then may the sender drop its temporary callback +monitor and acknowledge adoption completion to the callback. The callback +waits for that acknowledgement; the sender remains parked. The guardian has already dropped its own +temporary monitor after Core registration and retainer-monitor installation. +The callback then gives the guardian +its initialize message, including the request/configuration, opaque token and +registry handle but no credential bytes; the sender receives none of them. The +guardian starts ADR 0019's provider tree. Exact child readiness releases the +sender with the bound, non-secret `:begin_bootstrap` tuple and the retained +absolute deadline; a refusal before readiness releases nothing. The sender then +installs both exclusions, drains every pre-clear trace signal through OTP's +delivery barrier and, from the now-untraced sender, spawns and installs its +group-leader sink. The sink links for abnormal termination and monitors the +sender for normal exit. The sender acknowledges only after both pids are +verified clear, using the exact closed `:bootstrap_result` union above. A wrong +binding cannot release context, and a malformed current result fails closed. +Only exact success lets the guardian send the token, registry handle and +non-secret channel context — the accepted socket and invocation nonce — to it. +When the last sender using an excluded function exits, core restores each live trace session's selected pattern for that function. -Destroying a trace session removes its process flags; `Control` retains live +Trace-session start and stop route through `Control`, using a deadlock-free +snapshot handshake, so they serialize with exclusion. Trace alone holds each +full strong OTP session handle; Control retains only the weak `{name, id}` plus +selection/configuration. Explicit stop destroys the strong handle, and tracer +death drops the last strong holder; the replacement confirms the weak old +identity is absent before it creates and publishes a new session. A replacement +hello may reach Control before or after the predecessor monitor `DOWN`; Control +resolves that exact predecessor first and keeps the replacement idle until it +has received and applied the retained snapshot. `Control` retains live sender membership and the ref-counted function set so a replacement trace -session reapplies the same exclusion. A `Control` restart destroys the trace -sessions and the downstream sender owners together, so no credential-bearing -sender crosses that loss with an unremembered exclusion. +session reapplies the same exclusion. The tracer retains pending return timing +only at levels that request returns, monitors every pid represented there and +purges that pid's rows when it exits; managed exclusion also purges the sender's +rows after the delivery barrier. Thus clearing a flag cannot strand one call +row, and the Direct path returns to baseline when its sender exits. A `Control` +restart stops the sole strong-handle owner and, through `:rest_for_one`, the owner groups beneath it. M5's +managed provider-lifetime starter makes both guardian and sender temporary +children of the existing per-owner worker supervisor; owner-group teardown +kills and awaits them before the supervisor may start the replacement tracer. +Each managed start is authorized by an exact operation handshake: a child that +materializes after its calling scope died remains inert and token-free, +observes owner loss and exits before starting any helper or provider action. +The guardian drops and flushes its temporary callback monitor only after Core +registration succeeds and it has installed the returned retainer monitor. The +sender does so only after the guardian has acknowledged its exact adoption and +installed the sender monitor. Lifetime then passes to Core's retainer, the +guardian-sender relation and their `owner_workers` parent, so ordinary callback +completion does not end retained post-result cleanup. +The callback also monitors each child from the first matching start message +that discloses its pid until that transfer completes; a child death in the gap +is `:unavailable`, not an unbounded wait. +No credential-bearing sender therefore crosses that loss with an unremembered +exclusion. -The guardian's existing invocation deadline is the only clock for this -sequence. A capability or `Control` that is immediately unreachable produces -`:unavailable`; an exclusion that has not completed when the deadline arrives -causes the guardian to kill the sender and report `:timeout`. There is no -separate exclusion timeout and no hidden `GenServer.call/2` timeout. +The same absolute invocation deadline allocated before managed start is the +only clock for the initialized guardian sequence; neither start nor adoption +resets it. Once both transfers complete, it covers provider launch and +readiness, sender release, exclusion, routing, custody resolution and the +credential-frame write. A capability or `Control` that is immediately +unreachable produces `:unavailable`; any of those steps that has not completed +when the deadline arrives causes the guardian to kill the sender and report +`:timeout`. There is no separate sub-operation timeout and no hidden +`GenServer.call/2` timeout. At the three dataflow boundaries the sender parks. +The exact result/continuation exchange above makes both processes apply the same +clock before the next phase begins. + +**The existing direct `complete_prompt/3` helper remains a separate no-runtime +path, with an explicit option migration.** Its arity and result shape stay the +same, but an old environment-only options list no longer works and refuses +before launch with the adapter's ordinary missing-token result. Its caller +performs the same host work as the +reference compositions: it reads and deletes the environment input, creates +ephemeral custody and routing-registry processes, and passes only the opaque +token and handles. The adapter mints a private Direct marker for this helper; +runtime model options cannot select it, and every runtime-bound call requires +the managed starter above. Because the unmanaged sender can inherit named or +legacy trace flags from a traced caller, its token-free phase clears and +verifies every inherited live trace session before the guardian may deliver +the token. Its raw guardian starts the sender linked and monitored; abnormal +guardian loss ends it, while normal cleanup explicitly stops and awaits it. +The request's absolute deadline is allocated before Direct launch and carried +unchanged through inherited-session clearing, sink installation, routing, +custody resolution and the frame write. It does not alter or restore +runtime-owned MFA patterns: the helper +is outside ADR 0030's runtime process domain and this inherited-process clear is +defensive compatibility. This protects the direct helper's adapter sender from +Loopex tracing that already selected its ancestry; host custody and unrelated +host tracing remain the direct caller's responsibility, and no claim is made +against raw tracing started after the acknowledgement. **Everywhere else the boundary is where the adapter's claims stop.** Inside it — the token, the sender, the frame, the child — the adapter proves what it says: the value is never in the child's environment, in argv, in the journal, -in a public event, a snapshot, a progress item or a diagnostic, in adapter -process state, in any message but that one, in an exit reason, a crash report +in a public event, a snapshot, a progress item or a diagnostic, in guardian, +coordinator, registry or other long-lived adapter state, in any message but the +one custody reply, in an exit reason, a crash report or an IO request, and never written to a file. Outside it, custody belongs to the host and the adapter proves nothing about it beyond the structural rules it does impose: the registry holds routing only; the mandatory capability confirms exclusion before @@ -222,30 +354,72 @@ decision buys. A resolver supplied as a function was rejected because a closure is not plain boundary data and its captured environment is exactly the retention the security review has to exclude. -**Implementation and milestone-closure evidence.** This is a trust claim, so its class is +**Implementation and milestone-closure evidence.** Outcome 5's integrated +real-provider daemon workflow waits on this decision as well as Outcome 6. +This is a trust claim, so its class is negative tests plus a security review, with a real-provider proof for the path the release check already runs. Every credential-plane negative that M0 to M2 established is re-pointed at the new handoff and must hold with its assertion unchanged in meaning; the parent VM's environment is proved empty of the credential from the completion of composition onward — before, during and after a call; two invocations running at once are proved unable to observe -each other's credential; every resolution failure the contract names — absent -token, malformed token, no registry row, a gone registry, a dead custody -process, a refusing custody process, a malformed successful reply, one that -blocks past the invocation deadline, and a value outside the size bound — is -proved to refuse with one of the seven closed reason atoms and to leave no retained copy, with the -guardian's timeout proved distinguishable from every refusal and proved to -bound the invocation whatever the custody process does; two resolutions in -flight at once are proved to be independent successes rather than a refusal; -the token-free spawn entry, the post-exclusion token-and-registry message, the -one permitted credential-bearing reply, and the resolver call that -carries it, are proved excluded from tracing under a trace session at the -`arguments` level; the last owner restores every live session's selected MFA -pattern; trace-session and tracer restart cases prove that destroyed-session +each other's credential; the two adapter preflight failures — absent and +malformed token — and every remaining invocation-private failure the contract names — +immediate guardian start, Core registration, guardian authorization, sender +start or adoption refusal; sender raise, exit or kill before expiry and the +same `DOWN` consumed after expiry; an expired initialized deadline; immediate or blocked +provider readiness and group-leader sink installation; immediate and delayed exclusion failure; Direct-session +clearing failure, no registry row, a gone registry, a dead or refusing custody +process, malformed successful route or custody replies, registry or custody +silence, immediate or blocked frame write, and a value outside the size bound — +are proved to map to the seven closed reason atoms and to leave no retained +copy. The registry accepts only one exact valid custody reference or +`{:error, :unavailable}`; every other answer, including another in-set atom, is +normalized to `:unavailable`, while custody may originate only `:missing`, +`:expired` or `:unavailable`. Host composition separately proves refusal of a missing or malformed +registry handle, or a missing, malformed or unbound tracing capability, before +runtime use or child creation, with reverse cleanup of anything already +started. A live registry with no row for the token is instead an +invocation-time `:unavailable`. A non-answering managed start is proved to stay +in the Core owner-group liveness class rather than impersonate an adapter +timeout. The guardian's timeout is proved distinguishable from every refusal; +the same absolute deadline is proved not to reset across managed setup and, +after registration, adoption and initialize, to bound provider launch and +readiness, sender release, exclusion, routing, custody and frame writing +whatever the blocked operation does. Protocol witnesses inject wrong, stale +and malformed bootstrap and phase tuples, every result atom from the wrong +producer, and explicit error results; none can release context, receive a +continuation or start the next operation. At every sender release cut, paired +cases queue a valid message before the deadline and suspend the sender first +before receipt, then after receipt-time validation but before the permitted +operation, until the instant has passed. On resume it starts no next operation, +scrubs any credential bytes it still holds and exits with the fixed non-secret +`:credential_deadline` reason. The custody-to-frame cut specifically proves +that held bytes never reach a frame. A separate final-gate witness pauses after +the `:credential_frame` result and proves the parked sender already retains no +canary in its state, mailbox or forced-crash material; expiry there starts no +invocation helper. The +guardian reports `:timeout` only after its own clock confirms expiry. Direct +mode separately proves that its +request's pre-launch absolute instant survives a delay beyond 5 seconds, +expires a clear held through that instant, and bounds custody and frame write; +at each of those cuts guardian loss reaps the raw linked-and-monitored sender +and sink with no late frame, while normal cleanup stops and awaits both. Two resolutions +in flight at once are proved to be independent successes rather than a refusal; +the tracer captures the expected token-free sender start entry, deliberately backlogs +pre-clear traffic, and after the delivery-barrier-backed exclusion +acknowledgement receives no further raw trace event from that sender — including +no `:gen_tcp.send/2` event — while an unexcluded control produces one. Separate +state assertions prove token delivery follows the acknowledgement and that the +one custody reply is the only credential-bearing BEAM message; call-only tracing +is not used to claim application messages were observed. The last owner restores every live session's selected MFA +pattern; managed and Direct sender exit restore the tracer's pending-call state +to baseline; trace-session and tracer restart cases prove that destroyed-session flags are not treated as persistent and retained membership protects a -replacement session; capability loss before binding, immediate -unreachability and delayed exclusion distinguish composition refusal, -`:unavailable` and the guardian's `:timeout`; the adapter's library tree is +replacement session; missing or malformed registry handles and missing, +malformed or unbound tracing capabilities, +immediate capability loss and delayed exclusion distinguish composition +refusal, `:unavailable` and the guardian's `:timeout`; the adapter's library tree is proved to read no environment variable for a credential by any route, with the launcher's ADR 0019 scrubbing read proved never to be consulted for one; and a named @@ -255,7 +429,10 @@ resolution point, frame ordering, failure paths, the host implementations' custody, and every place a value could be retained — and records the reading with the milestone. The real-provider lane in `bash scripts/check-release.sh` proves the path -still reaches a real provider. The concurrency result is a measurement +still reaches a real provider. Every credential-consuming case runs in its own +fresh child BEAM inherited from the release shell, because reference +composition consumes and deletes the variable and never restores it; each run +must execute exactly one named case. The concurrency result is a measurement recorded beside the M4-closure baseline, not a pass condition. Technical depth: [Contract and evidence](0034-provider-credential-handoff-over-bootstrap-channel-technical.md#technical-adr-0034-decision). @@ -264,11 +441,17 @@ Technical depth: [Contract and evidence](0034-provider-credential-handoff-over-b ### Consequences, Compatibility and Rollback The credential plane gets the property the rest of ADR 0019's design already -has. In the parent the secret exists in exactly two places — the host's custody -process, which holds it and answers for it, and the short-lived sender, which -receives it once, writes it and dies — and in the child that needs it. Nowhere -else: not in adapter state, not in the environment, not in a durable or public -plane, and in no message but the one reply this pair permits. Two invocations in +has. For the reference hosts after composition, the live logical copies in the +parent are the host's custody process, which holds and answers for the secret, +and the short-lived sender, which receives it once, writes it and dies; the +child also receives the value it needs. Composition necessarily handles the +input transiently, and another host may choose a different defensible custody +mechanism. This is a dataflow and logical-custody claim, not a claim of erased +memory or forensic inaccessibility; ADR 0019's disclaimer remains. The secret +is not retained in guardian, coordinator, registry or other long-lived adapter +state, the environment after reference-host composition, a +durable or public plane, or any message except the one custody reply this pair +permits. Two invocations in one VM become independent, so the **eleven** provider test modules serial for this reason can run concurrently and the fast check stops being pinned by that application. The other two stay serial on their own reasons, which is why the @@ -282,9 +465,12 @@ ordinary refusal to dispatch, which is what a missing environment variable produces today. -Nothing public changes. This is adapter-internal: no Model callback, no public -event, snapshot, artifact, wire method or protocol generation, no durable -record, and no change to what the child may receive, from whom, or when. The +The public `complete_prompt/3` helper keeps its arity and result union, but its +accepted options change: callers must compose ephemeral custody and a routing +registry and pass their token and handle. An environment-only call now refuses +instead of making the adapter read the environment. The `Loopex.Model` +callback, public events, snapshots, artifacts, wire methods and protocol +generations, durable records, and what the child may receive remain unchanged. The credential-size bound and the refusal behaviour ADR 0019 fixed stay as they are. Rollback reverts the adapter, trace-exclusion support and the CLI, app-server and daemon composition changes together. No data, root or protocol diff --git a/docs/adr/README.md b/docs/adr/README.md index 6255f5deb..1514c42c4 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -165,7 +165,8 @@ because those numbers are now accepted M2 decisions. 0031 to 0034 are the four Proposed M5 prerequisites: the daemon's store selection for `0.2.0`, which is the existing local adapter with its documented limits, its capacity-as-store-loss consequence and its retirement procedure, -leaving a daemon-grade adapter and any migration open for a separate decision; +leaving a daemon-grade adapter and its Store/journal-format migration open for +a separate decision while ADR 0032 owns the daemon-index compatibility import; daemon attachment residency and at-least-once replay over the generation-2-only Unix-domain-socket transport with bounded session pages; the collaboration diff --git a/docs/developer/README.md b/docs/developer/README.md index 6daff7835..78f7681cb 100644 --- a/docs/developer/README.md +++ b/docs/developer/README.md @@ -10,7 +10,8 @@ New to the repository, in this order: 1. [Root README](../../README.md) — what Loopex is and where things stand. 2. [DEVELOPMENT.md](../../DEVELOPMENT.md) — prerequisites and the two check commands: `bash scripts/check.sh` before a merge and - `bash scripts/check-release.sh` before closure or release. + `bash scripts/check-release.sh` once before closure; an unchanged-source + release reuses that evidence. 3. [Plans and current status](../plans/README.md) — what the project is committed to, what is authorized right now, and the next decision. Its Directing the Work section covers how development is requested. diff --git a/docs/developer/agent-context-map.md b/docs/developer/agent-context-map.md index 7df74ef96..648c25373 100644 --- a/docs/developer/agent-context-map.md +++ b/docs/developer/agent-context-map.md @@ -50,7 +50,7 @@ separate decision duty when a founding boundary or invariant would change. | Embedded API, transports, clients, ACP | [API and transports](../vision.md#concept-vision-api-transports) | [Transport mechanics](../vision-technical.md#technical-vision-api-transports) | One semantic contract, JSONL RPC first, reference surfaces. The first non-Elixir surface is the foreground app server: read the [protocol pair](app-server-protocol.md#concept), the [operator runbook](../operator/app-server.md#concept), and the independent consumers in [`clients/`](../../clients/README.md). | | Hosts and wrappers | [Hosts](../vision.md#concept-vision-hosts) | [Host mechanics](../vision-technical.md#technical-vision-hosts) | Expected consumers, secured sample host, independent implementation. | | Repository layout and ADR agenda | [Repository seed](../vision.md#concept-vision-repository-seed) | [Exact seed](../vision-technical.md#technical-vision-repository-seed) | Pair with the [ADR 0001 decision](../adr/0001-repository-and-application-layout.md#concept-adr-0001-decision) and its [technical mechanics](../adr/0001-repository-and-application-layout-technical.md#technical-adr-0001-decision). | -| Delivery shape and milestones | [Delivery strategy](../vision.md#concept-vision-delivery-strategy) and [roadmap](../roadmap.md#concept-roadmap-ladder) | [Delivery mechanics](../vision-technical.md#technical-vision-delivery-strategy) and [roadmap evidence](../roadmap-technical.md#technical-roadmap-ladder) | The [plans index](../plans/README.md) owns current status; an accepted plan pair is the commitment. [M4](../plans/M4.md#concept) is Closed and no milestone is active; how one is planned, run and closed is the [milestone guide](milestones.md#concept), and which checks a change must pass is the [verification guide](verification.md#concept). | +| Delivery shape and milestones | [Delivery strategy](../vision.md#concept-vision-delivery-strategy) and [roadmap](../roadmap.md#concept-roadmap-ladder) | [Delivery mechanics](../vision-technical.md#technical-vision-delivery-strategy) and [roadmap evidence](../roadmap-technical.md#technical-roadmap-ladder) | The [plans index](../plans/README.md) owns current status; an accepted plan pair is the commitment. [M4](../plans/M4.md#concept) is Closed; the register carries the current M5 state. How a milestone is planned, run and closed is the [milestone guide](milestones.md#concept), and which checks a change must pass is the [verification guide](verification.md#concept). | | Serial barriers | [Ordering constraint](../vision.md#concept-vision-serial-barriers) | [Exact rejoin order](../vision-technical.md#technical-vision-serial-barriers) | A milestone may add barriers but cannot weaken the founding sequence. | | Verification, invariants, budgets | [Verification](../vision.md#concept-vision-verification) | [Exact evidence](../vision-technical.md#technical-vision-verification) | Claim-proportional tests and scope-specific minimalism budgets. | | Compatibility and release governance | [Compatibility](../vision.md#concept-vision-compatibility) | [Compatibility mechanics](../vision-technical.md#technical-vision-compatibility) | Versioned surfaces, 0.x labels, migrations, rollback, freezes. What is exposed today, with M4's experimental labels and the app server's exact-generation rule, is in [compatibility surfaces](compatibility-surfaces.md#concept); M4 moved the source `VERSION` to `0.1.0`, which ADR 0023 keeps separate from any package, tag, publication or freeze. | @@ -66,8 +66,10 @@ are Mix tasks: `mix loopex.deps_budget`, `loopex.core_only`, `loopex.matrix`, `bash scripts/check-bootstrap.sh` runs the bootstrap aggregate. `bash scripts/check.sh` is the fast check each integration candidate runs once, in CI on the branch or locally before the merge, and -`bash scripts/check-release.sh` is the slow check run before closure and -release; [DEVELOPMENT.md](../../DEVELOPMENT.md) describes both. The milestone +`bash scripts/check-release.sh` is the slow check run once before closure; an +unchanged-source release reuses that evidence and runs only its pre-tag +administrative-SHA proofs. [DEVELOPMENT.md](../../DEVELOPMENT.md) describes +both. The milestone gate runners they replaced are gone, and the gate files under `docs/plans/` are historical records of what those runs proved. The four repository skills are `open-milestone`, `close-milestone`, `adr`, and `mutant-hunt` as an @@ -5384,9 +5386,9 @@ satisfy: recording the decision is itself a commit, and it comes after the runs. Closure now names a **tested implementation SHA** — the candidate the matrix ran on and the reviewer read — and an **administrative closure SHA** that records the decision. The matrix runs once, from the first, and the -second is **confined to four paths** — the register row, the plan's Closure -row, this context map's own entry, and the milestone's closure-runs evidence -page — stated once in +second is **confined to five paths** — the register row, the plan's Closure +row, this context map's own entry, the milestone's closure-runs evidence page, +and the root README's exact derived status summary — stated once in [the confinement rule](milestones-technical.md#technical-milestones-confinement). The evidence page is in that list deliberately: the runs are *of* the tested commit, so the commit that records them is necessarily the later one, and an @@ -5394,15 +5396,18 @@ earlier wording that let the administrative commit change "nothing the runs covered" left that page with no home at all. The **tag names the administrative SHA**, because that is the tree a reader -who fetches the tag gets. The release verifies that commit is confined — -`git diff --name-only ..` reaching only the four paths -above, all of which are under `docs/`, so nothing outside `docs/` moved — and -on that basis re-proves documentation only: `check.sh --docs` on -the tagged SHA, and a recomputed archive manifest compared, for every entry -outside `docs/`, with the one recorded on the evidence page for the tested -SHA. **No suite and no release check run twice**, and no provider -credential is spent again. Run evidence is immutable, held where it cannot be -edited after the packet is read. +who fetches the tag gets. Before creating the tag, the release verifies that +commit is confined — `git diff --name-only +..` reaching only the five paths above — and re-proves +documentation with `check.sh --docs` and the final semantic gate on that +administrative SHA. A recomputed archive manifest must match the tested archive +for every entry outside `docs/` except root `README.md` and `SOURCE_IDENTITY`; +the README is validated by confinement plus the documentation/status gate, and +each archive's `SOURCE_IDENTITY` is separately validated against that archive's +own commit and source identity. **No suite and no +release check run twice**, and no provider credential is spent again. Run +evidence is immutable, held where it cannot be edited after the packet is +read. What changed in what a check proves: the documentation gate and the archive identity are now proved of the **published** bytes rather than only of the @@ -5426,18 +5431,20 @@ publication. The maintainer corrected the two-commit closure rule after external review. The tested implementation commit now contains an indexed, unfilled `docs/evidence/-closure-runs.md` scaffold. The administrative closure -commit is the tested commit's direct child and fills that existing page, so its -confinement remains exactly four paths and does not require an unlisted index -change. This entry supersedes the prior entry only where that entry said the -administrative commit creates the evidence page. +commit has the tested commit as its sole parent and fills that existing page. +Its confinement has five paths because the enforced lifecycle contract also +requires the root README's exact derived status summary to move to `Closed`. +This entry supersedes the prior entry's closure and release sequence wherever +the two differ. Release proofs run on the administrative closure SHA before the tag exists. They are `bash scripts/check.sh --docs`, the milestone's final semantic review of the relevant `docs/operator/` and `docs/developer/` pages, and the archive comparison. The archive comparison requires every non-documentation entry -except `SOURCE_IDENTITY` to match the tested archive. Each archive's -`SOURCE_IDENTITY` is validated against that archive's own commit and source -identity instead of being compared byte for byte. +except root `README.md` and `SOURCE_IDENTITY` to match the tested archive. The +README is validated by confinement plus the documentation/status gate. Each +archive's `SOURCE_IDENTITY` is validated against that archive's own commit and +source identity instead of being compared byte for byte. Complete closure outputs remain outside the repository; the administrative commit records their retained-output references and SHA-256 digests on the @@ -5448,3 +5455,24 @@ administrative commit, and the tag does not name evidence produced after tag creation. The sequence is the tested commit, the administrative commit, and the tag. It adds no third commit and grants no closure, tag, release, or publication by itself. + +### Administrative confinement is content confinement — 2026-09-21 + +The maintainer's two-commit closure decision remains unchanged, but the path +test recorded in the two preceding entries was incomplete. Those entries are +historical records; this correction supersedes their path-only descriptions. +The administrative commit is confined to both the five named paths and the +exact allowed region within each path, as the +[single confinement rule](milestones-technical.md#technical-milestones-confinement) +defines. Release review retains the complete zero-context patch, maps every +changed byte to that table, and reconstructs the two marked status files from +the tested bytes plus their canonical replacement blocks, requiring +byte-for-byte equality. A path-only diff and a passing `mix loopex.status` +cannot prove those properties. + +The root README comparison in the archive step relies on that exact +marked-block reconstruction plus the documentation/status checks. The evidence +scaffold's headings and prose, every pre-existing context-map byte, and all +bytes outside the two status markers remain fixed. This correction changes +what the release confinement proof must retain; it grants no closure, tag, +release or publication. diff --git a/docs/developer/milestones-technical.md b/docs/developer/milestones-technical.md index f280b4498..9f938c9b3 100644 --- a/docs/developer/milestones-technical.md +++ b/docs/developer/milestones-technical.md @@ -33,9 +33,10 @@ to the Milestone Register table in `docs/plans/README.md`. The register's Gate column is history: a milestone run under the retired gate machinery links its gate file, and a new milestone's entry is `—`. That row is the pair's index — the index's Files section states the naming convention and indexes nothing. -Then run -`mix loopex.status`; it refuses until the Current Status capsule holds the -values it derives for an `Open` milestone and prints what it expects. +Then construct the Current Status capsule from the register under the status +contract and run `mix loopex.status`; it refuses until the capsule holds the +derived values for an `Open` milestone. The task reports pass or failure; it +does not print replacement bytes. Names: lowercase ASCII letters and digits separated by single hyphens, `M` followed by digits, or a version-shaped numeric slug such as `1.0` or `v0.1`; @@ -86,9 +87,12 @@ At the **tested implementation commit**, which is the closure candidate: in `docs/evidence/README.md`. The scaffold has the final headings and fields, marks results pending, and claims no run that has not happened. 3. The closure matrix, run **from** that commit: `bash scripts/check.sh` under - the floor pair - (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`, - with its own `MIX_BUILD_ROOT`), and `bash scripts/check-release.sh` once on + the floor pair with an absolute, pair-specific build root and the + higher-priority build-path variable removed + (replace `NAME` with the milestone name in + `env -u MIX_BUILD_PATH MIX_BUILD_ROOT="/absolute/retained-work/NAME-otp27-build" + mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`), and + `bash scripts/check-release.sh` once on the current pair with the credential and pinned Node; CI already holds the current-pair fast check for the candidate. Each run's revision, platform, toolchain, result and measured duration is retained outside the repository @@ -96,7 +100,8 @@ At the **tested implementation commit**, which is the closure candidate: administrative commit fills the existing `docs/evidence/NAME-closure-runs.md` scaffold with those identities and digests, including the tested archive manifest's retained-output reference - and SHA-256 digest. The runs are *of* the tested commit, and that commit + and SHA-256 digest, and every plan-required outcome value whose final field + or row was predeclared `Pending` in the tested scaffold. The runs are *of* the tested commit, and that commit cannot carry its own later results. 4. An independent reviewer reads the candidate for outcome compliance, correctness, test honesty, public impact, security and rollback; blocking @@ -107,15 +112,18 @@ At the **tested implementation commit**, which is the closure candidate: commit** moves the register row to `Closed`, fills the plan's Closure row, records the maintainer's words in `docs/developer/agent-context-map.md`, and fills the evidence-page scaffold - with the runs of step 3 and the review of step 4. `mix loopex.status` derives the - `Closed` capsule; run it and copy what it expects. + with the runs of step 3, the review of step 4 and every predeclared + plan-required outcome value. Construct the canonical + `Closed` capsule from the register under the status contract and run + `mix loopex.status` to validate it; the task does not print replacement + bytes. **The two SHAs, and what each one carries.** | | Tested implementation SHA | Administrative closure SHA | | --- | --- | --- | | What it is | The candidate the checks ran on and the reviewer read | The commit that records the decision | -| What it changes | Everything the milestone implemented | The four paths below, and nothing else | +| What it changes | Everything the milestone implemented | Only the five paths and the allowed regions within them below | | What names it | Every run on the evidence page, and the review | The register, once `Closed` | | Its evidence | The runs of step 3, taken from it | None of its own; it is a record, not a claim | @@ -124,8 +132,10 @@ sole parent. An intermediate or merge commit would add a third revision to the closure and could hide changed-then-restored paths from an endpoint diff. The plan's **Closure row names the tested implementation SHA** — the candidate -the packet was assembled from — with the content digests closure rows have -always carried. It does **not** name the administrative SHA, for the reason +the packet was assembled from — with the exact Bound-bytes syntax defined by +the plans register: for a gate-less milestone, +`candidate <40-hex>; concept sha256:<64-hex>; technical sha256:<64-hex>`. +It does **not** name the administrative SHA, for the reason the whole split exists: that row *is* the administrative commit's content, and a commit cannot contain its own hash. An earlier revision asked the row to name both, which is the same impossibility as asking one commit to carry runs @@ -139,16 +149,18 @@ the evidence reads the tested SHA out of the Closure row, where it is. **The confinement, stated once and referenced everywhere else.** The -administrative closure commit touches **exactly these four paths**: +administrative closure commit touches **exactly these five paths, and only the +named region within each path**: | Path | What it carries | | --- | --- | -| `docs/plans/README.md` | The register row, moved to `Closed` | -| `docs/plans/.md` | The plan's Closure row, naming the tested implementation SHA and the content digests | -| `docs/developer/agent-context-map.md` | The maintainer's closure disposition | -| `docs/evidence/-closure-runs.md` | The existing scaffold, filled with the run identities, results, measured durations, retained-output references and SHA-256 digests of step 3; the tested archive manifest's retained-output reference and SHA-256 digest; and the independent review result, retained-output reference and SHA-256 digest | +| `docs/plans/README.md` | The exact `` register-table row, moved to `Closed`, and the bytes between `` and ``, replaced only by the canonical status block `mix loopex.status` derives from that row | +| `docs/plans/.md` | Only the plan's Closure governance-table row, naming the tested implementation SHA and the content digests | +| `docs/developer/agent-context-map.md` | One newly appended, dated subsection recording the maintainer's closure disposition; every pre-existing byte remains unchanged | +| `docs/evidence/-closure-runs.md` | Only the scaffold's designated `Pending` value fields and placeholder rows. The tested candidate predeclares every label, heading and row slot that closure will fill, including the generic run identities, results, measured durations, retained-output references and SHA-256 digests of step 3; the tested archive manifest's retained-output reference and SHA-256 digest; the independent review result, retained-output reference and SHA-256 digest; and any plan-required outcome fact, review, demonstration identity, source inventory or measured observation. The administrative commit replaces only those `Pending` values or placeholder cells; it adds no label, heading, row or prose. Every non-placeholder byte remains unchanged | +| `README.md` | Only the bytes between `` and ``, replaced by the exact derived status block for the register's `Closed` state; every byte outside the markers remains unchanged | -and **nothing else**. That is the whole rule; every other passage in this +and **nothing else in those files or the tree**. That is the whole rule; every other passage in this repository that bounds the administrative commit refers here rather than restating it, because three different formulations of it — "changes nothing the runs covered", "the register row, the Closure row and the context-map @@ -156,14 +168,24 @@ entry", "nothing outside `docs/`" — coexisted in five documents and disagreed about whether the evidence page had a home. The tested candidate creates and indexes that page; the administrative commit only fills it. -All four are under `docs/`, so "the administrative commit touches nothing -outside `docs/`" is a **consequence** of this rule rather than a second rule, -and that is how the release step states it. `git diff --name-only -..` against those four paths is the content check; -`git rev-list --parents -n 1 ` must show exactly -` `. Anything else in the parent line or the diff means -the evidence no longer covers the tree, and the packet is reassembled from a -new implementation SHA. +Path membership is only the first half of confinement. Inspect the complete +`git diff --no-ext-diff --unified=0 .. -- ` and map every changed byte to the table above. Reconstruct each marked +status file by taking its tested bytes and replacing only its named marked +block with the canonical block derived from the administrative register, then +require byte equality with the administrative file. The same review requires +the exact register row, Closure row, appended context-map subsection and +scaffold placeholders to be the only other changed regions. Retain the full +patch and that five-row content-confinement result outside the repository under +a stable reference and SHA-256 digest. `mix loopex.status` inside +`check.sh --docs` separately validates the derived status values; it is not a +substitute for proving that bytes outside their markers did not change. + +`git diff --name-only ..` must name exactly the five +paths, and `git rev-list --parents -n 1 ` must show exactly +` `. Any extra parent, path, hunk or byte outside an +allowed region means the evidence no longer covers the tree, and the packet is +reassembled from a new implementation SHA. **The closure matrix runs once, from the tested implementation SHA**, and the administrative commit re-runs nothing. The pre-tag release proofs and their @@ -184,10 +206,10 @@ creating the tag: | Step | Command | What a failure means | | --- | --- | --- | -| Confine the administrative commit | Require `git rev-list --parents -n 1 ` to return exactly ` `, then compare `git diff --name-only ..` with [the four paths](#technical-milestones-confinement) | An extra parent, an intermediate commit, a missing path or any other path means the tag would publish a tree outside the two-commit closure contract; the release stops and the packet is reassembled. Because all four paths are under `docs/`, a passing check also establishes that nothing outside `docs/` moved, which is what makes the three re-proofs below sufficient | +| Confine the administrative commit | Require `git rev-list --parents -n 1 ` to return exactly ` `; compare `git diff --name-only ..` with [the five paths](#technical-milestones-confinement); inspect and retain the complete zero-context patch; map every changed byte to its one allowed region; and reconstruct both marked status files from the tested bytes plus the canonical administrative status blocks, requiring byte equality | An extra parent, intermediate commit, missing or extra path, hunk outside a named region, changed pre-existing context-map byte, changed scaffold structure, or changed byte outside either status marker means the tag would publish a tree outside the two-commit closure contract. `mix loopex.status` proving the values does not prove this byte confinement. The release stops and the packet is reassembled | | Re-prove the documentation structure | `bash scripts/check.sh --docs` on `COMMIT` | The administrative commit's own documentation changes are not green; fix the candidate and assemble a replacement administrative commit | | Re-prove documentation meaning | Run the milestone's final semantic documentation gate on the relevant `docs/operator/` and `docs/developer/` pages at `COMMIT` | The operator and developer accounts disagree with each other, the plan, the accepted ADRs, or the implemented behavior; fix the candidate and assemble a replacement administrative commit | -| Re-prove the archive identity | Recompute the archive manifest from `COMMIT`. Compare every entry outside `docs/`, except `SOURCE_IDENTITY`, with the manifest retained for the tested SHA. Require exactly one root `SOURCE_IDENTITY` in each archive and validate it against that archive's own commit and source identity | The published bytes are not the closed bytes outside `docs/`, or an archive identifies the wrong source. The entries under `docs/` and the two `SOURCE_IDENTITY` payloads are expected to differ. What this catches beyond step 1 is an archive that includes or excludes differently from the tree; `.gitattributes` can make that change without a path appearing in `git diff` | +| Re-prove the archive identity | Recompute the archive manifest from `COMMIT`. Compare every entry outside `docs/`, except root `README.md` and `SOURCE_IDENTITY`, with the manifest retained for the tested SHA. Require exactly one root `SOURCE_IDENTITY` in each archive and validate it against that archive's own commit and source identity | The published bytes are not the closed bytes outside the confined regions, or an archive identifies the wrong source. Entries under `docs/`, the derived root README and the two `SOURCE_IDENTITY` payloads are expected to differ. The preceding content-confinement proof covers every permitted documentation hunk and the README's exact marked-block replacement. This comparison catches archive inclusion or exclusion changes that `.gitattributes` can cause without a path appearing in `git diff` | Nothing else is re-run. There is no second suite, no second release check and no second provider credential: the tested tree and the administrative tree diff --git a/docs/developer/milestones.md b/docs/developer/milestones.md index af3d9de23..31d6fc973 100644 --- a/docs/developer/milestones.md +++ b/docs/developer/milestones.md @@ -63,7 +63,8 @@ then present the packet to the maintainer. The maintainer closes it; the register moves to `Closed`, the plan records the closing decision and the tested implementation SHA, and the closing commit fills the existing evidence page with the run and review identities, retained-output references, and -SHA-256 digests. Use the `close-milestone` skill. +SHA-256 digests, plus every plan-required outcome field or placeholder the +tested scaffold predeclared. Use the `close-milestone` skill. **Closure names two commits, because one cannot name itself.** The checks and the review are of a **tested implementation commit**; recording the closure is @@ -71,12 +72,14 @@ a further commit that necessarily comes after, and that the evidence therefore cannot have been taken from. The tested commit carries the indexed evidence-page scaffold; the administrative commit fills it with runs *of* the tested commit. Earlier wording created the page in the second commit, which also required its -index to change and broke the four-path confinement. +index to change and broke the confinement rule then in force. So a closure carries the **tested implementation SHA**, which the runs and the review name, and the **administrative closure SHA**, which records the decision as the tested commit's direct child. That second commit is -**confined to four paths** — the register row, -the plan's Closure row, the context-map entry and the evidence page — which +**confined to five paths and the exact administrative region in each** — the +register row and generated status block, the plan's Closure row, an appended +context-map disposition, the evidence scaffold's designated placeholders and +the root README's marked derived-status block — which the [technical companion](milestones-technical.md#technical-milestones-confinement) states once and everything else refers to. A closure whose administrative commit touches anything else is not administrative, and its evidence is @@ -99,22 +102,26 @@ package, installer or publication is its own decision with its own evidence. **The tag names the administrative closure SHA**, which is the commit that carries the closure record and therefore the tree a reader who fetches the tag gets. That is only safe because the administrative commit is confined to -[its four paths](milestones-technical.md#technical-milestones-confinement), -and the release step verifies that rather than trusting it — -`git diff --name-only ..` against exactly those four. -A diff that reaches anything else means the tag would publish source the -closure evidence does not cover, and the release stops. All four are under -`docs/`, so a passing check also establishes that nothing outside `docs/` -moved; that is a consequence of the confinement, not a second rule. +[its five paths and allowed regions](milestones-technical.md#technical-milestones-confinement), +and the release step verifies that rather than trusting it: a name-only diff +must name exactly those five, and the retained complete patch must map every +changed byte to the named region in its file. A diff that reaches anything +else means the tag would publish source the +closure evidence does not cover, and the release stops. The root README is the +only confined path outside `docs/`; it is reconstructed as the tested file with +only its marked block replaced, then checked byte-for-byte as well as by +`check.sh --docs`, including that command's `mix loopex.status` step. **Three re-proofs run before the tag exists, and none is a second closure.** The administrative tree differs from the tested one only in documentation, so `bash scripts/check.sh --docs` runs on the administrative SHA. The final semantic documentation gate then reads the relevant `docs/operator/` and `docs/developer/` pages from that same SHA. The archive manifest is also -recomputed there. Every entry outside `docs/`, except `SOURCE_IDENTITY`, must -match the tested archive entry. Each archive's `SOURCE_IDENTITY` differs by -design and must name that archive's own commit and source identity correctly. +recomputed there. Every entry outside `docs/`, except the root `README.md` and +`SOURCE_IDENTITY`, must match the tested archive entry. The README is validated +by the marked-block confinement proof and documentation/status checks. Each archive's +`SOURCE_IDENTITY` differs by design and must name that archive's own commit and +source identity correctly. This comparison catches archive inclusion or exclusion changes that `.gitattributes` can cause without a path appearing in the commit diff. No suite is re-run, no release check is re-run, and no provider credential is diff --git a/docs/developer/verification-technical.md b/docs/developer/verification-technical.md index 284ca0c1d..b16142f86 100644 --- a/docs/developer/verification-technical.md +++ b/docs/developer/verification-technical.md @@ -20,8 +20,8 @@ Concept: [Three stages](verification.md#concept-verification-stages). | --- | --- | --- | | Change, while editing | `mix test `, `mix format`, `mix compile --warnings-as-errors`; the client Stop hook runs format, the dependency budget and the adapter check | Seconds | | Change, before merge | `bash scripts/check.sh --select` in hosted CI on the branch; a read-only review of `git diff main..` | 12 min 54 s and 12 min 38 s on the hosted runner at the final M4 candidates; on the Mac 287 s at the final candidate `d738ec7` with a warm build and ten applications at once (346 s at `031554c`, before the bound and concurrency work), against 870 s Mac and 809 s Linux in the sequential shape it replaced; 18 s before the suite starts | -| Close | An indexed evidence-page scaffold at the tested SHA; `bash scripts/check.sh` under the floor pair (`mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`); `bash scripts/check-release.sh` once on the current pair | Release check: 149–163 s on Linux, 12 tests | -| Release | Before tag creation: confine the administrative commit's diff to its four paths; run `check.sh --docs` and the final semantic operator/developer documentation gate on that SHA; recompute its archive manifest; compare every non-documentation entry except `SOURCE_IDENTITY` with the tested manifest; validate both archive identities | The documentation-scoped check alone: 12–13 s on the Mac at this revision, warm build, plus the semantic review and manifest comparison. No suite and no release check | +| Close | An indexed evidence-page scaffold at the tested SHA; `bash scripts/check.sh` under the floor pair (replace `NAME` with the milestone name in `env -u MIX_BUILD_PATH MIX_BUILD_ROOT="/absolute/retained-work/NAME-otp27-build" mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`); `bash scripts/check-release.sh` once on the current pair | Release check: 149–163 s on Linux, 12 tests | +| Release | Before tag creation: confine the administrative commit's complete retained patch to its five paths and each path's exact allowed region, reconstructing both marked status files byte-for-byte; run `check.sh --docs` and the final semantic operator/developer documentation gate on that SHA; recompute its archive manifest; compare every non-documentation entry except the derived root `README.md` and `SOURCE_IDENTITY` with the tested manifest; validate both archive identities | The documentation-scoped check alone: 12–13 s on the Mac at this revision, warm build, plus the confinement review, semantic review and manifest comparison. No suite and no release check | `check.sh` step order and cost: warning-free compilation 1 s (warm), formatting 1 s, repository structure 11–14 s (`scripts/check-bootstrap.sh`: client @@ -59,7 +59,9 @@ Evidence retention: the tested candidate carries an indexed scaffold under `docs/evidence/`. The administrative closure commit fills that page with the candidate, each closure run's platform, toolchain, result, measured duration, retained-output reference, and SHA-256 digest. It also records the independent -review result, retained-output reference, and SHA-256 digest. The +review result, retained-output reference, and SHA-256 digest, and fills every +plan-required outcome field or placeholder predeclared by the tested +scaffold. The [M4 closure-runs page](../evidence/M4-closure-runs.md) illustrates the identity and result layout; new closures add the external reference and digest. Complete logs stay with the maintainer outside the repository; the page records diff --git a/docs/developer/verification.md b/docs/developer/verification.md index 9f4eef954..89e124346 100644 --- a/docs/developer/verification.md +++ b/docs/developer/verification.md @@ -33,13 +33,15 @@ Technical depth: [What each stage runs](verification-technical.md#technical-veri | --- | --- | --- | --- | | Change | Is this change whole, and is it what it claims to be? | While editing: the focused tests for the changed boundary, `mix format`, a warning-free compile. Before merge to `main`: `bash scripts/check.sh` green in hosted CI on the branch, plus an independent review of the diff against its stated purpose. Every merge, not only milestone closures. | A red check or a blocking review finding; the integrator merges only a green, reviewed candidate | | Close | Did the milestone deliver its outcomes? | An indexed evidence-page scaffold in the candidate; `check.sh` once under the floor toolchain pair (the current pair is already proved by CI on every change); `bash scripts/check-release.sh` once; the outcome-to-evidence map in the plan; an independent review of the candidate. All checks and review use the **tested implementation SHA** once. The **administrative closure SHA** fills the scaffold and records the decision without re-running the matrix | The maintainer, who closes it or does not | -| Release | Is the source about to be tagged the closed source? | Reuse the closure evidence when the source is unchanged. On the **administrative closure SHA**, verify the four-path confinement, run `check.sh --docs`, run the final semantic gate over the relevant operator and developer documentation, and compare the archive with the tested archive outside `docs/`, except for separately validated `SOURCE_IDENTITY`. Retain these proofs outside the repository and put their results, retained-output references, and SHA-256 digests in the annotated tag at creation. No suite and no release check run twice | The maintainer's separate release decision | +| Release | Is the source about to be tagged the closed source? | Reuse the closure evidence when the source is unchanged. On the **administrative closure SHA**, verify the five paths and each path's exact allowed region from the complete retained patch, including byte-for-byte reconstruction of both marked status files; run `check.sh --docs`; run the final semantic gate over the relevant operator and developer documentation; and compare the archive with the tested archive outside `docs/`, except for the derived root `README.md` and separately validated `SOURCE_IDENTITY`. Retain these proofs outside the repository and put their results, retained-output references, and SHA-256 digests in the annotated tag at creation. No suite and no release check run twice | The maintainer's separate release decision | The fast check is the everyday gate. It is credential-free, needs no network, and is the same command locally and in CI, where it runs as `check.sh --select` on every push to `main` and every pull request. The release check is the expensive one: it spends a provider credential, needs the pinned Node, and runs the attended operator workflow, so -it runs at closure, at release, and whenever a change touches what it proves. +it runs once at milestone closure and whenever a change touches what it proves +during development. An unchanged-source release reuses that closure evidence +and runs only the pre-tag administrative-SHA proofs in the table. ### A changed guarantee selects its checks diff --git a/docs/plans/M5-technical.md b/docs/plans/M5-technical.md index 6114136ac..ba6fc3860 100644 --- a/docs/plans/M5-technical.md +++ b/docs/plans/M5-technical.md @@ -20,21 +20,24 @@ lists tests that exist once the milestone implements it; requiring those tests *before* acceptance would mean no decision could ever be accepted, since implementation waits on acceptance. So acceptance means the maintainer has read the design and the obligations it commits to, and those obligations — -renamed in every one of the five to **implementation and milestone-closure +renamed in all five proposals in this planning set, including deferred ADR +0035, to **implementation and milestone-closure evidence** — are discharged at Outcome closure, where the exact-diff tests and the security review belong. The repository status check reads the links in this section, so a decision named only in prose declares nothing. | Decision | Acceptance point | What its acceptance settles | | --- | --- | --- | -| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and any migration left open for a separate decision | -| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or any of those core changes lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023 unchanged, generation 2's methods, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, marker-first startup, race-free attach with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle eviction and bounded session pages, and every residency number below | +| [ADR 0031](../adr/0031-daemon-grade-store-selection-and-migration.md#concept) | Before the daemon opens a state root, so before workstream 2 lands | The existing local adapter as the daemon's store for `0.2.0`, with the 256 MiB log capacity, 4 MiB frame ceiling, full retention, `store_capacity_exceeded` refusal, the capacity-as-store-loss consequence, the shared crash-reclaimable host placement lock preserving ADR 0008 across early Store-marker release, explicit stale-writer recovery and the operator root-retirement procedure documented; a daemon-grade adapter and its Store/journal-format migration left open for a separate decision, while ADR 0032 owns the daemon-index compatibility import | +| [ADR 0032](../adr/0032-daemon-attachment-residency-and-replay.md#concept) | Before the socket is bound or any of those core changes lands, so before workstreams 1 and 3 | The Unix-domain-socket transport reusing ADR 0023's framing, initialize handshake, admission, snapshot/event/progress records and existing input limits unchanged; generation 2 adds `writer_epoch` to its request records and adds its enumerated methods, records, errors and daemon/residency limits; inherited connection-local boolean replacement mapped to core's exact target, durable existence established by core's read-only query rather than by attaching or resuming, refusal of a generation-1-only client, owner-only peer access, the bounded socket path, placement-lock-then-marker startup, race-free multi-attachment holders with at-least-once contiguous delivery, the resident window, daemon-owned output buffers, detachment at the last emitted cursor, idle-observer eviction with controller-lease exemption, and a versioned bounded daemon index with explicit legacy import and bounded pages | | [ADR 0033](../adr/0033-collaboration-controller-lease-and-takeover.md#concept) | Before any admission check is written, so before workstream 4 | One daemon-owned controller lease per session held in daemon memory with a fresh opaque writer epoch per grant, admission that binds holder connection, held state, unexpired term and epoch together, explicit takeover, cross-process abort through the core's own cancellation, and no authority from content, metadata or order | -| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as an opaque token bound at composition beside the registry handle and **resolved per invocation**, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside the sender that writes the credential frame, after the child proves nonce, codec version and build manifest digest and before the invocation frame; custody and registry ownership, rotation, the guardian-enforced deadline, `:unavailable` on lost custody or registry with no reconstruction, and every failure outcome; no credential environment read anywhere in the adapter's library tree, with `provider_bridge` reading none at all and the launcher's ADR 0019 scrubbing enumeration kept exactly where it is, which is what leaves ADR 0019 unamended; the re-pointed credential-plane proofs and the security review as acceptance points | +| [ADR 0034](../adr/0034-provider-credential-handoff-over-bootstrap-channel.md#concept) | Before the adapter's credential resolution changes, so before workstream 5's credential item | The credential as an opaque token bound at composition beside the registry handle and **resolved per invocation**, routed by a host-owned registry that holds routing only, resolved from a host-owned custody process only inside a sender whose exact supervised argument is token-free. Managed setup registers an inert guardian with Core, obtains its authorization acknowledgement, then starts and adopts an inert sender and obtains its adoption-complete acknowledgement before initialize. Each supervised start requires the exact start-proxy result and exact child acknowledgement in either order, followed by proxy `DOWN`, before the next gate. The sender parks until exact provider readiness, then installs mandatory runtime-bound trace exclusion and a linked, sender-monitoring sink before it receives the token or channel context. Managed mode allocates one absolute invocation deadline before either supervised start, never resets it and, after registration, adoption and initialize, applies it to provider launch/readiness, sender release, exclusion, token routing, custody resolution and the credential-frame write. Every accepted completion and next release rechecks `now < deadline`; a queued completion consumed at or after the instant loses, and the timer only prompts that check. Direct mode has no Core gate and carries its request's same pre-launch absolute instant through inherited-session clearing, sink installation, routing, custody and frame write. Either expiry is `:timeout`, while lost custody, registry or capability is `:unavailable` with no reconstruction. No credential environment read occurs anywhere in the adapter's library tree, with `provider_bridge` reading none at all. ADR 0034 narrowly supersedes ADR 0019's environment-as-sender-source, ready-sender-resolution, raw-spawn and sole-guardian-ownership clauses for managed calls: managed guardian and token-free sender are direct temporary `owner_workers` children, while Direct mode retains the raw linked-and-monitored sender. It retains ADR 0019's provider child/Port/OS-guard/private-channel topology, launch-time enumeration and scrubbing, failure teardown and forensic disclaimer; the re-pointed credential-plane proofs and the security review are milestone-closure obligations | ADR 0031 decides one thing, the `0.2.0` local-adapter selection and its -documented limits. It prescribes no successor engine, experiment or migration; -those are named as open questions there and settled by their own decision. +documented limits. It prescribes no successor engine, experiment or +Store/journal-format migration; those are named as open questions there and +settled by their own decision. ADR 0032 separately owns the daemon-index +compatibility import. M4 owns interactions, transfers, the foreground server and observability. An inherited defect is reproduced at the exact base and repaired at its owner; a @@ -47,13 +50,13 @@ Concept: [Scope](M5.md#concept-plan-scope). | Component | Owns | Cannot own | | --- | --- | --- | -| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — the dispatcher monitors the attaching process and drops its attachment on `DOWN`, which is what replaces the supersession this change removes, with `Control`'s own attachment and repetition state held per holder rather than per session — the holder pid owning the entry and releasing it on `DOWN`, the handle's `attachment_id` resolving it at the command path, which discards its caller because under the daemon that caller is a relay task and not the holder**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need, before any message is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded `quiesce/1` that settles every active coordinator or names what it could not — executing in its caller's process, not in `Control`, which is on every coordinator's commit path — together with the one coordinator change it needs in two halves, a drained abort pausing where cleanup would have begun and its commit presented once rather than retried on an ambiguous answer, and the one new `Control` read it enumerates from — a transient, core-internal drain context carrying the Store handle `Control` holds beside each entry's status, coordinator pid and owner, because `%Loopex.Runtime{}` carries a supervisor and a token and no store**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | -| `loopex_protocol` | Generation-2 records, validators, schema and vectors | Daemon behaviour or lease semantics | -| `loopex_store_local` | The unchanged local adapter, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals and its writer marker, which it takes at start and releases in its own `terminate/2` — so the daemon owns the Store *process* and stops it last in an orderly shutdown, and a store loss releases the marker before the daemon can act | Any daemon fact, lease, index or residency state | -| `loopex_daemon` | Marker-first process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the session index with its recorded-entry bound and its bounded pages, attachment residency and the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a durable record or a durable method | -| `loopex_composition` | The edge-assembly sequence, and the one new public function that runs it in the caller's process, calls the caller's `interrupt` checkpoint before each edge, and returns the edges — or, on an interrupt or a failure, returns the ones it has already started so the caller can unwind them — used by `RuntimeOwner` and by the daemon's owner | Daemon lifetime, ownership of what it assembles, or any knowledge of a daemon | +| `loopex` | Durable session truth, the race-free attach barrier and cursor, independent concurrent attachments to one session **and their release — `Control` and the dispatcher each hold a holder-to-attachment-set keyed by attachment identity and own the monitor or explicit release notification they consume; one holder `DOWN` drops that holder's full set and its transfers; `replace_attachment_id` names the exact target and enters the request binding; and a narrow internal attach-for-holder call lets a relay task perform the attach while the connection pid remains the stable holder**, the read-only session-existence query, **`Loopex.Trace.exclude_self/2`, which installs both the match-specification exclusion ADR 0030 names and the process-level exclusion its callees need before any token is delivered, and the `Loopex.Trace.Entry` clause that redacts a keyword list's values under their own keys**, **the bounded, single-use `quiesce/1` that settles every active coordinator or returns `{:error, :runtime_unavailable}` — executing in one private monitored phase-owner process, not in `Control` or by changing its caller's flags, because `Control` is on every coordinator's commit path — whose first Control call installs a terminal create/resume/attach/ordinary-route gate and projects each entry's status, coordinator pid and owner; whose drain-specific coordinator call closes ordinary command admission before proposing the abort; whose drained abort pauses where cleanup would have begun and presents its commit once rather than retrying an ambiguous answer; whose later census is read-only under the same gate; and whose one-shot fence-mode `SessionCoordinator` becomes the sole serial writer for one abort-status recovery followed by one `advance_owner` and, if its result is ambiguous, one exact fence re-presentation after the ordinary coordinator is gone; no Store handle leaves core**, **`create_session_detailed/3` and `resume_session_detailed/3`, the two runtime-side functions carrying `disposition` and `control_entry` beside the unchanged create and resume**, the per-attachment event-count dispatcher queues, cancellation and recovery | A lease, a transport, a byte limit, residency policy or any daemon fact | +| `loopex_protocol` | The existing `LoopexProtocol.Session` generation-1 compatibility facade and the daemon-only `LoopexProtocol.Session.V2` contract, each with its own zero-arity metadata, negotiation, validators, schema and vectors | Daemon behaviour or lease semantics | +| `loopex_store_local` | The local adapter's unchanged durable format, private port shape and marker cleanup, its 256 MiB log and 4 MiB frame ceilings, its `store_capacity_exceeded` and `store_log_too_large` refusals, plus the missing retained-create read projection through existing `runtime_command/2`; that projection adds no durable byte, callback arity or result-union member — so the daemon owns the Store *process* and stops it last in an orderly shutdown, while host placement exclusion remains outside the adapter | Any daemon fact, lease, index or residency state | +| `loopex_daemon` | Placement-lock-then-marker process and socket lifetime, existence validation by calling core's query rather than by attaching or resuming, the peer-credential check, generation-2 negotiation, per-connection socket output buffers, the resident window and aggregate byte ceiling, attachment residency and eviction, the in-memory controller lease and writer-epoch check, the versioned durable daemon index with its file-size and recorded-entry bounds, offline legacy import and bounded pages, the one-way activation ceiling, and diagnostics | Store or coordinator internals, a second loop, policy selection, host identity, a journal record or a durable session method | +| `loopex_composition` | The edge-assembly sequence; the `LoopexComposition.Placement` crash-reclaimable host lock extracted from `LoopexCli.Placement` without changing its path, record or recovery protocol so the CLI and daemon use one mechanism; and the one new public `LoopexComposition.start_edges/2` function that validates the existing host option set, runs in the caller's process, calls the caller's optional `interrupt` checkpoint before each edge, and returns `{:ok, edges}` or `{:error, reason, partial_edges}` with exactly the started keys and optional transfers absent rather than `nil` — used by `RuntimeOwner` and by the daemon's owner | Daemon lifetime, ownership of what it assembles, or any knowledge of a daemon | | `loopex_app_server` | The foreground stdio server unchanged, sharing the protocol mapping the daemon reuses, and its use of `with_runtime/2`, which M5 does not change | Daemon lifetime or residency | -| `loopex_cli` | `loopex daemon` with its readiness line, signal handling and exit classes, `loopex attach` with its roles, takeover presentation and cursor reconnect, the live `loopex sessions --daemon` form beside the unchanged offline one, and the host-side credential custody and registry it composes | Normative lease or session semantics, and any change to the released offline `loopex sessions` | +| `loopex_cli` | `loopex daemon` with its readiness line, signal handling and exit classes; `loopex attach` with its roles, takeover presentation and cursor reconnect; the live `run`, `resume` and `sessions` forms beside offline forms whose released grammar, session-driving semantics and output remain stable; and Outcome 6's governed host-side credential custody and registry composition | Normative lease or session semantics, or any other change to released offline command behavior | | `loopex_llm_reqllm` | The credential handoff, its sender, the token it accepts, the launcher's unchanged ADR 0019 scrubbing enumeration, the `req_llm` version floor, the re-pointed credential-plane proofs and the provider suite's concurrency | Any host credential policy, any new credential scope, where a host keeps the bytes behind a reference, or anything outside the adapter | | `clients/node` | Socket connection, observer following and takeover presentation for the independent client | Normative semantics | @@ -61,7 +64,7 @@ Concept: [Scope](M5.md#concept-plan-scope). its dependency-budget change, and the narrow core attachment change — the first half of workstream 1, which the daemon's attach path needs before it can be proved, and which is why workstream 1 is numbered first in the concept -pair. Then marker-first daemon lifetime and the socket over the local adapter, +pair. Then placement-lock-then-marker daemon lifetime and the socket over the local adapter, workstreams 2 and 3, which may run together once the application exists. Then the collaboration lease, workstream 4, on that base. Then the daemon-side residency, replay and backpressure that sit above the core change, the second @@ -70,7 +73,7 @@ the independent Node client. Then the documentation and the source-archive proof, workstream 6, at the end because it describes what the others built. Then independent review of the closure candidate. -Prove lifetime, refusal of a second daemon at the marker, shutdown on store +Prove lifetime, refusal of a second daemon at the placement lock, shutdown on store loss, capacity refusal, reopening under the foreground server after an orderly stop, independent simultaneous core attachments, snapshot-then-contiguous delivery, stale-epoch refusal, takeover and cross-process abort before the @@ -86,10 +89,10 @@ to the integrator, who resolves them rather than either writer: | Shared surface | Why both reach it | | --- | --- | -| Host composition — `apps/loopex_composition`, `apps/loopex_app_server/lib/loopex_app_server/host.ex`, `apps/loopex_cli` | The credential item makes every host compose a routing registry, a custody process and the token bound in its model options, and delete the operator's variable; the daemon *is* a new host composed the same way, and `host.ex:221` is where the variable is read today | -| The integration scripts — `scripts/check-release.sh` and its fixtures | Workstream 5 selects the real-provider lane; the daemon workstreams add `loopex_daemon` to `release_apps` and the Linux cross-uid case | +| Host composition — `apps/loopex_composition`, `apps/loopex_app_server/lib/loopex_app_server/host.ex`, `apps/loopex_cli` | The credential item makes every host compose a routing registry and custody process, bind the token in model options, bind the mandatory tracing capability after runtime start, and delete the operator's variable; the daemon *is* a new host composed the same way, and `host.ex:221` is where the variable is read today | +| The integration scripts — `scripts/check-release.sh` and its fixtures | Workstream 5 replaces the shared real-provider application lanes with an eight-row fresh-BEAM manifest; the daemon workstreams add the daemon's real-provider, Node, long-bound and Linux cross-UID cases | | Provider and credential documentation under `docs/operator/` and `docs/developer/` | Workstream 5 adds the operator credential sentence and the host-composition note; workstream 6 rewrites the same pages for the daemon | -| Closure evidence — `docs/evidence/M5-closure-runs.md` and `docs/evidence/README.md` | Every workstream's runs, the security review and the demonstration are retained on one page | +| Closure evidence — `docs/evidence/M5-closure-runs.md` and `docs/evidence/README.md` | One page records every workstream run's identity, result, retained-output reference and digest, plus the corresponding references and digests for the security review and demonstration; complete outputs and reports remain outside the repository | So workstream 5 takes its own worktree like every other writer, and the integrator sequences those four surfaces. What is true without qualification @@ -108,8 +111,8 @@ every mutating method; request identities never enter journals. uncontrolled session and grants nothing. Attach and acquire are independent and their order is not fixed, as ADR 0033 settles it: the constraint is on the first mutation, which is admitted only when the sending connection holds the -lease, its epoch matches and that connection holds a controller-capable -attachment. The single exception is `session.resume` on a verified dormant +lease, its epoch matches and that connection holds a live attachment for the +pinned session. The single exception is `session.resume` on a verified dormant session, which the holder may send before attaching. "Verified" means verified by core's read-only existence query, not by having attached or resumed already: acquire validates existence with that query and refuses an unknown ID with @@ -117,13 +120,19 @@ nothing created. The lease record lives in the daemon's memory, keyed by session, for as long as that session has a lease or an acquisition; one owner process per session serializes its lease transitions with its admission handoff, and that owner's failure is **scoped -to its session**: the controller's connection is sent `control_owner_lost` -and closed with its attachment, -every observer stays, and the next acquisition starts a fresh owner with a -fresh epoch. What keeps a successor's call from overtaking an older one is the -**admission relay**, a fixed daemon process that holds a ticket for every core -call and blocks the replacement's first grant until that session's tickets -settle. ADR 0033 fixes both rules. For +to its session**. A granted holder is sent `control_owner_lost` and closed with +its attachment. Every other acquire or release claimed by owner loss, and every +pending or queued mutation claimed before promotion, receives the same code as +a correlated refusal and keeps its connection; a promoted mutation remains +relay-owned to its real result. A free or retiring owner with no claimed +operation has nobody to notify. Every observer stays. Successor start waits for +mirror pop, classification acknowledgement and terminal holder-close or +correlated-refusal settlement, while its first grant waits for predecessor +retirement completion and tickets before minting a fresh epoch. What keeps a successor's call from overtaking an older one is the +**admission relay**, a fixed daemon process that holds a ticket for the ten +core-call kinds that affect the drain, records the ticket and starts its +monitored task before acknowledging, and blocks the replacement's first grant +until that session's mutation ticket settles. ADR 0033 fixes both rules. For every existing-session mutation the daemon checks the requesting connection identity, the current epoch, the held state and the unexpired term together before forwarding to core; an epoch alone is not authority, and every epoch is @@ -143,12 +152,24 @@ Concept: [Verification stages](M5.md#concept-plan-verification). | Outcome | Witness | What must be proved, beyond ordinary unit tests | | --- | --- | --- | -| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the line appears on `stdout` only after the marker is held and the socket is bound, permission-checked and accepting, a client connecting the instant it appears is served, and each of a held marker elsewhere, a failed socket permission check and an exceeded index bound prints no readiness line and exits non-zero with its own class. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the listener stopped accepting and the **admission cut** taken as one synchronous call in which the relay closes admissions and answers at once, followed by the owner's **bounded wait** for the tickets already inside core — proved by **two witnesses that must differ on one surface, the connection's own reply stream**: a ticketed mutation admitted in the instant *before* the cut is asserted to have settled before the drain begins, and a `session.prompt` sent on a still-open connection *after* it is asserted to be refused `daemon_stopping` with nothing admitted and no journal record — with `session.create`, `session.attach` and `artifact.read_chunk` sent after the cut refused the same way, the first two being the cases that would fail if either bypassed the relay and the third proving the refusal covers an unticketed method too; a case that holds a resume's replay past the wait's bound and asserts the stop **proceeds**, with that session reported `unsettled` from an `:acquiring` `Control` entry and fenced; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its three parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then every cancellation released together — each abort being the command a client's own `session.abort` writes, under a `command_id` core mints fresh per session per drain and asserted to be one no client sent, and **every enumerated session** fenced by a committed `advance_owner` — settled ones included — so no transaction for any of them can commit afterwards, each refused `:stale_owner_epoch`, and the answer's **three** lists — settled, unsettled and absent, with an `:unavailable` entry asserted to land in `absent` and be fenced and an `:awaiting_owner_barrier` entry asserted `unsettled` and fenced — plus its per-session `fences` map, asserted `:committed` for the settled session as well as for the unsettled one — and `:not_needed` only where the fence's own fresh enumeration holds no entry at all — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and the `budget_ms` core derived reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and at the deadline terminating **every** enumerated coordinator and only then fencing every one of those sessions, in that order, before it answers — **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated, one bounded best-effort `daemon.stopping` naming `operator_stop` attempted per open connection — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next daemon removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped last, and exit `0` — with the foreground server opening the same root immediately afterwards, which is what proves the marker was released, and the journal differing from what an abrupt death at the same instant would have left by exactly the admitted-abort record and the fence record per enumerated session, both of which the released reader replays without a migration, with the unresolved transaction and its own fence identical. **Store loss is a separate fail-stop, not that sequence**: the Store terminates itself and releases the marker before the daemon can act, so the daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by a second daemon starting on that root with no stale marker to recover. An active session progresses with zero attachments. An orderly stop releases the writer marker and records nothing false; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves the marker path explicitly: the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous starts on one root resolve at the writer marker with exactly one listener and the loser never touching the socket. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose directory entry was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving dormancy releases attachments and never a coordinator. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, and the next command for it returns core's own refusal forwarded unchanged, with the daemon adding and interpreting nothing; a root whose directory exceeds the recorded-entry bound refuses at start; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose directory entry was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `present`, the daemon repairs the directory entry and index row, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch is what activates the session — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the directory entry and index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; a directory write that fails during activation is reported to that client, leaves the session usable and reachable by ID while absent from `session.list`, and is written by the retry the next time the live daemon holds that ID — right after activation, on a later command for the session, or when a client reaches it by ID; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | -| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `Session.generation()` equals each served generation's manifest `/generation`, for generation 1 and generation 2 alike, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` and `daemon.notice`, the second carrying `index_write_failed` for an activation whose directory write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`) — eight where artifact transfers are enabled and seven where they are not, and **neither `listener_lost` nor `connections_lost`**, which have no vector for the same reason: the listener is what would have written the record and the connection registry owns the buffer-control interface it would have been written through, so no client ever receives either reason, plus an uncorrelated `error` vector for `control_owner_lost` and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable or undecodable peer credential closing the connection before initialize — all in the fast check, which needs no second user — with the real cross-uid refusal and the same-uid success carried by two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on its single run, which closure requires to be on Linux, and where the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. Frame, fragment, malformed-input and over-long socket path refusals with distinct stable reasons, the path cases binding at the derived bound and at one byte past it on each platform the release check runs. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check | -| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. Connection identity, epoch, held state, unexpired term and controller-capable attachment checked together before core admission or any durable write, including a known current epoch sent by an observer — the gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate. Takeover only after release or expiry, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` frees the lease at once, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed while a mutation is in flight taking neither the daemon nor any other session down: that session's controller connection sent `control_owner_lost` and closed with its attachment, its observers still attached on their own connections and still receiving, the relay's ticket for the in-flight mutation retained, the replacement owner's first grant held until that ticket settles, and the previous holder's delayed command refused on both the holder and the epoch check. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in arrival order, one at a time**, the second held in its lease owner until the first ticket resolves, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; and the ordering inside the ticket callback asserted on the surface that shows it: at the instant the acknowledgement arrives at the caller, the relay's own state is read in-VM and asserted to hold **both** the ticket row **and** a live task pid for that ticket, and the task is asserted to be monitored rather than linked, so a relay that died next would leave the call running rather than take it down. A relay that replied before spawning passes the first assertion and fails the second, which is the difference the case exists to make. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | -| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, **`apps/loopex/test/session_detailed_results_test.exs`**, **`apps/loopex/test/session_listing_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only session-existence query answers exactly one of the closed set `present`, `absent`, `invalid_id`, `store_unavailable` and `unexpected`, from a fresh process against a real root, with one case per result. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. `unexpected` is injected by a stub answering outside the set. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `present`; the other four fail closed with no attachment, no lease and no activation, and name four distinct reasons, so an unreadable store is never reported as an unknown session. Several core attachments to one session remain independent when one detaches or backpressures. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then the furthest-behind session's window, then detachment — including the case where zero-attachment windows alone consume the ceiling. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | -| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then starting and printing the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` activating a dormant one through acquire, resume with a fresh command ID, attach; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a controller whose renewal fails continuing as an observer and sending no further mutation; a reconnecting controller retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | -| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, **`apps/loopex_cli/test/`, `apps/loopex_app_server/test/`, `apps/loopex_daemon/test/`** for ADR 0034's host-owned-process cases — read-once, environment deletion and a redacted crash report, each proved at the host whose composition it is about — and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it. Every row of ADR 0034's failure table resolves to its closed-set atom and retains no copy: `:no_token` for an absent token, `:invalid_token` for a malformed one, `:unavailable` for a token with no registry row, a gone registry, a dead custody process and a malformed successful reply, and each of `:missing`, `:expired` and `:oversized`, a term outside the closed set reported as `:unavailable`, and a custody process blocking past the invocation deadline, where the **guardian** kills the sender and reports `:timeout`, asserted distinct from every refusal so the guardian can tell a refusal from a silence and asserted to bound the invocation whatever the custody process does. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — carrying the **same** credential, because one runtime composes one token, which is the point the two-runtime isolation case below carries and this one does not. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a tracing capability that is absent, malformed or bound to a dead process is asserted to **refuse** the invocation with `:unavailable` before the token is routed, the reversal of the earlier 'absent proceeds' rule, with the composition-time refusal asserted separately, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer is asserted to receive **no raw trace message from the sender process at all** — not for `:gen_tcp.send/2`, not for anything — while a non-excluded control process performing the same `:gen_tcp.send/2` in the same session does produce one, so the case cannot pass by tracing nothing; the canary appears in no message and no entry. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential bytes or token appear anywhere — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The ordering claim is proved rather than asserted, and it is proved at the **process boundary** rather than inside the body: what the bridge spawns holds no token, no registry handle and no credential — `set_on_spawn` traces a spawned closure's **entry call**, so a token in that closure is exposed before any line of it runs — and it receives the token by message only after its exclusion is established and confirmed. The tracer is asserted to receive **no raw trace message from that process carrying the token at any point**, entry included, while a non-excluded control process spawned with the same closure shape does produce one; `exclude_self/2` returns before the token is sent, and a session started concurrently with it yields no message from the sender either way round. The keyed shape is proved as defence in depth, not as the mechanism: each of the three bridge functions is called with a one-byte credential and no captured entry contains that byte — which matters because size alone does not protect, since running `Entry.render/2` shows a bare or tuple-wrapped credential of 1, 40, 51 or 64 bytes rendered verbatim and only a credential-keyed value placeholdered at every size. A further case asserts the three function identities, so no tier can pass vacuously. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion and its subsequent traced call produces nothing while a non-excluded control call produces a message, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case subsumes the old within-one-runtime concurrency witness, which a composition-bound token makes meaningless: two invocations of one runtime necessarily carry the same token, so what has to be proved independent is two *runtimes*. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | +| 1 | `apps/loopex_daemon/test/session_lifetime_test.exs`, `apps/loopex_store_local/test/writer_lock_holder_test.exs` | A real daemon operating-system process per state root. The startup ordering and its readiness line: the bounded write is launched only after the placement lock and Store marker are held and the socket is bound, permission-checked and listening under a parked listener. The lifecycle sentinel serializes handled `SIGTERM`, helper result or deadline, the owner's exact component-fatal notice and its post-success clock-and-liveness-checked release authorization; only release authorization lets the sentinel send exact `begin_accept`. Forced orders prove stop, component fatal or readiness failure consumed first leaves the gate parked even when the completed line is already visible, while release first opens it and a later signal or component exit takes the running path. A client connecting before release is served only after that exact gate event. Killing the parked listener after its startup acknowledgement and ordering the owner's fatal notice before release authorization selects `listener_start_failed`, leaves the gate parked and creates no client or wire state, including when readiness success is already visible; the paired order in which the sentinel's exact send wins selects running `listener_lost`. Forcing the first accept operation to fail immediately after the exact `begin_accept` release selects `listener_lost` with no client; forcing a later accept failure while one initialized client remains attempts `fatal:listener_lost` to that client, and neither path selects startup-only `listener_start_failed`. Each of a held placement lock, a held Store marker, a failed socket permission check and an exceeded index bound releases no gate and exits non-zero with its own class. Killing the command process after owner `init/1` returns but before its exact `:go` proves the unlinked owner exits by `owner_start_gate_ms: 5_000` with no placement handle, Store pid, socket or child acquired; the startup-only gate clock never enters `T_orderly`. Post-exclusive-create WriterLock failures are forced separately: no Store pid is returned, a complete residual follows verified stale recovery, a partial residual refuses as unverifiable, and the daemon maps the originating failure to `store_writer_acquisition_failed` without touching the socket. Orderly shutdown on `SIGTERM` sent to the daemon, and on `SIGINT` sent to the launcher that forwards it as `SIGTERM`: the relay **admission cut** taken through one ref-tagged exchange, asynchronous in process mechanics and synchronous only in sequencing, that closes admissions and answers at once, followed by the registry's acknowledged `transport_closing(cut_ref)` gate, the listener's kill and exact reap, and EOF close plus reap of the complete marked provisional/uninitialized set, all within the one transport-cut deadline; a peer accepted in the interval between relay cut and registry gate may reserve a provisional slot but never initializes, while no reservation or promotion passes the registry gate. Then follows the owner's **bounded admission wait** in which only the frozen pre-cut origin rows may promote or settle — proved by distinct surface witnesses: a ticketed mutation admitted in the instant *before* the relay cut settles before the drain begins; `session.prompt`, `session.create`, `session.attach` and `artifact.read_chunk` presented on an already initialized connection after that cut each refuse `daemon_stopping` with nothing admitted and no journal record; and an accepted but uninitialized peer receives EOF without a protocol record; a pre-cut `artifact.read_chunk` whose waiting worker claims its permit and receives `go` before the cut is held across the admission-wait bound, remains `executing` through quiesce, then ends exactly once as `connection_lost` at the later connection/worker barrier and changes neither Control nor durable bytes; its paired worker held before the claim loses `shutdown_cancelled` at the deadline and is proved never to dispatch, while the same claimed read released inside the bound completes normally; killing its bounded request worker and, separately, closing its peer while a dispatcher read is held clears the exact connection-incarnation permit, kills remaining request workers and returns permit and attachment counts to baseline; a paused lease owner forced on both sides of pending-ticket promotion proves connection loss before promotion starts no task while promotion first keeps the accepted slot closing to the real result; 512 occupied incarnations with 32 active origins each hold the 513th peer out, never exceed 16,384 origins or tasks under reconnect churn, and a healthy maximum-population seal completes within the selected teardown bound while a suspended relay selects the fatal deadline path. Every relay barrier — `cut`, `freeze_lease_ops`, `quiescing`, `seal_after_quiesce` and `tearing_down` — separately proves exact-ref acknowledgement, stale and wrong-reference rejection, exact malformed response, suspension, and another owned component's `EXIT` while the barrier is pending; an exact acknowledgement consumed just before its deadline advances once, while one consumed at or after it is cleanup-only. Cut, freeze or quiescing failure enters bounded fail-stop without core quiesce; seal or tearing-down failure reports no operator-stop success. At an expired barrier the first fatal class is latched and the 35-second watchdog started before untrappable relay kill, with no out-of-phase reap wait and later `EXIT` cleanup-only; activation-cut cases forcing both serialized mailbox orders: create and resume handled first finish their Store and entry-or-dormant decision, with any `:acquiring` entry reported `unsettled` and fenced and a post-commit owner-start failure proved to have no writer, while the early quiescing barrier handled first refuses the call before Store access with no entry or durable record; a prompt held after Control routing but before `SessionCoordinator.command/3` is released only after the coordinator's drain call returned `rejected_no_active_run`, then refuses and writes no prompt admission; and one asserting the acknowledgement returns while a prompt commit is still in flight, which a cut that waited for settlement would have failed into `relay_lost`; then core's `quiesce/1` running its three parts — every active session's abort durably admitted and paused **before any** cancellation begins, asserted from journal order across two sessions, then all paused cancellations released together only when every admission is committed or definitively `rejected_no_active_run`, with a failed or ambiguous admission case asserting that **none** are released and the stop proceeds to termination and fencing — and maximum-population clock witnesses: a suspended initial Control gate returns `runtime_unavailable` inside its first 5 seconds with no worker; 64 admission workers held through the 65-second work cutoff are killed and reaped by 70 seconds with no cleanup released; 64 cleanups share one release instant and advance at the earlier of all-terminal or their one root-derived deadline; 64 status calls hit their 5-second work cutoff and return to worker baseline by 10 seconds; 64 coordinators under a suspended supervisor cause direct coordinator and blocked termination-worker kills at 325 seconds with every exact exit consumed by 330 seconds before fencing; and 64 fence paths begin cancellation at the 125-second work cutoff with every pid and operation absent by the 130-second outer deadline — each admitted abort being the command a client's own `session.abort` writes, under the deterministic `drain_abort` command ID derived from that session ID and its pre-admission owner epoch, with journal version retained only in the Store binding, and one fence procedure for every writer-started key in the frozen census after every enumerated coordinator is dead — settled ones included — while a never-started key is omitted from the projection and result and starts no worker — with a committed fence preserving the earlier settled or unsettled classification, a stale refusal reported conservatively as `unsettled` with `:superseded`, a bounded head-read failure carrying `{:unknown, :no_head}`, and an unresolved proposed fence carrying `{:unknown, :fence, head}`; the answer's **three** lists — settled, unsettled and absent — and its per-session `fences` map are asserted together — with **the case that would have failed before**: a settled session's straggler commit, held inside the Store and released during the Store stop while it is still alive, asserted refused `:stale_owner_epoch` and absent from the journal, and both the root-specific `budget_ms` and fixed `fence_budget_ms: 130_000` reported on the daemon's stop line beside its `drain_id` — no shutdown-specific field on the record, the cause reaching the operator through `daemon.stopping` and `stderr` instead — driving each session's in-flight work to settle under that session's own grace within a drain budget derived from `cancellation_bounds/1`, and after all released cleanups become terminal or the shared deadline is reached, directly killing every coordinator still alive after the concurrently issued `DynamicSupervisor.terminate_child/2` calls, awaiting every `DOWN`, and only then fencing every writer-started session and omitting every key outside the writer-domain projection, in that order, before it answers — including a suspended-supervisor witness proving the direct coordinator kills complete, fence mode starts outside that supervisor, and resuming it releases no queued late start, and **both halves asserted**, with `settled` read on the surface that decides it — the coordinator's `{:session_status, owner}` reply, asserting the aborted run is in neither `active_run_id` nor `pending_work_ids`: a dispatched tool effect that settles carries its ordinary terminal fact in the journal, and a session whose cancellation finished but whose terminal is not yet committed at the budget is asserted **`unsettled`** rather than settled, and one held past the budget leaves its coordinator dead at the instant it is reported with **no terminal claimed for that work** — no `cancelled`, no `outcome_unknown` — its ambiguous mutation left as `commit_unknown` and resolved to exactly one outcome when that session is next activated; a `Control` restart during the bounded census is forced under a live retained runtime root with Control and EventDispatcher monitor messages consumed in both orders: direct Control loss and EventDispatcher-first followed by the nonblocking retained-pid checks each name fatal `drain_failed`, claim no census or fence result and take crash-equivalent teardown; a runtime-root exit is forced with root and child signals consumed in both orders and always names `runtime_lost`; an isolated EventDispatcher loss while retained root and captured Control remain exact and live also names `runtime_lost`; the detailed create/resume API is forced with exact `Control` loss before processing and after child start but before reply, returning only outer `{:error, :runtime_unavailable}` to the daemon with no fabricated disposition, control entry or public method reply and forcing fatal `runtime_lost`; outside an orderly stop, killing the exact monitored `Control` child and, separately, the exact monitored `EventDispatcher` child each makes the owner name `runtime_lost`, fail-stop, close controller and observer connections, discard no marker, and permit a clean successor, with the case asserting no stale lease or attachment reservation survives; while the unlinked quiesce helper is held, killing only EventDispatcher with the captured Control proved exact and live and, separately, killing the Store proves the responsive owner latches `runtime_lost` or `store_lost`, terminates the helper, emits no `operator_stop` success and never exits zero; a Store exit injected while the listener's stop-helper wait is active is consumed by that same all-owned-exit loop, latches `store_lost`, sends the exact fatal latch to the sentinel before continuing and suppresses the not-yet-sent `operator_stop` notification; one case completes teardown and exits non-zero, while a paired case kills the owner immediately after the sentinel receives that latch and proves the retained status is `store_lost`, never `owner_lost`, and the absolute 35-second watchdog still bounds halt; the connection registry's deferred bounded `close_all` attempting one best-effort `daemon.stopping` naming `operator_stop` per open connection, consuming its existing monitor `DOWN`s and killing survivors at the shared deadline — asserted received where the transport accepts it and an EOF alone accepted where it does not — the socket pathname **left in place** — no exit path unlinks, and the next verified placement-lock and marker holder removes it before binding, asserted by a following daemon starting cleanly on that root — the Store stopped after every composed edge and completed its release attempt, then the placement helper returned exact `:ok` and normal `DOWN`, and exit `0` — with direct probes observing both exclusion paths absent and the foreground server opening the same root immediately afterwards, which together prove the healthy attempts released them, and, for an active session whose abort and fence both commit, the journal differing from abrupt death by exactly those two records, both replayed by the released reader; separate refused-abort, superseded-fence and unknown-fence cases assert no record the Store did not commit. **Store loss is a separate fail-stop, not that sequence**: the Store's own `terminate/2` attempts marker release before the daemon can act, while ignored removal or parent-sync failure may leave a residual and the host placement lock remains held. The healthy witness separately observes marker absence; a residual follows verified live/dead/unverifiable recovery rather than being called released. The daemon observes the death, refuses service, closes every connection with `store_lost` (or `store_capacity_exceeded` where that was the reason), leaves the socket pathname in place and exits non-zero with that class on `stderr`, attempting no Store stop because there is none to attempt — proved by same-VM and separate-VM contenders refusing `placement_active` before Store or socket access while the predecessor Control lives, followed after its halt by one successor reclaiming the stale placement lock and starting. An active session progresses with zero attachments. A healthy orderly stop observes the writer marker and placement path absent after their bounded best-effort attempts and records nothing false; callback completion alone proves only that an attempt finished, so an ignored removal or sync failure may still leave a residual for verified recovery even when orderly shutdown exits `0`; an abrupt kill followed by restart activates nothing, then activates each session the root records when a client reaches for it, under the same placement identity and with no duplicate effect. The restart proves both exclusion paths explicitly: placement acquisition first refuses a live owner, refuses an unverifiable owner and recovers a dead one; only then the daemon opens with `recover_stale_writer: true`, a marker whose holder is proved dead is reclaimed, a marker whose holder is alive refuses with `store_writer_active`, and a marker whose holder cannot be decided refuses with `store_writer_unverifiable` — all three before the socket path is read, unlinked or bound. Simultaneous daemon starts on one root resolve at the placement lock with exactly one listener and the loser never opening the Store or touching the socket; an independent raw Store writer remains refused at the writer marker. A root driven to the 256 MiB log capacity refuses the append with `store_capacity_exceeded`, the store terminates, the caller sees `commit_unknown`, and the daemon closes the listener and every connection and exits naming the capacity with nothing committed lost; a root whose log is already past that bound is refused at open with `store_log_too_large` rather than opened and truncated. `session.list` returns pages of at most 256 entries in session-ID order with an exact continuation cursor from the daemon index, carrying only session identity, recorded placement identity, `residency` and `controlled`. A session committed to the Store whose daemon-index row was never written — injected at that exact cut — is absent from the listing, still reachable by ID, and present in every listing after the activation that records it. A detached long-running command and a pending admission each cross the idle deadline with every client gone and run to completion, proving idle eviction releases attachments, windows and buffers but never a coordinator; the already-activated session remains `active` for that daemon lifetime rather than becoming dormant. The activation ceiling refuses the 65th activation of a daemon lifetime with `activation_ceiling_reached` and the restart remedy, and the count starts again after a restart because it counts per lifetime; a fresh `session.create` raises the count by one, and at the ceiling a create is refused with that same reason, so creation is proved to spend an activation rather than being exempt from the bound; attach consults the activation set rather than the listing index, proved at the 4,096-entry ceiling where a session activated but deliberately unrecorded still attaches; killing an activated session's coordinator leaves the daemon serving: the listing still reports `residency: active`, which remains true because this daemon did activate that session, attach still succeeds, and the first session-driving mutation returns core's unchanged `session_unavailable`; repeating against that daemon repeats the refusal, while restarting the daemon and retrying `loopex resume --daemon` takes the dormant resume branch, starts one coordinator, reattaches and drives the same durable session successfully; a bounded daemon index whose encoded size, literal header/version, canonical identity encoding, digest or 4,096-entry ceiling is invalid refuses at start without scanning `sessions/`; an exact 726-byte maximal row opens and a 727-byte row refuses as corrupt. Every live index update writes the complete canonical image exclusively to the one fixed mode-`0600` sibling `session-index-v1.next`, retains its opened device/inode identity, syncs and closes it (with close failure treated as pre-rename), renames it over `session-index-v1`, and syncs `daemon/`; a crash before rename leaves the old index plus at most that one temporary, while a crash after the directory sync leaves the new image. Startup and `prepare-index`, only after acquiring the placement lock and then the Store marker, remove that exact temporary only after `lstat` proves a daemon-owned non-symlink regular file; any other shape refuses `session_index_corrupt`, and repeated crashes cannot accumulate names. A write, file-sync, close or rename failure before successful replacement closes the descriptor where still open and removes `.next` only when its owner/type/device/inode still match that attempt, then syncs the directory; successful cleanup proves the prior image is still named and permits an in-process retry. Unverifiable identity or failed removal poisons publication until restart. A directory-sync failure **after** rename instead leaves the complete next image named and adopted in memory, reports `index_write_failed`, poisons later publication without touching either path and admits that a crash may reveal either the prior or next complete snapshot; it never claims rollback. `prepare-index` follows the same split and exits `session_index_write_failed`. Forced pre-rename write, file-sync, close and rename failures prove cleanup then successful retry; a substituted temp identity proves poison and no later write until locked restart cleanup or `session_index_corrupt`; a distinct post-rename directory-sync failure proves the new valid image is live in-process, no rollback or later publication occurs, and abrupt restart accepts one of the two complete valid snapshots. A fresh root creates a mode-`0700` non-symlink `daemon/` directory and persists the exact canonical mode-`0600` empty index before bind, and restart consumes it. A legacy root with session-directory entries and no index refuses `session_index_upgrade_required`, and the explicit offline import is proved to acquire placement then Store, create the canonical bounded index before ordinary startup, stop Store to attempt marker release, and run the same bounded exact-handle placement helper last; exact `:ok` plus normal helper `DOWN` completes only the attempt, while the healthy witness observes both paths absent and immediately reopens, and a residual follows the same verified recovery rules; a failed import before rename removes only a newly created empty daemon directory while a pre-existing directory and index remain byte-for-byte unchanged; a post-rename directory-sync failure leaves the new complete image named, makes no rollback claim and admits either complete snapshot after a crash; at that bound a session reached by ID is activated and not recorded and the listing carries `index_full`; a session committed to the Store whose daemon-index row was never written is recovered both by its ID — validated through core's read-only existence query, with the case asserting the validation itself created no attachment and no durable record — and, by a client that never saw the ID, through ADR 0032's full command-identity sequence run to the end — replay `session.create` with the original `command_id`, core returns the historical result and so the session ID **without starting a coordinator**, the existence query answers `{:ok, :present}` without publishing, control is acquired, and `session.resume` with a fresh resume command ID under the granted writer epoch validates this daemon's placement and activates the session, after which the daemon repairs the compatibility directory entry and daemon-index row — with the case asserting exactly one session in the root, the returned ID equal to the committed one, the replay itself starting no coordinator, the compatibility directory entry and daemon-index row present afterwards, the session listed, a live coordinator existing after the resume with the activation count risen by one, and a later prompt landing on that session and producing its events rather than on a second session or on nothing; an unknown ID answers negative from that query with nothing created, nothing attached and no lease granted; an index write that fails during activation sends that client `daemon.notice` with `index_write_failed`, while a compatibility-directory write failure emits a bounded operator warning; either leaves the session usable and reachable by ID; a pre-rename index failure leaves it absent from `session.list` and, when cleanup proved the fixed temporary gone, a later ID-bearing command retries publication, while a post-rename directory-sync failure leaves the complete next row visible in this daemon but poisons every later publication because crash durability is unknown; a poisoned publisher touches no later temp and waits for restart; bare existence or command-history lookup never publishes; a recorded session the daemon's composition cannot serve refuses at activation by name while every other session in the root activates. After an orderly stop the foreground server and the reference CLI reopen the same root and resume a daemon-created session under the same placement identity with identical replay. No durable method reaches the socket | +| 2 | `apps/loopex_daemon/test/socket_transport_test.exs`, `apps/loopex_protocol/test/public_schema_conformance_test.exs`, `apps/loopex_cli/test/daemon_commands_test.exs` | A raw-byte client over the socket negotiates generation 2 and receives generation 2's **own** exact schema digest, written out as a literal in the conformance module beside generation 1's and different from it by construction: `LoopexProtocol.Session.V2.schema_digest/0` is taken over the generation, the ordered methods, the ordered record families, the ordered error codes and the limits, and generation 2 changes **all five**, so a generation 2 that negotiated generation 1's digest would be reporting a contract it does not serve. Generation 1's **method inventory, record families, error codes and limits** are proved unchanged in the same module — the four inputs it keeps —, so the generation-2 work is proved additive rather than asserted to be — but **exactly one pinned literal moves, and the case asserts the move rather than the old equality**: the `3a17…08f4` **schema digest** at `public_schema_conformance_test.exs:291-292`, because `@generation` is one of the five inputs `schema_digest/0` hashes (`session.ex:192-199`). The **two file digests at `:297-298` do not move**, because the manifests they pin already carry `loopex.experimental/1` and contain no occurrence of the retired name. The generation assertion at `:282` changes with the code it checks. The case asserts the new schema digest against a freshly computed value and asserts the other four inputs are byte-identical to what generation 1 served in `0.1.0`, which is what separates a rename from drift. **And it adds the assertion whose absence let a released discrepancy survive**: `LoopexProtocol.Session.generation()` equals generation 1's manifest `/generation` and `LoopexProtocol.Session.V2.generation()` equals generation 2's, so generation 2's new manifest and pin cannot drift from its code the way generation 1's did. A `0.1.0` client's generations list is refused `unsupported_generation` with nothing created, and the repository's Node client is proved against the new string. A generation-1-only initialize is refused with nothing created. Generation 2's record families include `daemon.stopping` — required `reason` and `message`, with no `retry_after_ms` — and `daemon.notice`, the second carrying `index_write_failed` for an activation whose daemon-index write failed, with literal vectors for each `daemon.stopping` reason a **client can actually receive** — `operator_stop`, `store_lost`, `store_capacity_exceeded`, and one `fatal:` per linked component a client can actually be told about (`runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, `capability_lost`, `relay_lost`, `listener_lost`, `drain_failed`) — ten where artifact transfers are enabled and nine where they are not, and **not `connections_lost`**: listener loss leaves the registry and accepted connections alive to write and close, while registry loss removes the set and buffer-control interface, so only the latter cannot reach a client, plus one correlated `control_owner_lost` lease-operation vector — required `request_id` and `message`, no session state or cursor, and the connection kept open — covering the shared shape used by a claimed acquire, release or unpromoted mutation — and two uncorrelated vectors for granted-holder loss — required `message` and `session_id` in both, no `request_id`, optional `event_cursor` present only for an attached controller, and the connection closed — and three for ADR 0023's `detached` — overflow, aggregate pressure and idle eviction — each carrying `session_id` and the last completely emitted `event_cursor`, each written best-effort and followed by the close of **that connection alone**, and none of them ending the daemon, and vectors for `control_not_held`, `control_pending`, `control_capacity_reached` and `daemon_stopping`, the correlated refusal a command meets after the admission cut — and explicitly none for the startup-phase classes, which carry no vector because no socket exists when they occur and no client can be holding one, and its presence in the digest is what a generation 2 omitting it would fail on. Its delivery bound is proved both ways: a reading client receives the record before the close, and a client that has stopped reading until its 4 MiB output buffer is full receives nothing and is closed anyway, with the daemon making exactly one attempt and never blocking on it. Identical durable identities for the same command corpus through facade, foreground server and socket. Owner-only peer access proved in both layers: the socket's `0700` daemon-owned subdirectory and `0600` socket mode read back after bind, a permissive subdirectory or socket mode refused at start, a subdirectory the daemon does not own refused, a path component below the root that it did not create refused — and a state root at the ordinary `0755` the foreground server creates it with accepted, not refused, because the daemon owns the subdirectory and never re-permissions the root — and an unreadable, short, undecodable or valid-but-mismatched peer credential closing the accepted connection before initialize — all in the fast check, which needs no second user — with two `@tag :cross_uid` cases the release check runs as `mix test --only cross_uid` on Linux. The foreign-user case first proves the verified filesystem modes deny connection in the kernel, then deliberately relaxes the directory and socket modes after readiness so a second foreign connection reaches `accept` and is rejected by decoded `SO_PEERCRED` before initialize; the paired daemon-uid case succeeds. Cleanup restores both modes, and the script asserts exactly two executed tests so neither a zero nor a lone survivor can pass. The accept-time initialize deadline is forced at the child-start/listener-owned cut, on both sides of controlling-process transfer with both transfer results, after listener death between reservation and child start, after listener death following a failed transfer but before close acknowledgement, across registry promotion, and with an initialize completion queued before but consumed after the instant; every late branch closes the exact socket owner, reaps the child and row, returns one slot, and advances no initialization, while each paired just-before branch advances once and timer order changes nothing. Frame, fragment, malformed-input and over-long socket path refusals have distinct stable reasons; the Darwin floor run binds at 103 and refuses 104 while the Linux lanes bind at 107 and refuse 108. A client disconnect recorded as transport loss with no cancellation and no interaction change. The generation-2 vectors are literal bytes with literal verdicts, held beside generation 1's in `apps/loopex_protocol/test/public_schema_conformance_test.exs`, never values generated from the implementation they check. The table-driven CLI case enumerates every accepted and refused live flag, incompatible pair, duplicate, missing value and numeric endpoint; accepted rows assert the exact request sequence, while every parser refusal proves zero socket dials and zero facade calls, and paired offline rows prove the released grammar, session-driving semantics and output stable while Outcome 6's governed host-composition credential custody changes | +| 3 | `apps/loopex_daemon/test/collaboration_test.exs` | One lease per session in daemon memory with observers attached. For the eight existing-session core mutations, connection identity, epoch, held state, unexpired term and a live attachment for the pinned session are checked together before core admission or any durable write, including a known current epoch sent by an observer — the mutation gate's **five conditions** exercised by **six cases** — ADR 0033 maps them one to one — each asserted separately in the daemon's own state and all six asserted to produce the **same** wire answer, `control_not_held` with nothing beyond the envelope, so no refusal is an epoch oracle. Release checks the first four conditions and deliberately has no attachment condition. The one explicit fifth-gate exception is proved beside them: a holder resumes a verified dormant session before attach, while a prompt in the same state refuses `control_not_held`. A holder's own `session.acquire_control` asserted to **renew**: same epoch, moved deadline, `renewed: true` — the branch a rule that refused every held lease would have swallowed. `session.release_control` asserted to carry `writer_epoch`, to refuse `control_not_held` from a non-holder, and to refuse ADR 0023's `invalid_request` — not `control_not_held` — when the field is absent, since a malformed request never reaches the gate; a dormant acquire followed by `session.attach` refusing `session_dormant` then releases successfully without an attachment, and another connection acquires immediately. Live-owner takeover only after release or expiry, and post-owner-loss replacement only after the exact dead-owner pop, owner-loss classification acknowledgement, terminal holder-close or correlated-refusal settlement, and retained predecessor-ticket settlement, with a fresh epoch minted before the successor's first command. A killed controller fenced and its late commands refused. The three ways a controller stops holding, proved separately because the transport cannot tell two of them apart: an explicit `session.release_control` linearizes release at the relay's `result` CAS and reports success only after mirror-clear settlement, while an EOF from a politely closed client and a killed client both wait for expiry, with a takeover refused before the deadline and granted after. A lease owner killed before and after a mutation is promoted takes neither the daemon nor any other session down: a pending or queued origin starts no core task and receives exactly the holder close or non-holder correlated refusal selected by mirror classification; a promoted relay task remains retained to its real core result; observers stay attached and keep receiving; successor start waits for the classification and notification barrier, its first grant waits for both populations to settle, and the previous holder's delayed command is refused on both the holder and the epoch check. Mirror publication is then forced at three cuts — owner death before sending the daemon request, after that request reaches the daemon but before registry commit, and after commit but before reply — plus an ordinary-serving acknowledgement queued ahead of its timer and consumed after the five-second absolute deadline; the last case must atomically latch `connections_lost`, start the fail-stop watchdog, send untrappable `:kill` to the exact registry, await no out-of-phase reap and claim no success. Exact dead-owner mirror pop is forced present, absent, duplicate and racing a successor, proving the linked daemon owner orders any sent install before EXIT, atomically removes only the dead pid/incarnation before successor install, leaves no stale row and preserves the successor mirror against an old exact clear or pop. The relay retains an `owner_lost` winner until it joins the exact owner `DOWN` and mirror-pop classification, with those two facts delivered in both orders. Acquire and release are each killed before and after `pending -> executing`, including after acknowledgement of a pending permit carrying the immutable exact-owner binding but before that owner claims it; the relay must select `owner_lost` from retained data without guessing or leaking the row. A lease-authorized mutation is killed as `pending_ticket`, queued and promoted. An unpromoted mutation starts no core task, while a promoted relay task stays retained to its real core result. For every claimed origin on the returned granted holder, the correlated reply is suppressed and only the uncorrelated close is emitted; any claimed non-holder acquire or release, or claimed pending or queued mutation, receives only the correlated refusal and stays open; a promoted mutation receives its real result. Renewal's direct-result branch is forced both ways: a result sent directly to the relay before EXIT wins `result`, while exact-owner DOWN first wins `owner_lost`. Release uses one daemon-coordinated settlement: witnesses kill the owner before its proposal, after proposal before the relay result CAS, after result before mirror clear, and after clear before reply, proving an owner-loss winner preserves the mirror for classification while a result winner clears it before one correlated success and makes the later pop absent. A separate disconnect after proposal but before result CAS retains `settling(connection_lost, release_ref)`, restores the owner to `held` with its original deadline through the exact cancellation handshake before terminalization, emits no success, leaves no stuck `release_pending` and permits takeover only after ordinary expiry. Disconnects after result wins before mirror clear and after clear before the success attempt prove result-first settlement still clears the mirror, terminalizes the permit and frees the lease when its reply is lost. A live owner paused through `owner_restore_deadline` and an owner restoration acknowledgement queued before but consumed at or after that instant both force exact-owner kill and begin the no-reply cancellation supersede. The supersede acknowledgement, the restored-owner cancellation settlement and the result settlement are each forced just before and at or after `release_settlement_deadline`: a matching first case terminalizes, while an at-or-after acknowledgement is cleanup-only after `relay_lost`, leaving no stuck `release_pending` or settling permit. A missing or malformed relay settlement also selects `relay_lost`. Each cut yields one terminal disposition, drains the predecessor set and emits exactly its selected reply or close. A crossing witness pauses a serving classification before acknowledgement and orders stop consumption and classification completion both ways: classification-first may emit its selected form before the cut; stop-first rebinds the row to the transport-cut instant, makes the private timer and queued acknowledgement cleanup-only, and emits only the later `daemon.stopping`/EOF path. A stop-overlap case kills the maximum live-owner population after the admission cut, delivers each owner `DOWN` and mirror-pop result in both orders, and proves the facts join the already scheduled stop barrier and its one deadline: no per-owner clock starts, no `control_owner_lost` form is emitted, and the measured orderly bound gains no owner-count term. Holder-changing acquisition is forced under both an existing owner and a fresh child at provisional install, on both sides of the recorded actor's `executing -> result` CAS, and on both sides of exact provisional resolution: connection loss first resolves cancelled, discards the existing-owner proposal or kills and reaps the fresh `start_op_ref` child and exposes no epoch, while result first resolves granted and only its acknowledgement exposes the epoch; a later EOF follows ordinary expiry even if the reply is lost. The existing-owner case also consumes the grant report and install acknowledgement before forcing owner DOWN on both sides of the daemon's later result CAS: `owner_lost` first resolves cancelled, awaits exact clear, sends one correlated refusal and leaves the connection open with no epoch, while result first resolves granted and the later owner-loss path closes the exact promoted holder once. The registry refuses provisional install for an incarnation already closing. A pre-cut acquire and release claim immediately before the deadline while relay freeze is forced before and after the daemon timer; idempotent `freeze_lease_ops` returns the same fixed tagged executing-lease set in both orders, and exact teardown CAS yields one disposition per permit without an actor-map scan. Separate cut crossings overtake release settlement before each serving instant. A holder-changing acquisition already settling at the admission deadline is returned as `{:settling_acquire, permit_id, disposition, actor_pid, actor_incarnation, start_op_ref, op_ref}`; a proposed release is returned as `{:settling_release, permit_id, disposition, actor_pid, actor_incarnation, release_ref}`; and a pre-proposal acquire or release whose owner-loss CAS already won is returned as `{:settling_owner_loss, permit_id, class, actor_pid, actor_incarnation, op_ref}` without inventing a release record. Forced acquisition result and connection-loss, release result, restored connection-loss, unresolved connection-loss and owner-loss rows each complete their no-output cleanup by `freeze_deadline`. Fresh executing acquisition is frozen before and after provisional install and must cancel or remove that exact row before child reap; existing-owner acquire and pre-proposal release are held across freeze in result-versus-stop and owner-DOWN-versus-pop orders. The exact mirror is absent, every claimable lease or pending/queued mutation origin is terminal, and a promoted ticketed mutation remains on its real-result path before quiesce. A missing required operation record, wrong tag or missed relay/registry acknowledgement selects the named fatal class before core quiesce. The relay's own two rules, each with a case that would pass without it: a client pipelining two mutations on one connection without waiting has them **admitted in wire-arrival order, one at a time**, the connection itself sending sequence-numbered owner enqueues before its independently scheduled workers can invert, the second held in its lease owner until the first ticket resolves; a forced scheduler inversion releases the later worker first and still observes the earlier ticket first; an earlier mutation followed by `session.release_control` likewise settles before release, with the in-flight admission set asserted to hold at most one entry throughout and a takeover asserted to be granted after exactly one resolution rather than after a queue drains — and the relay asserted never to answer `ticket_outstanding`, the invariant's own refusal, under that same pipelining; killing a queued mutation worker before its ticket cancels the exact owner row and starts no core call, while killing it after ticket acknowledgement retains the ticket and returns the real result without an early generic failure; and the ordering inside the ticket callback asserted on the surface that shows it: before the acknowledgement is emitted, the relay's own state is read in-VM and asserted to hold the ticket row, recorded task pid and monitor, with executor start ordered before reply; at delivery the row and monitor remain until any already-queued result or `DOWN` is consumed, without asserting the fast task is still alive. This includes `session.attach` through the internal attach-for-holder call with the connection pid as holder. A relay that replied before spawning passes the ticket assertion and fails the recorded-start assertion, which is the difference the case exists to make. A daemon restart leaving every session uncontrolled with every earlier epoch refused. A controller abort cancelling work dispatched under an earlier process with a truthful cleanup outcome. The expiry linearization: a mutation blocked inside core across the deadline settles under its own lease while the eligible takeover waits and is granted only after it resolves; the holder's next mutation refused at the deadline; the acquiring request refusing with `control_pending` when its own deadline elapses first; and the holder disconnecting while a mutation is in flight — in every case exactly one of settle or refuse, never both. No control from content, metadata, answers or attachment order. Forward and backward wall-clock jumps changing neither live admission nor takeover timing | +| 4 | `apps/loopex/test/concurrent_attachments_test.exs`, `apps/loopex/test/session_existence_query_test.exs`, **`apps/loopex/test/runtime_quiesce_test.exs`**, **`apps/loopex/test/cancellation_test.exs`**, **`apps/loopex/test/trace_session_test.exs`**, **`apps/loopex/test/session_detailed_results_test.exs`**, `apps/loopex_daemon/test/replay_residency_test.exs` | Core's read-only `session_existence/2` returns exactly `{:ok, result}` where `result` is one of `present`, `absent`, `invalid_id` and `store_unavailable`, or the distinct outer `{:error, :runtime_unavailable}`, from a fresh process against a real root, with one case per result and failure. `store_unavailable` is injected through the controllable fault store the suite already has, `Loopex.M1RuntimeTestStore`, whose `fail_reads/2` hook makes its reads refuse, and through an out-of-set adapter reply that the real Store facade normalizes to unavailable — not by making the root unreadable, which cannot produce that answer on the real adapter: `Loopex.Store.Local` answers `ownership_head` from `state.store`, in memory, so a root that has become unreadable on disk still answers. It is proved to create no attachment, no incarnation, no durable record and no Store write: the root's journal and session directory are byte-identical before and after a run of queries, including for unknown and malformed IDs. Control acquisition proceeds only on `{:ok, :present}`; the other three domain results fail closed with no attachment, no lease and no activation, and name three distinct reasons, so an unavailable store is never reported as an unknown session. A killed or replaced `Control` selects only the outer runtime error; the daemon latches `runtime_lost`, sends no existence refusal and fail-stops. Several core attachments to one session remain independent when one detaches or backpressures, including several attachment IDs under one holder. Targeted replacement removes only the named attachment owned by that holder; an unknown or foreign target refuses, the selector is part of the request binding, and one holder `DOWN` clears both core maps and all of that holder's transfers. A paused-dispatcher churn case proves the daemon does not release a reservation until core acknowledges cleanup and that neither installed map ever exceeds its per-session or per-daemon ceiling. A snapshot anchored at the committed sequence, then contiguous at-least-once buffered and live delivery across the window boundary with no gap. Core is the only replay owner: every delivery case runs a second time with the daemon's resident window disabled and a third with it dropped mid-stream, all three byte for byte identical, so the window is proved to establish no snapshot and no cursor. Aggregate reclamation follows the fixed order ADR 0032 sets — zero-attachment windows by ascending last delivery, then active-session windows by encoded bytes owed, then unattached connections by descending output-buffer bytes and connection-incarnation tie-break, then live-attachment detachment — including the cases where zero-attachment windows alone consume the ceiling and where only initialized but unattached clients hold bytes. The latter presents a pending admission that would make `charged_aggregate + pending_admission_bytes` exceed 512 MiB, leaves those bytes uncharged, reclaims until that sum fits or closes clients without admitting the candidate and without inventing a detach cursor; a suspended initialized peer proves reclamation performs only one non-blocking write/flush attempt, never waits for peer progress, and returns the aggregate to at most 512 MiB after close. A slow observer detached at its last emitted cursor while the controller and the other attachments continue. Per-session and per-daemon limits refusing independently. Idle-observer eviction and reconnect with no missing durable event, any duplicate deduplicated by session ID, sequence and event ID; a quiet controller remains attached while its lease is held and becomes eligible for the same idle eviction only after release or expiry. Retained encoded bytes at or below the 4 MiB output buffer, 16 MiB window and 512 MiB aggregate ceilings, enforced in the daemon-owned stages, exercising 512 attachments and maximum-sized output records separately, with observed process RSS recorded beside the ceilings. Progress coalesced or dropped with counted drops and no journal delay | +| 5 | `apps/loopex_daemon/test/multi_client_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_test.exs`, `apps/loopex_daemon/test/external_socket_workflow_real_test.exs`, `docs/evidence/M5-closure-runs.md` | The operator workflow end to end, each step a command an operator types: `loopex daemon` refusing once per missing or invalid composition input with its own class and leaving no marker or socket behind, then staging a legacy root, running `loopex daemon prepare-index --state-root ` while no host owns it, observing the bounded index and released exclusions, and starting that prepared root with the one-line JSON readiness record; `loopex run --daemon` creating and driving a session; `loopex resume --daemon` taking both exact branches — an already-active session through acquire and successful attach with no resume mutation, and a dormant one through acquire, refused first attach, resume with a fresh command ID and one successful reattach; two created sessions then making `loopex sessions --daemon --limit 1` print exactly one four-field row and a continuation cursor, the next page under `--after` print the other row without duplication, and `loopex sessions --daemon --status` print placement identity, daemon incarnation, socket path, uptime and every current count beside its limit while sending `daemon.status` and no `session.list`; `loopex attach` refused with `session_dormant` at the **attach** step against a session this daemon has not activated, in both roles, while `loopex resume --daemon` acquires that same dormant session, receives `session_dormant` on its first attach, resumes, reattaches once and succeeds — the two asserted together, since refusing dormancy at acquisition would break the resume path; `--take-over` on a dormant session asserted to release its lease before exiting, proved by `loopex resume --daemon` succeeding immediately afterwards rather than refusing `control_held`; a CLI holding a lease attempting an explicit release on every exit path where its transport is still writable, and the killed-client case asserted to differ — no release, the lease waiting out its term, which is what ADR 0033 already fixes; `--after` starting strictly after a sequence and its absence replaying from `0`; a live-socket correlated renewal refusal continuing as observer on the existing attachment and sending no further mutation; a failed renewal send or EOF proving the old attachment is gone, then reconnecting at the retained cursor and reattaching as observer with no mutation; a reconnecting controller that intends to continue controlling retrying acquisition with backoff until its own lease can have expired and then holding a fresh lease with a fresh epoch before any mutation, and the variant where another client took over meanwhile exiting `control_held` rather than retrying against a live holder. From a fresh extraction of the exact candidate — staged with `git archive`, extracted and built outside the checkout — an operator follows the documented prerequisites and commands, supplies workspace, provider and policy inputs, starts the daemon, and drives one session from the reference CLI as controller and the Node client as observer, kills the controller, takes over from the observer and aborts cross-process work. The documented CLI build and the provider companion build both run inside that extraction, on the archive-carried source identity rather than on `.git`, with the missing, unsubstituted-or-malformed, changed-during-build and mismatched-commit refusals each proved and the identity the build reports asserted equal to the commit the archive was staged from. The attended real-provider cases run from that extraction, against the escript it built there. The workflow drives ADR 0030's existing core spans end to end — command admission, commit, effect intent, publication, interaction, and the model, store, policy and executor port callbacks — with the same bounded identity metadata an embedded caller produces, and no event outside that closed inventory is emitted by anything M5 adds. Daemon-internal functions are proved by the daemon's own tests and logs: `Loopex.Trace` traces only processes the runtime owns, flagged with `set_on_spawn` from the runtime's supervisor, and the daemon's listener, connections and lease owners are host processes above the runtime, so no trace-session witness is claimed for them. `VERSION` in the extracted tree is exactly `0.2.0`. Every tracked file under `docs/operator/` and `docs/developer/` has been read against the candidate, including the ones M5 leaves unchanged, recorded as a checklist derived at that commit — `git ls-files -- docs/operator docs/developer`, sorted, one row per path, each row marked *updated* or *reviewed unchanged* — retained with the closure runs. The derivation is over **every tracked file** in those two trees, not only Markdown, and that is deliberate: the gate promises that every file under them was read, so a diagram, a fixture or a data file added later must appear rather than slip through a `*.md` filter that was true when it was written and silently false afterwards. It also avoids a pathspec trap, checked rather than assumed: `git ls-files 'docs/operator/**/*.md'` without `:(glob)` matches nothing at all and would have made the gate pass vacuously. The directory form returns 26 tracked files as of this revision — 18 under `docs/developer/` and 8 under `docs/operator/`, all Markdown today — and the closure checklist states the count it derived so a reviewer can see the list was not empty, with every path in the tree present, no row unmarked, and each finding named and resolved before the closure packet | +| 6 | `apps/loopex_llm_reqllm/test/credential_plane_test.exs`, `apps/loopex_llm_reqllm/test/adapter_test.exs`, `apps/loopex_llm_reqllm/test/provider_retainer_boundaries_test.exs`, `apps/loopex_llm_reqllm/test/provider_startup_boundaries_test.exs`, core's `apps/loopex/test/trace_session_test.exs` and `apps/loopex/test/provider_lifetime_test.exs`, the exact host files `apps/loopex_cli/test/credential_custody_test.exs`, `apps/loopex_app_server/test/credential_custody_test.exs` and `apps/loopex_daemon/test/credential_custody_test.exs`, and `docs/evidence/M5-closure-runs.md` | From the completion of a reference host's composition onward, the configured credential name is absent from the parent VM's environment and no function in the adapter's call path reads the environment for a credential, before, during or after a call — "during" observed from inside the call at child readiness; composition is proved to read the operator's variable once and delete it: each exact composition-owner pid is call-traced only for `System.get_env/1` with `credential_variable/0`, with return tracing disabled, and must produce exactly one name-only call between composition entry and return; the canary is then present in custody and the environment name absent, so zero or two reads fail. The two adapter-preflight failures and every invocation-private failure map to the seven closed atoms and retain no copy: `:no_token` for an absent token; `:invalid_token` for a malformed one; `:unavailable` for immediate guardian start, Core registration, guardian authorization, sender start or adoption refusal, immediate group-leader-sink installation failure, immediate exclusion or Direct-clear failure, a token with no registry row, a gone registry, a dead custody process, malformed route or custody success, any wrong-producer registry or custody reply, a term outside the closed set, or an immediate frame-write failure; each of `:missing`, `:expired` and `:oversized`; and private `:timeout` when managed mode's unchanged absolute deadline is already elapsed at initialize or provider launch/readiness, sender release, sink installation, exclusion, registry lookup, custody resolution or frame write crosses it, or when Direct mode's pre-launch absolute instant is reached during inherited-session clearing or any later step. Exact-key validation is adversarial: canary-bearing extra keys on the token, registry handle, custody reference, tracing capability and custody success map all refuse before their next boundary, and the registry accepts only `{:error, :unavailable}` or an exact valid custody reference while custody accepts only its own three refusal atoms. Managed setup consumes and never resets the absolute invocation deadline. After Core registration, exact guardian authorization, exact sender adoption and initialize, the **guardian** applies that same instant to provider launch/readiness, sender release and every later sender step, kills the sender on timeout, and the harness proves that class distinct from every refusal. Before it accepts provider-readiness, sender, registry, custody or frame completion or emits the next release, it rechecks monotonic `now < deadline`; a timer only prompts that check, so completion queued first but consumed at or after the instant is cleanup-only and cannot extend the invocation. Paired cases at provider readiness, the exact `:bootstrap_result`, every `:credential_phase_result` and every `:credential_phase_continue` consume the same completion on either side of the instant in both mailbox orders and prove that only the before-deadline case advances. Immediate refusal at any managed gate is `:unavailable`; paired sink-install witnesses return `:unavailable` immediately or guardian `:timeout` when blocked, with no token delivered and no sink or sender retained; killing the guardian while the sender is parked or sink installation is blocked kills and reaps the exact sender and sink and returns trace-exclusion state to baseline; a live `owner_workers` start that never answers is an owner-group/runtime liveness failure outside the adapter clock, and the plan makes no adapter-timeout claim for it. The three host suites separately prove that a missing, malformed or extra-key registry handle, or a missing, malformed, extra-key or unbound tracing capability, refuses composition before runtime use or child creation and reverse-cleans every already-started edge. Each binds one capability to runtime A, accepts an idempotent A bind, refuses a B bind while preserving A, and completes a later A invocation. Each also forces custody and registry crashes during canary-bearing requests and refutes the canary across the complete OTP report and owner-observed exit — initial call, last message, state, reason, metadata and emptied log — rather than inspecting state alone; a live registry with no token row instead returns invocation-time `:unavailable`, and those composition refusals do not pretend to be one of the seven invocation atoms. Two resolutions in flight at once is a success case, not a refusal: both invocations complete, each with its own sender, its own custody reply and its own frame — using the same opaque token but independently resolved custody replies and frames, whose credential bytes may differ when custody rotates between replies. Tracing is proved against `Loopex.Trace` including the process-level exclusion M5 adds to it and the `Entry` keyword-key redaction beside it — the token travelling in model `options` through `module.complete/3` (`session_coordinator.ex:3231`) reaches the coordinator **before** the sender exists, so what keeps it out of an entry is redaction rather than exclusion, and the credential bytes after the exclusion point are what the absolute no-trace claim is about; a missing, malformed or unbound tracing capability refuses **composition**, so no invocation or child exists; after a successful bind, an immediately lost capability or unreachable `Control` refuses the invocation `:unavailable` before the token is routed, while an exclusion left unanswered until the guardian deadline yields private `:timeout`, and the decisive case names `:gen_tcp` on purpose: a trace session configured with `:gen_tcp`, `Loopex.LLM.ReqLLM.ProviderBridge` and `Loopex.LLM.ReqLLM.ProviderCodec` runs a real invocation with a **one-byte canary** credential, and the tracer captures the expected token-free sender start entry, whose exact arguments are `sender_ref`, callback owner, guardian and capability — no token, registry handle, socket, nonce, request or credential — and observes only the exact non-secret gate tuples plus `{:begin_bootstrap, sender_ref, guardian_pid, sender_pid, absolute_deadline}` before exclusion. After exclusion the sender returns `{:bootstrap_result, sender_ref, sender_pid, guardian_pid, :ok}`; only that exact success permits `{:credential_context, sender_ref, guardian_pid, sender_pid, token, registry_handle, accepted_socket, invocation_nonce}`. Registry lookup, custody resolution and credential-frame write each report the exact `{:credential_phase_result, sender_ref, guardian_pid, sender_pid, phase, result}` and advance only on the exact `{:credential_phase_continue, sender_ref, guardian_pid, sender_pid, phase, absolute_deadline}`. Wrong-reference, wrong-pid, wrong-phase and changed-deadline injections, plus a stale replay, never unpark, route or write and are cleaned at the unchanged deadline. After a successful frame write the sender drops every credential-bearing logical reference and tail-calls a non-secret final wait **before** it emits the `:credential_frame` result; its exact final continuation permits only normal exit. Only the exact normal sender `DOWN` in that final state, consumed before the retained deadline and followed by the guardian's own clock check, starts the invocation helper. Raise, exit, kill or early normal `DOWN` before expiry is `:unavailable`; the same `DOWN` after confirmed expiry is `:timeout`; and expiry at the final-continuation cut starts no helper. The Trace process is deliberately backlogged before the clear; it consumes the matching `:trace.delivered/2` marker and purges the sender's pending-call keys before the exclusion acknowledgement, after which it spawns and installs the sink from the untraced sender and receives **no further raw trace message from either sender or sink pid**, including none for `:gen_tcp.send/2` or `ProviderBridge.sink_loop/1`, while a non-excluded control process performing the same call in the same session does produce one, so the post-exclusion negative cannot pass by tracing nothing; the Direct path likewise awaits every named-session delivery marker and the legacy `:erlang.trace_delivered/1` marker before spawning its sink from the cleared sender and acknowledging. Releasing those markers after 5 seconds but before the Direct request's pre-launch absolute instant succeeds; holding them through that instant returns `:timeout`. At blocked clear, custody and frame-write cuts, abnormal or killed Direct-guardian exit reaps its raw linked-and-monitored sender and sink with no late frame; normal cleanup stops and awaits both. Managed and Direct sender exit return pending-call state and monitors to baseline; the canary appears in no captured raw trace message, rendered entry or IO request outside the one permitted custody reply. Under the **default** configuration no trace entry names `ProviderBridge.route_credential/2`, `receive_custody_reply/2` or `write_credential_frame/2`, the tracer receives no raw trace message for them and no credential byte appears in any captured raw trace message, rendered entry or IO request outside the one permitted custody reply — because `modules/1` expands a namespace through the application's own module list and the adapter is not a `:loopex` module. The token can traverse core in model options before the sender exists; the existing structured redaction proof, rather than sender exclusion, keeps it out of rendered entries. The ordering claim is proved rather than asserted, and it is proved at the **process boundary** rather than inside the body: the guardian's exact initial argument is `{guardian_ref, callback_owner_pid, stop_reference}` and the sender's is `{sender_ref, callback_owner_pid, guardian_pid, tracing_capability}`; neither holds a token, registry handle, request, socket, nonce or credential. For each child the case forces exact `start_proxy_result` and child acknowledgement in both mailbox orders plus all three legal placements of proxy `DOWN` after its same-sender result, requires the callback to monitor the child from its first pid disclosure and consume the proxy's normal `DOWN` before the next gate, kills guardian and sender after either disclosure and before transfer completion to prove `:unavailable`, and proves both supervisor refusal and a caught starter exit reverse-clean an acknowledged child without overlapping a second proxy. `set_on_spawn` traces a spawned closure's entry call, so the proof observes both exact tuples, both acknowledged ownership gates, the sender parked until child readiness, and token delivery only after exclusion is established and confirmed. The tracer is asserted to receive **no raw trace message from that process carrying the token at any point**, entry included, while a non-excluded control process spawned with the same closure shape does produce one; `exclude_self/2` and its delivery barrier finish before the sender spawns its sink; the sink inherits no trace flags, both pids are verified clear before the token is sent, and a session started concurrently with exclusion yields no message from either pid in either order. Every IO request during the real credential invocation is captured and proved credential-free; a separate non-secret IO canary after token delivery is swallowed by that sink and appears in no sender/sink raw trace or host Logger output, while the credential canary remains absent from every captured raw trace message, rendered entry and IO request outside the one permitted custody reply. Process and MFA exclusion are the sole credential-byte trace control: ADR 0030 placeholders retain value-derived size and digest, so even a placeholder for a one-byte credential is a 256-guess oracle. The one-byte canary must therefore appear in no captured raw trace event or rendered entry at all. The keyed custody map remains the exact validation/dataflow shape, not a safety fallback. A further case asserts all three exact function identities and separately proves keyword-key placeholdering only for the opaque 128-bit token before the sender exists, so no tier can pass vacuously or against the wrong signatures. The exclusion mechanism itself is proved in core's own suite: a process flagged by `:set_on_spawn` inheritance calls the exclusion, a forced tracer backlog is drained through the delivery marker before acknowledgement, its subsequent traced call produces nothing while a non-excluded control call produces a message, `:calls` retains no pending start, return-bearing state is purged on process death, and all monitors and pending keys return to baseline, at both toolchain pairs. The registry lookup is proved to carry no credential. Two runtimes composed in one VM, each with its own registry, custody and token, are proved isolated: a token minted for one answers `:unavailable` in the other, so tokens do not cross runtimes, and neither runtime's child — nor either child's diagnostics — ever observes the other's credential. That case complements the within-one-runtime concurrency witness: one runtime uses the same opaque token for both calls, but each call resolves independently and may receive different rotated bytes; two runtimes additionally prove registry isolation. A registry killed under a composed runtime makes every later resolution through that handle answer `:unavailable`, and the adapter is proved not to retry, wait or rebuild — recomposition is the only repair. A guardian forced to crash after its initialize message leaks neither the valid token nor registry-incarnation canary through its Task/supervisor report, exception or exit reason, stack, messages, state, metadata, log or owner-observed exit. Every re-pointed case of `apps/loopex_llm_reqllm/test/credential_plane_test.exs` passes with its assertion unchanged in meaning: version refusal and bootstrap refusal before any credential, late delivery after expiry impossible, rotation between invocations, two live credentials in one VM, sink loss, one child's loss not poisoning another, ordinary host messages and returned reasons, every child Logger form and metadata, and the four crash-report cases. The child-environment witness inside the version-refusal and bootstrap-refusal cases — the child's recorded `entry-env` marker refuting `Adapter.credential_variable()` — holds unchanged. `provider_startup_boundaries_test.exs` counts the actual custody protocol: exact readiness produces one resolution, while killing the real pre-entry process produces zero resolutions, zero dispatches and no canary in diagnostics. The 65,536-byte ceiling case in `provider_retainer_boundaries_test.exs` is re-pointed too, because that module delivers its credential through `System.put_env` in its `setup` and again in the case body; that invocation's own custody process holds the oversized value instead. The drift-protection case in `adapter_test.exs` survives strengthened, with an exact allowlist: `[]` for `provider_bridge.ex`, the arity-zero enumeration and only that for `provider_launcher.ex` because it is ADR 0019's first-image scrubbing rather than a credential read, `provider_worker.ex`'s two non-secret crash-dump names, and `[]` everywhere else. Because the launcher's read survives, the case also asserts its *use*: the enumeration's result flows only into the Port's removal list, every name is mapped to `false`, none is compared against `credential_variable/0`, and no value reaches the sender, the frame or any caller. Its scan is widened from one `System.get_env(...)` expression to every route an environment read can be written — `System.get_env/0`, `/1` and `/2`, `System.fetch_env/1` and `fetch_env!/1`, `:os.getenv/0`, `/1` and `/2`, `:os.env/0`, and indirect application through `apply/3` or a captured function — each unpinned route refuted outright. The `req_llm` move to `~> 1.24.0` — pinned to that minor, not to `~> 1.24`, so the reviewed diff is the version actually built against — lands as its own reviewed change before the credential change, with the reviewed changelog diff across the intervening releases named in the commit, the adapter and streaming-conformance suites green, and the *existing* real-provider case at closure run against it. It adds no call path: nothing in M5 calls anything `1.24.0` makes newly reachable, and no second provider, second credential or new release-check case enters this milestone. It is explicit M5 scope, separate from ADR 0035 and not conditional on it. A security review by someone other than the implementer is recorded. The eleven modules — of the thirteen the application runs serially, the count measured by loading them rather than by globbing `test/*.exs`, which misses `test/support/provider_entry_test.exs` — are then converted to run concurrently one at a time, each kept only while its application's suite stays green, any module that stays serial keeping its reason beside it, and the measured duration is recorded beside the M4-closure baseline as evidence about the change rather than a threshold | + +The reference CLI witnesses are named separately because they prove command +ownership and parser effects rather than a core invariant: + +| Exact file | Exact case | Lane | What it proves | +| --- | --- | --- | --- | +| `apps/loopex_cli/test/daemon_commands_test.exs` | `daemon startup grammar resolves exact inputs before effects` | fast | The startup and `prepare-index` grammars, their distinct accepted inputs, flag-over-environment precedence, empty and invalid values, the startup-only two-policy registry, duplicate and positional refusals, zero placement, Store, socket or component work on every parser refusal, status `1` for those refusals, and silent status-`0` import success with no readiness line; operational import failures assert the reused class/status map, including `session_index_corrupt` for a legacy/index identity conflict | +| `apps/loopex_cli/test/daemon_commands_test.exs` | `live command grammar separates host and request flags` | fast | Every accepted and refused live-form flag and combination, numeric endpoints, the offline/live split, exact run/resource/follow-up/steer request sequences, and zero socket dials or facade calls on a parser refusal | +| `apps/loopex_daemon/test/external_socket_workflow_real_test.exs` | `a controller and observer complete the documented daemon workflow against a real provider` | release | The already selected exact manifest case exercises `loopex daemon prepare-index` on a staged legacy root, daemon startup, `loopex run --daemon`, both the already-active and dormant branches of `loopex resume --daemon`, controller and observer `loopex attach`, and the reference CLI's one-page listing, continuation and status output over the socket, so every changed operator command has one discoverable release workflow rather than a separate unselected case | +| `apps/loopex_daemon/test/session_lifetime_test.exs` | `listener failure class follows the begin-accept cut` | fast | Killing the parked listener after its startup acknowledgement and ordering the owner's exact fatal notice before release authorization, including after readiness success is visible, selects `listener_start_failed`, leaves the gate parked and creates no client or wire state; when the sentinel sends exact `begin_accept` first, the first accept error and a later error with one initialized client both select `listener_lost`, and the later case attempts `fatal:listener_lost` to that client | +| `apps/loopex_daemon/test/session_lifetime_test.exs` | `startup dispositions share one sentinel arbiter` | fast | The lifecycle sentinel consumes both orders of stop versus completed success and deadline, and component-fatal notice versus completed success and deadline. Stop first exits `0`; fatal first retains its class; readiness failure first retains `readiness_write_failed`; each leaves the gate parked even if the line is visible and makes later candidates cleanup-only. Release authorization first makes the sentinel send exact `begin_accept`, after which the same signal runs the ordinary orderly stop and the same component loss takes the running fatal path | +| `apps/loopex_daemon/test/socket_transport_test.exs` | `registry owns a connection from its first pid` | fast | The registry is paused inside its serialized start callback after `GenServer.start_link/3` returns but before row bind and unlink; killing the listener makes the child exit, queueing the trapped child `EXIT`, child-monitor `DOWN` and listener `DOWN`. Resuming proves the registry first binds the returned pid, survives, handles those signals idempotently and reaps the exact child, provisional row, socket and slot, while every no-child row is proved to have no connection pid | **Checks a boundary selects.** Beyond `bash scripts/check.sh`, which every merge needs green in hosted CI, M5 selects exactly these, from the @@ -158,6 +179,7 @@ merge needs green in hosted CI, M5 selects exactly these, from the (`--only node_client`, part of `bash scripts/check-release.sh`) and an update to `docs/developer/compatibility-surfaces.md` in the same change; - a new or changed operator command — `loopex daemon`, `loopex attach`, + and the live forms of `loopex run`, `loopex resume` and `loopex sessions` — selects its operator page in the same change and its workflow in the release check; - Outcome 6 is provider and credential handling, so it selects @@ -176,25 +198,75 @@ merge needs green in hosted CI, M5 selects exactly these, from the `taskset -c 0-3`, one process writing 8 MiB with `dd oflag=dsync` in a loop, thirty runs, any run past its 60 s deadline counted as a hang, and no failure and no hang admitted; -- the Store and recovery are touched only through the daemon's use of the - unchanged adapter, so nothing more runs and the review confirms the - fault-injection and old-reader cases still cover the change; +- the Store and recovery keep the local adapter's durable bytes, marker cleanup, + private port callback, arity and result union; the one adapter change is the + retained-create read projection through existing `runtime_command/2`, so the focused adapter + tests, fault injection and old-reader cases cover it; - `.tool-versions` and the toolchain floor are unchanged, so nothing selects the floor row for that reason. **Closure runs.** At the candidate: hosted CI's green fast check on that -commit is the current-pair evidence; `bash scripts/check.sh` runs once under -the floor pair, `mise exec erlang@27.3.4 elixir@1.18.5-otp-27 -- bash -scripts/check.sh` with its own `MIX_BUILD_ROOT`; and -`bash scripts/check-release.sh` runs once on the current pair **on Linux**, which closure requires because the cross-UID witness needs a second unprivileged user and `SO_PEERCRED`, neither of which a Darwin lane supplies; the evidence page records the platform beside the result. It runs with the +commit is the current-pair Linux evidence; `bash scripts/check.sh` runs once +under the floor pair **on Darwin**, `env -u MIX_BUILD_PATH +MIX_BUILD_ROOT="/absolute/retained-work/M5-otp27-build" mise exec +erlang@27.3.4 elixir@1.18.5-otp-27 -- bash scripts/check.sh`; and +`bash scripts/check-release.sh` runs once on the current pair **on Linux**. +This platform split is required: the Darwin floor run executes +`LOCAL_PEERCRED` decode/fail-closed and the 103/104-byte path boundary, while +Linux CI and release execute `SO_PEERCRED`, the 107/108-byte boundary and the +real second-user witness. The evidence page records the platform beside each +result. The release run needs a second unprivileged user and runs with the provider credential and the pinned Node version in `scripts/fixtures/m4/client-toolchain.txt`. +**Each credential-consuming real-provider workflow runs in its own fresh BEAM.** +Reference composition consumes and deletes `LOOPEX_PROVIDER_API_KEY`; a second +production composition in the same VM must refuse rather than find or restore +it. The release shell retains the exported variable and lets each child BEAM +inherit it once. No test, helper or application re-seeds the variable inside a +VM. `scripts/check-release.sh` therefore replaces the application-wide +real-provider pass with an explicit manifest of these independently launched +cases: + +| Application and file | Exact case | +| --- | --- | +| `loopex_cli/test/foundation_workflow_real_test.exs` | `public pinned Git import and a real provider complete the admitted skill tool and artifact workflow` | +| `loopex_cli/test/coding_task_test.exs` | `one real provider task streams edits a real repository across several turns and the operator sees the committed result` | +| `loopex_cli/test/coding_task_test.exs` | `one real provider call surfaces the provider's own response identifier and reported usage that the deterministic adapter cannot produce` | +| `loopex_app_server/test/external_workflow_real_test.exs` | `an extracted source archive follows the operator guide to serve the shipped host and complete the chain against a real provider` | +| `loopex_llm_reqllm/test/provider_test.exs` | `one real model call completes through the model boundary` | +| `loopex_reference_client/test/end_to_end_recovery_test.exs` | `one real-provider trace forces a credential-free tool survives an untrappable runtime-tree kill after receipt before fact reconciles one effect without redispatch preserves its fact and completes a second real call` | +| `loopex_reference_client/test/real_model_session_test.exs` | `one real non-streaming model call receives the committed canonical request bytes and digest and completes inside a session` | +| `loopex_daemon/test/external_socket_workflow_real_test.exs` | `a controller and observer complete the documented daemon workflow against a real provider` | + +The manifest stores the application, file and exact case name. The script +requires the literal `test ""` definition to occur once, resolves its +current source line, and invokes `mix test : --only real_provider` +in a new operating-system process. Every invocation streams to its own named +log, prints its elapsed time, and must report exactly one executed test; the +script also asserts that all eight manifest rows ran exactly once. Node-only, +long-bound, cross-UID and fresh-source non-provider steps remain separately +selected and run through `env -u LOOPEX_PROVIDER_API_KEY`; only the eight +manifest subprocesses inherit the release shell's credential. The script's +wrapper self-check plants a synthetic value, proves the manifest wrapper sees +the name and the non-provider wrapper does not, and logs only present/absent — +never the value — before any provider call. + +Each reference host's fast custody suite also composes its production path +twice in one VM: the first consumes and deletes the variable and the second +refuses `provider_credential_required` without starting another runtime or +child. That witness makes fresh release VMs a consequence of the host contract +rather than a test-runner convenience. + That release check is where Outcome 2's cross-UID witness lives, and it needs -a selector it does not have today. `scripts/check-release.sh` runs each -`release_apps` lane as `mix test --only real_provider --only node_client ---include long_bound`: three selectors, none of which a cross-UID case -belongs to. So M5 adds one — the cases are tagged `@tag :cross_uid` — and the +a selector it does not have today. Before M5, `scripts/check-release.sh` runs +each `release_apps` lane as `mix test --only real_provider --only node_client +--include long_bound`. M5 removes that combined lane: the manifest above owns +real-provider cases, `node_client_apps="loopex_app_server loopex_protocol +loopex_daemon"` runs `--only node_client`, and +`long_bound_apps="loopex loopex_executor_local loopex_daemon"` runs +`--only long_bound`. None of those selectors covers a cross-UID case. M5 adds +one — the cases are tagged `@tag :cross_uid` — and the script runs, on the Linux lane only, for `loopex_daemon`: ```text @@ -252,17 +324,16 @@ cannot be mistaken for the run closure needs. **Closure requires the evidence page to cite a Linux run whose final line is a plain `PASS`**, and a `closure-incomplete` line is not that. -`loopex_daemon` joins the `release_apps` list in the change that adds its -first release case. Joining that list is separate from the cross-UID lane, -which is its own invocation described above and not a `release_apps` run: -every `release_apps` lane already runs -`--include long_bound`, so the daemon's long-duration bound tests are carried -there and the application does not also join `long_bound_apps`, which exists -for applications with no other release test. Each run's revision, platform, -toolchain, result and measured duration is retained on +`loopex_daemon` joins the real-provider manifest, `node_client_apps` and +`long_bound_apps` in the changes that add those exact cases. Its cross-UID lane +is the separate Linux-only invocation above. Every selected lane asserts its +own exact or nonzero count, so combining selectors cannot hide an omitted +class. Each run's revision, platform, +toolchain, result and measured duration is recorded on `docs/evidence/M5-closure-runs.md`, indexed in `docs/evidence/README.md`, -together with the Outcome 6 security review and the attended demonstration's -provider and model identities. Complete logs stay with the maintainer. +together with the Outcome 6 security review's result, retained-report +reference and digest and the attended demonstration's provider and model +identities. Complete logs and reports stay with the maintainer. **Documentation the milestone must update.** New: `docs/operator/daemon.md` and the developer pair `docs/developer/daemon.md` and @@ -284,43 +355,60 @@ and the developer pair `docs/developer/daemon.md` and operating-system-process-boundary row and its case list M5 widens from the executor to the provider child, the indexes `docs/operator/README.md`, `docs/developer/README.md`, `docs/README.md` and -`README.md`, and `CHANGELOG.md`. Outcome 6 adds the operator's credential +`README.md`, `DEVELOPMENT.md`, and `CHANGELOG.md`. `DEVELOPMENT.md` must replace +its old combined release-check selector description with the implemented +fresh-BEAM provider manifest and separate Node, long-bound and cross-UID lanes. +Because the derived two-tree checklist does not include this root file, the +tested scaffold predeclares a separate `DEVELOPMENT.md` review row and closure +cannot fill it as reviewed until its commands and lane counts match the + implementation. Outcome 6 adds the operator's credential sentence and the developer note on host composition to the pages that describe provider configuration. -**Two page-level obligations are named here rather than left to the writer**, -because both are facts an operator cannot derive from the software and a +**Three page-level obligations are named here rather than left to the writer**, +because all three are facts an operator cannot derive from the software and a reviewer can check against this sentence at closure. -- **`docs/operator/daemon.md` must state the maximum graceful stop, and the - figure it states is the one the implementation *measures*** — not one this - plan derives. The maintainer withdrew the derived sum on 2026-09-20 for the - reason the lifecycle section gives, so this row carries the obligation - instead of the number: at closure the page names the measured maximum, the - conditions it was measured under, and the two bounds this pair does fix - beside it — the **fail-stop** exit at **5 s + 30 s = 35 s** and the **Store - stop's** fixed **30 s**. It must also say that the measured figure is - **not** read off the daemon's own - `--cleanup-grace-ms`, because each session drains under the grace it - committed and a root may carry sessions composed earlier, so the page must - point an operator at the figure the daemon **reports in its stop line** - rather than at one they can compute from flags. And that - a shorter external service-manager timeout turns the stop into a **forced - shutdown**, where work that would have settled does not and the writer - marker may be left for the next daemon's verified recovery. It must also distinguish the **usual - millisecond** Store release from that 30-second **safety ceiling**, so the - number is read as a bound on the worst case rather than as the cost of every - stop. Nothing is written until the implementation exists; this row is what - makes closure unable to forget it. +- **`docs/operator/daemon.md` must state the graceful-stop contract as a + per-root bound, not as one useful configuration-independent operational + timeout.** The accepted cleanup-grace + domain reaches far beyond a useful service-manager timeout and a root may + contain sessions composed under different graces. At closure the page + explains that the daemon derives and reports its drain budget from the + root's committed cancellation bounds, records the selected fixed admission + wait and teardown costs with their maximum-population conditions, and + recommends an unlimited service-manager stop + timeout unless the operator intentionally chooses forced cutoff. It states + the complete successful bound + `5_000 + admission_wait_ms + 5_000 + 5_000 + 70_000 + budget_ms(root) + + 10_000 + 330_000 + 130_000 + teardown_ms + 30_000 + 5_000`, naming each + term and its units. It states the distinct **35 s from first fatal latch** + fail-stop watchdog as an alternative tail after the prefix already spent, + and distinguishes the Store's usual millisecond release attempt from its + safety ceiling and from the final placement-release deadline. A finite external + timeout shorter than that root's reported stop bound is a forced shutdown: + work that would have settled may not, and the placement lock and writer + marker may be left for the next daemon's verified recovery. Nothing is written until the + implementation exists; this row makes closure unable to forget the contract. +- **`docs/operator/coding-sessions.md` keeps every released offline command + syntax row but corrects its numeric-validation account and links to the new + daemon page.** `--context-token-budget` is refused before composition unless + it is a positive unsigned-64 value. The released + `--cleanup-grace-ms` parser checks only that the value is a positive whole + number; core enforces the unsigned-64 ceiling when composition reaches the + runtime, after earlier edges may have started and then been reverse-cleaned. + The page must not claim both flags fail before runtime work. Its daemon-page + link sends readers to the separate live grammars without adding a live-only + flag to an offline syntax row. - **`docs/developer/app-server-protocol.md`, its companion, `docs/developer/compatibility-surfaces.md`, `docs/developer/agent-context-map.md` and `docs/operator/app-server.md` must carry the renamed generation string** and the one-line migration it implies. -Both are covered by the docs gate, which derives its checklist from +All three are covered by the docs gate, which derives its checklist from `git ls-files -- docs/operator docs/developer` over **every** tracked file -rather than a Markdown filter, so neither page can be marked reviewed-unchanged -by accident. +rather than a Markdown filter, so none of those files can be marked +reviewed-unchanged by accident. Every other tracked file under `docs/operator/` and `docs/developer/` is read at the candidate and left unchanged only @@ -329,9 +417,9 @@ makes that auditable rather than asserted. **Every core change has a core witness, named here to file, case and lane — -six changes, six rows**, matching the surfaces table below one for one. An -earlier revision had five rows for six changes, with one of the five being -half of change 4 and two changes carrying no core row at all. +six changes, six rows**, matching the surfaces table below one for one. +Session discovery is daemon-owned under the final index decision, so there is +no core listing change or core listing witness. A downstream witness is not a substitute, and three properties say why: quiesce's `absent` branch needs a @@ -340,14 +428,50 @@ quiesce's `absent` branch needs a `Control` pruning an excluded sender needs that sender's `DOWN`. All three are core-internal states a daemon cannot construct through the socket. +Core change 3 also reroutes `Loopex.Runtime.trace/2` and the matching trace +stop through `Control`. Start receives the current excluded-pid/MFA snapshot +without calling back into `Control`. Trace alone retains the full handle from +`:trace.session_create/3`; it sends Control only the weak `{name, id}` element +split from that exact handle, never a name-selected result from +`:trace.session_info(:all)`. Control retains normalized configuration and +selected MFAs and monitors the exact Trace pid. Explicit stop removes the +retained selection only after Trace acknowledges destruction. That Trace pid's +`DOWN` instead marks the predecessor lost while retaining its weak identity, +normalized configuration and selected MFAs until a replacement resolves the +predecessor and acknowledges the restored snapshot; only `Control` restart +loses that retained state. A replacement first announces its pid/incarnation and stays idle; Control handles +both orders of predecessor `DOWN` and replacement hello, queueing the hello or +proving the old exact pid dead and demonitor-flushing it before it supplies the +retained snapshot. The replacement then verifies each exact weak predecessor +is absent before creating a session and acknowledging. On the production path +Trace released the predecessor's sole strong handle when it died, so the weak +identity is already absent and no destroy is attempted. A defensive destroy +branch exists only for a present identity; its witness is an explicit +fault-injection fixture that retains one forbidden extra strong handle outside +`Control`, a state the production ownership graph cannot create. A racing +`false` or `:badarg` is accepted only after a fresh all-session query proves +that exact identity absent. Control +promotes one current Trace monitor and publishes start/status only after that +acknowledgement. The internal acknowledgement does not change the experimental +embedded API: `Loopex.Runtime.trace/2` still returns its existing +`{:ok, session_description}` shape, and trace stop and status keep their +existing shapes. This is the mechanism behind the concurrent +start/exclusion witness, not an assumption about the current direct call from +`Runtime.trace/2` to `Trace.start_session/3`. The same change makes pending-call +state total: `:calls` retains no start time because that level requests no +return event; return-bearing levels monitor every pid with retained calls and +purge all of its keys on `DOWN`; managed exclusion waits for the named-session +delivery marker, purges that sender's remaining keys and only then acknowledges +`Control`. Session destruction demonitor-flushes every retained monitor. + | Core change | Core witness | Cases | Lane | | --- | --- | --- | --- | -| Concurrent attachment (core change 1) | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `two attachments to one session coexist without replacement`; `one detaching leaves the other delivering`; `an attachment is released when the process that attached it exits`; `an attachment released by its process exiting leaves no open transfer`; `the installed attachment records the attacher pid and the monitor reference`; `a controller and an observer attached to one session both remain usable`; `Control validates each holder's command against that holder's own attachment`; `a command sent from a process that is not the holder resolves by attachment_id and is admitted` — the case a pid-keyed `Control` fails, and the one that forced the dual key; `replace true supersedes only the attaching process's own prior attachment and releases its transfers`; `replace true from a second process supersedes nothing of the first's`; `replace true leaves every other connection's attachment to that session delivering`; `the dispatcher holds no attachment for a dead attacher`; `one backpressuring does not stall the other`; `each carries its own cursor and incarnation` | fast | -| Read-only existence query (core change 2) | `apps/loopex/test/session_existence_query_test.exs` | one per result of the closed set | fast | -| **`quiesce/1` and the coordinator change it needs** (core change 4) | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) for the drain, and **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) for the coordinator half | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `a drain task that crashes fences its session and does not reach the caller as an exit`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes eleven store calls`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst`; `releases cancellation concurrently once every admission resolves`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `reports an unavailable Control entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `reports not_needed only where the fence enumeration holds no entry`; `fences every unavailable entry, including one whose coordinator was terminated`; `reports an awaiting_owner_barrier entry as unsettled and fences it`; `terminates and fences an entry that appeared during the admission and the cancellation`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a fence answering commit_unknown is resolved through transaction_status under the same derived tx_id and reported unsettled with fences[id] == {:unknown, head}`; `a fence id recomputed from the head alone matches the one the drain used`; `a session whose abort admission is ambiguous has no cleanup released and is fenced`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split`; `the status census is bounded by one deadline, not one per session` — five hundred and twelve enumerated sessions whose coordinators never answer, asserted to be reported `unsettled` within one census deadline rather than within five hundred and twelve of them; `the enumeration carries the store handle the fence commits through`, asserted by a drain that fences with no store handle of its own; and, in `cancellation_test.exs`, the coordinator half: `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | -| **`create_session_detailed/3` and `resume_session_detailed/3`** (core change 5) | **`apps/loopex/test/session_detailed_results_test.exs`** (new) | `a fresh create answers disposition created`; `a replayed create with the original command_id answers disposition replayed and starts no coordinator`; `a resume of a dormant session answers control_entry dormant`; `a resume of an already-active session answers control_entry active`; `create_session/3's own return is byte-identical to the released shape` — the case that makes the addition provably additive rather than a facade change; `resume_session/3's own return is byte-identical too` | fast | -| **`Loopex.list_sessions/2`** (core change 6) | **`apps/loopex/test/session_listing_test.exs`** (new) | `a bounded listing stops after the bound-plus-first valid entry`; `it reports that it stopped early`; `a root within the bound reports that it did not`; `the arity-one form is unchanged over the same root` — the pair that proves the addition is additive; `a bounded listing over a root past the bound performs exactly bound-plus-one entry reads`, asserted by tracing `Loopex.SessionDirectory` and counting `read_entry` calls over a root seeded with far more, never by timing it | fast | -| **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid set and `Entry`'s keyword-key redaction** (core change 3) | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process produces no trace message`; `the exclusion survives a tracer restart`; `a new session skips an already-excluded pid`; `fails closed while the tracer is absent`; `fails closed while Control is unavailable` — the case that constructs a `Control` restart, and which therefore asserts what that costs: every child after `Control` restarts with it, so every session coordinator in that runtime is gone and the case starts a fresh session rather than reusing one; `the excluded set returns to baseline after the sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | +| Concurrent attachment (core change 1) | `apps/loopex/test/concurrent_attachments_test.exs` (**new**) | `several attachments under one holder coexist without replacement`; `attachments under different holders coexist`; `one detaching leaves every other attachment delivering`; `holder DOWN removes that holder's full attachment set from Control and the dispatcher and releases every transfer`; `the internal attach-for-holder call installs the supplied stable holder rather than its transient caller`; `a command executed by a relay task is admitted when its stable holder owns any live attachment for the pinned session`; `replace_attachment_id replaces only the named attachment owned by that holder and releases its transfers`; `an unknown, foreign or different-session replacement target is refused`; `an exact live replacement target is reserved once: exact repetition coalesces and a distinct concurrent request refuses without a second borrow`; `the replacement selector is part of repetition binding`; `Control allocates one attachment and incarnation identity at reservation and that exact pair appears in Control pending/live state, dispatcher staged/live state, the returned or repeated handle and cleanup acknowledgement`; `a Control generation change between dispatcher staging and validation discards an ordinary pending attach with both live maps equal`; `the same forced refusal for replacement at the 512 ceiling leaves the old attachment and transfers live, clears pending state and never undercharges the daemon count`; `post-publication holder death is forced in both Control mailbox orders for ordinary and replacement attaches: publish-ack then DOWN finalizes before ordinary cleanup, while DOWN then publish-ack returns holder_unavailable only after idempotent dispatcher cleanup; both leave equal live sets, zero pending rows and no retained charge, and neither restores a replacement target`; `a post-publication interruption reconciles by transaction identity before returning a result`; `the state-changing half is one deferred infinity Control call whose handle_call returns noreply, whose dispatcher acknowledgements go directly to Control, and whose only terminal reply comes from Control while post_commit remains responsive`; `caller death drops only the reply route and the transaction reaches cleanup`; `one linked preparation worker exists per pending attach, worker death refuses only that transaction, and 512 pending attaches create no 513th worker`; `EventDispatcher death before stage, after stage, after authorization and after publish acknowledgement was sent but before Control consumed it returns attachment_superseded to a live retained embedded caller within the fixed bound, while the daemon sentinel instead fail-stops runtime_lost and teardown settles its relay ticket and charge once; both paths clear predecessor live, pending, waiter, repetition, monitor and borrowed-charge state, treat late predecessor messages as cleanup-only, never restore a removed target, make old handles stale and permit a fresh attach after recovery`; `replacement registration seeds Control's retained acknowledged event sequence, so an unacknowledged outbox row stays fenced until resolution`; `a replacement stays mailbox-responsive while a linked registration worker talks to Control, accepts and max-merges an acknowledgement while Control is in post_commit, then opens admission only after dispatcher-ready and Control-ready states agree`; `dispatcher death kills its registration worker and no predecessor worker survives restart`; `one backpressuring attachment does not stall another`; `each attachment carries its own cursor and incarnation` | fast | +| Read-only existence and create-history query surface (core change 2) | `apps/loopex/test/session_existence_query_test.exs`, `apps/loopex/test/create_history_query_test.exs`, the shared Store conformance cases for `Loopex.Store.Local` and `Loopex.M1RuntimeTestStore` | existence: `{:ok, :present | :absent | :invalid_id | :store_unavailable}`, each with a byte-identical root, plus a malformed adapter answer proved to normalize to `{:ok, :store_unavailable}` through the Store facade, and exact-Control loss returning only `{:error, :runtime_unavailable}`; create history: `{:ok, {:historical, session_id} | :absent | :conflict | :store_unavailable | :unexpected}` with exact command/options binding, no coordinator and no write, plus the same distinct outer runtime failure; both Store implementations project an exact retained create as `{:completed, %{result: session_id}}`, reject changed options and a cross-kind command ID as `runtime_command_conflict`, and leave durable bytes unchanged | fast | +| **`quiesce/1` and the coordinator change it needs** (core change 4) | **`apps/loopex/test/runtime_quiesce_test.exs`** (new) for the drain, and **`apps/loopex/test/cancellation_test.exs`** (existing; the file that already drives an abort against a receipt arriving mid-reduction) for the coordinator half | `admits every abort before any cleanup begins`; `a coordinator commit during the abort admission is served by Control and its session settles`; `an unlinked quiesce helper crash becomes drain_failed without taking the owner down`; `one abnormal per-session worker affects only that session while siblings finish`; `a phase-owner crash returns runtime_unavailable and leaves no worker or fence-mode coordinator at cuts before the head read, inside the first fence transaction, and before and inside exact re-presentation`; `a suspended ordinary session supervisor cannot block fence start and its later resume creates no delayed coordinator or Store call`; `killing the daemon outer helper ends the monitored phase owner and every linked worker before fail-stop`; `a drained abort commit is presented once and never re-presented on commit_unknown`; `a fresh create executes nine store calls, ten with the retry`; `attach executes one store call over an empty session and two over eight events`; `resume of a twelve-record session executes fifteen store calls when both current/predecessor abort IDs and both current/predecessor fence IDs are absent — the ordinary eleven plus four status queries — and thirteen when the current abort and fence candidates are terminal`; `the reserve-completion callback commits three times on a refused fact and twice on a committed one`; `an abort admission whose reply path settles an open model attempt commits twice and stops`; `quiesce admits no abort into an acquiring entry, and terminates and fences it instead`; `a fence executes three store calls at worst, and an ambiguous abort followed by a fence executes four`; `releases cancellation concurrently once every admission resolves`; `a suspended initial Control gate returns runtime_unavailable inside five seconds and starts no per-session worker`; `sixty-four admission calls are issued together, held through the 65-second work cutoff, killed and reaped by the 70-second outer deadline, release no cleanup, and recover a late deterministic abort rather than treating it as absent`; `sixty-four cleanups receive one release transition and one shared cancellation deadline, with an all-early population advancing when all are terminal and a mixed population advancing once at the deadline`; `an empty active set drains with a zero budget`; `reports a Control entry whose coordinator has died as absent`; `omits an unavailable entry that never entered the writer domain and starts no worker; reports an unavailable writer-domain entry as absent and fences it`; `reports an acquiring entry as unsettled and fences it`; `an acquiring entry whose owner_ready cast is in flight is terminated and reported unsettled`; `settled is read from the coordinator's status, not from the cancellation finishing`; `a cancellation that finished with its terminal commit held is unsettled, not settled`; `fences an unsettled session and refuses its paused transaction as stale`; `fences an absent session too`; `fences a settled session too, and refuses its straggler commit released during the store phase`; `the first census freezes its exact writer-domain projection through fencing`; `uses the monotonic writer-domain set, not unavailable status, so a terminated coordinator is fenced and a never-started entry is omitted`; `an awaiting_owner_barrier owner-group DOWN consumed between censuses answers its waiters runtime_unavailable, retains the same key, starts no ordinary owner and is fenced`; `the first Control call gates create, resume, attach and ordinary routes`; `create and resume forced in both Control mailbox orders either finish their Store and entry-or-dormant decision before the gate or refuse before Store access after it`; `a prompt held after Control routing but before SessionCoordinator.command refuses when the drain call wins its mailbox`; `two concurrent quiesce calls produce one owner and one runtime_unavailable refusal with no second per-session work`; `a fence refused stale_owner_epoch is superseded with no second attempt`; `a fence refused stale_journal_version is superseded too, not an error`; `a live fence owner answering commit_unknown re-presents once with its exact retained binding and a second unknown remains fences[id] == {:unknown, :fence, head}`; `a tx_id_conflict on first fence presentation returns `{:unknown, :fence, head}` with no alternate ID or retry; a tx_id_conflict during exact live re-presentation is an invariant violation and never reports the fence committed`; `a fence id and incarnation recomputed from session id and owner epoch reproduce that live operation's exact transaction; replayed `owner_advanced` reconstruction derives the expected prior head from the stamped journal version, rebuilds `Store.advance_owner/6` and its canonical digest, and compares every durable field because the record carries epochs, incarnation and transaction ID but no digest`; `restart after fence commit_unknown receives no drain head or transaction bytes: a fresh process checks the current-epoch ID and, only on absence or an exactly attributable different-command collision, the predecessor ID, with reconstructed committed, collision/no-fence, terminal non-commit, stale-journal, stale-epoch, both-absent, unattributable-commit and unavailable branches before ordinary successor admission; unattributable or unavailable stays unavailable`; `a client command pre-bound to the derived abort ID with a different binding returns `idempotency_conflict`, releases no cleanup, remains unsettled and proceeds to termination/fencing; a session whose abort admission is ambiguous has no cleanup released`; `committed, terminal non-commit, absent in both CAS orders, and unavailable exhaust the abort-unknown outcomes`; `a crash between abort unknown and fencing is recovered before successor admission`; `an admission task shut down mid-call still leaves the coordinator admitting the abort and pausing at the split`; `the status census is bounded by one deadline, not one per session` — sixty-four enumerated sessions whose coordinators never answer are cut at five seconds, killed and reaped to worker baseline by ten seconds, and reported `unsettled` rather than taking sixty-four deadlines; `sixty-four coordinators under a suspended supervisor start termination together, at 325 seconds directly kill every still-live coordinator and blocked termination worker, consume every exact coordinator DOWN and worker exit by 330 seconds, reach worker baseline before fencing, and after supervisor resume produce no queued start, result or Store call`; `sixty-four fence paths begin cancellation at the 125-second work cutoff, have every exact pid and operation absent by the 130-second outer deadline, and permit one ordinary sibling to finish`; `sixty-four writer-domain entries succeed, sixty-five refuse runtime_unavailable before any worker starts, while more than sixty-four no-writer dormant entries are omitted and start no worker`; `a start_child refusal reports no_activation, leaves the session outside the writer-domain set and spawns no fence worker`; `a child start followed by later attach/readiness failure reports activated and remains fence-eligible, with sixty-four such entries filling the activation ceiling and the sixty-fifth refused before start`; `the enumeration carries no Store handle`; `after ordinary coordinator DOWN, a one-shot fence-mode SessionCoordinator is the sole serial owner for abort status recovery, advance_owner and exact fence re-presentation, then exits`, asserted with the helper holding no Store handle; and, in `cancellation_test.exs`, the coordinator half: `a drained abort commits without beginning cleanup`; `a client abort still begins cleanup on its commit reply path` — the pair that proves the split changed the drain and nothing else | fast | +| **`create_session_detailed/3` and `resume_session_detailed/3`** (core change 5) | **`apps/loopex/test/session_detailed_results_test.exs`** (new) | `a create that starts an owner answers disposition activated`; `a completed create replay answers no_activation and starts no coordinator`; `a fresh resume answers activated`; `an open resume-command replay answers activated and charges because it starts an owner`; `a completed resume replay answers no_activation`; `control_entry is observed independently as active, acquiring or dormant`; `exact Control loss before processing returns outer runtime_unavailable with no metadata`; `exact Control loss after child start but before reply also returns only runtime_unavailable, fabricates no disposition or control_entry, and leaves successor recovery rather than a continuing daemon to determine durable truth`; `only a domain result from a live Control authorizes reservation conversion or release and initial directory/index publication, while no_activation under all three control_entry values publishes nothing`; `create_session/3's own return is byte-identical to the released shape` — the case that makes the addition provably additive rather than a facade change; `resume_session/3's own return is byte-identical too` | fast | +| **`Loopex.Trace.exclude_self/2`, `Control`'s excluded-pid/MFA state and `Entry`'s keyword-key redaction** (core change 3) | **`apps/loopex/test/trace_session_test.exs`** (existing; extended) | `the named MFAs produce no raw message under an explicitly named module, before any process flag is set`; `an excluded process drains its pre-clear trace signals through :trace.delivered before acknowledgement and produces no post-ack trace message`; `level :calls retains no pending start while return-bearing levels monitor each represented pid`; `managed exclusion purges the sender's pending-call keys at the delivery marker`; `managed and Direct sender DOWN return pending-call state and monitors to baseline`; `destroying a trace session removes that session's process flags and pending-call monitors`; `Trace alone retains each full session handle while Control retains the exact weak element split from that handle, with exactly one current Trace monitor and no start/status publication before replacement acknowledgement`; `the rerouted Runtime.trace/2, trace_stop/1 and trace_status/1 preserve their existing public result shapes`; `a tracer restart forces both mailbox orders of predecessor DOWN and replacement hello, keeps the replacement idle until Control resolves the exact predecessor, proves the ordinary production predecessor weak identity absent after Trace released its sole strong handle, exercises the present-and-destroyed branch only in a separate fault-injection fixture that deliberately retains one forbidden extra strong handle outside Control, and normalizes a racing false or badarg only after a fresh all-session query proves that exact identity absent, performs no lookup by the shared name, and creates a new session that reapplies retained live-sender pid and MFA exclusions`; `the last sender DOWN restores each live session's own selected MFA pattern while a session that never selected the MFA remains clear`; `a new session skips every already-excluded pid`; `fails closed while the capability or Control is immediately unavailable`; `an unanswered exclusion remains pending for the guardian deadline`; `a Control restart stops Trace, the sole full-handle owner, and downstream sender owners together, after which a fresh sender excludes anew`; `the excluded set and ref-counted MFA union return to baseline after the last sender exits`; `a keyword list's value is redacted under its own key`; `the same value under a key naming nothing is rendered, so the case cannot pass vacuously` | fast | +| **Managed provider lifetime** (core change 6) | **`apps/loopex/test/provider_lifetime_test.exs`** (new), plus **`apps/loopex_llm_reqllm/test/credential_plane_test.exs`** | `managed scope starts an inert guardian and an inert sender sequentially as direct temporary owner_workers children, with at most one linked start proxy alive`; `each proxy reports the exact start_proxy_result tuple for guardian or sender, reference, proxy pid and either the exact child pid or unavailable; the callback accepts only that matching result plus the exact child acknowledgement, monitors the child as soon as either message first discloses it, and consumes proxy normal DOWN before continuing, so no second proxy overlaps`; `the three legal start orders are child acknowledgement then result then proxy DOWN, result then child acknowledgement then proxy DOWN, and result then proxy DOWN then child acknowledgement; same-sender ordering forbids proxy DOWN before its result`; `a starter refusal and a caught starter exit follow that same unavailable result and reverse-clean an acknowledged child`; `the guardian initial argument is exactly guardian_ref, callback-owner pid and stop_reference`; `the sender initial argument is exactly sender_ref, callback-owner pid, guardian pid and tracing capability`; `suspending owner_workers before guardian materialization, ending the scope and resuming produces only an inert late guardian and every count returns to baseline`; `pausing guardian start acknowledgement before Core registration and killing the callback produces no registration or provider action`; `Core registration returns the exact retainer and cleanup grace, the guardian installs that monitor and acknowledges authorization before sender start`; `every private gate uses the exact tagged guardian-started, authorize-guardian, guardian-authorized, sender-started, authorize-sender, sender-adopt, sender-adopted-by-guardian and sender-adopted tuple with the expected reference and pid`; `after registration, holding sender materialization while Core sends its exact stop request yields the stop acknowledgement and guardian DOWN; resuming owner_workers creates only an inert late sender that sees callback or guardian loss and exits, with every population at baseline`; `sender start, guardian adoption and sender adoption-complete acknowledgement are separate cuts, and initialize cannot race either`; `guardian or sender death after either first pid disclosure and before transfer completion reaches the callback child monitor as unavailable; the callback demonitor-flushes only after the retainer monitor owns the guardian or the guardian monitor owns the sender`; `immediate refusal at any gate returns unavailable, reverse-cleans partial children and never raw-spawns`; `a non-answering start remains owner-group liveness rather than adapter timeout`; `normal callback completion after both transfers leaves the guardian retained and the sender governed by the guardian, not callback DOWN`; `the adopted sender parks until exact provider readiness, so pre-ready refusal or guardian death performs no exclusion, sink, route, custody or frame work`; `release, bootstrap result, credential context, every phase result and every continuation use the exact sender_ref/guardian-pid/sender-pid binding; phase continuations also carry the exact phase and unchanged deadline, and wrong-ref, wrong-pid, wrong-phase, changed-deadline and stale-replay injections never unpark, route or write and end at the unchanged deadline`; `managed setup consumes and never resets the absolute invocation deadline, release after 5 seconds but before that instant succeeds, and expiry after initialize returns timeout`; `before accepting provider readiness, the bootstrap result or any phase result, and before emitting credential context or a phase continuation, the guardian rechecks monotonic now before deadline; paired mailbox-order cases prove a completion consumed before the instant advances once, one consumed at or after it is cleanup-only timeout even when queued first, and the timer only prompts the check`; `after begin_bootstrap the sender keeps trap_exit false, completes exclusion before starting a sink that is linked for abnormal exit and monitors the sender for normal exit, and both pids are clear before token delivery`; `normal sender success and abnormal or kill exit each return the sink population to baseline`; `abnormal guardian death while the sender is parked or post-readiness sink installation is blocked ends sender and sink, restores Control and Trace baselines, and delivers no token, handle, channel context, frame or raw trace canary`; `normal guardian cleanup explicitly stops and awaits the sender`; `only the adapter-minted direct/no-runtime mode retains the existing raw-spawn fallback`; `killing Control while a sender is paused after custody reply delivers guardian and sender DOWN before the replacement tracer appears`; `a fresh sender succeeds after restart`; `ordinary completion leaves no guardian, sender, start proxy, receiver, generic phase-send helper, sink, Port, carrier, guard or provider BEAM behind, and every member's population returns to baseline`; `credential_plane_test.exs: credential frame result is emitted only from a non-secret final wait` proves all credential-bearing logical references are dropped before the exact `:credential_frame` result; `credential_plane_test.exs: only final-state normal sender DOWN starts invocation` proves the final continuation permits only normal exit and only that exact normal `DOWN` before the retained deadline starts the generic invocation helper; `credential_plane_test.exs: sender DOWN and final-deadline cuts never start invocation` forces raise, exit, kill and early normal exit before expiry to `:unavailable`, consumes the same `DOWN` after the guardian clock reaches the instant as `:timeout`, and expires the final continuation with no helper | fast | The paused-transaction case in `runtime_quiesce_test.exs` pauses the transaction through core's own controllable store, not the shipped adapter: @@ -388,7 +512,11 @@ where it is not (`Loopex.M1RuntimeTestStore`, which core's tree can reach and executed counts this plan already holds are the ones named in the `quiesce/1` row of the evidence table above: a fresh create's nine Store calls, ten with the retry; an attach's one over an empty session and two over eight events; a -resume's eleven over a twelve-record session; a fence's three at worst. +resume's fifteen over a twelve-record session on the path where both plausible +abort IDs and both plausible fence IDs are absent — the original eleven plus +two abort-status and two fence-status queries — and thirteen when the current +abort and fence IDs are terminal; a shutdown +fence's three at worst. Those are **core** witnesses, because those paths are core's: the daemon contributes no Store call of its own to any of them. A case that asserted "at @@ -463,19 +591,17 @@ artifact formats and the executor protocol are unchanged. **The embedded API's *shape* is unchanged and one of its *behaviours* is not**, which an earlier revision folded into "the embedded API is unchanged" -and thereby denied. `Loopex.attach/3` (`loopex.ex:134`) keeps its arity, its -arguments and its result. What changes is what a second attach to the same -session does. Today the dispatcher supersedes unconditionally: it splits -`state.attachments` on `session_id` alone -(`runtime/event_dispatcher.ex:812-818`), and no `replace` option exists -anywhere in core — `Loopex.attach/3`, `Runtime.attach/3` and the dispatcher -mention none. So an embedded caller that attaches twice for one session, from -one process or from two, sees the first attachment superseded and its -transfers released. **After core change 1 it does not**: supersession -requires `replace: true` and is scoped to the attaching process's own prior -attachment, and a second attach without it leaves both attachments live. That -is the behaviour the daemon exists to have, and it is the one the migration -note below names. +and thereby denied. `Loopex.attach/3` (`loopex.ex:134`) keeps its arity and +result and gains only one optional attach option, +`replace_attachment_id`. Today the dispatcher supersedes unconditionally: it +splits `state.attachments` on `session_id` alone +(`runtime/event_dispatcher.ex:812-818`), and no replacement selector exists in +core. After core change 1, a second attach without a selector leaves both +attachments live, including when the same holder owns them. A replacement +names one attachment identity, is admitted only when the same stable holder +owns that attachment for the same session, and removes only that target. A +boolean replacement flag is insufficient because one holder may own several +attachments and there is no implicit ordering that can select one. Source `VERSION` is distinct from protocol generation, provider build and schema digest. @@ -513,9 +639,10 @@ unedited, and nothing supersedes it: it never named the string, so nothing it says stops being true. **Now is the cheapest moment**, which is the other half of the decision. -Workstream 3 already restructures `LoopexProtocol.Session` from one generation -in module attributes into one module serving two, with both digests pinned -side by side; the string is a module attribute in exactly that restructuring. +Workstream 3 keeps `LoopexProtocol.Session` as the generation-1 compatibility +facade and adds `LoopexProtocol.Session.V2` as the daemon's explicit generation-2 +contract, with both digests pinned side by side; the generation-1 string is a +module attribute in exactly that work. Renaming later would mean a second pass over the same module, the same vectors, the same clients and the same documents. @@ -545,8 +672,10 @@ So the released surface is **already inconsistent with itself**: `session.ex:32` serves `loopex.session.v1-experimental`, the conformance module pins that string at `:282`, and the digest-pinned manifests those same clients read say `loopex.experimental/1`. Nothing catches it, because the conformance test pins -each manifest by its **file digest** and never compares the manifest's -`/generation` with `Session.generation()`. +each manifest by its **file digest** and never compares the generation-1 +manifest's `/generation` with `LoopexProtocol.Session.generation()`; M5 adds +the corresponding `LoopexProtocol.Session.V2.generation()` assertion for the +generation-2 manifest. That reframes the rename. It is not a break introduced for tidiness; it is the change that makes the **code agree with the artifacts already published beside @@ -559,9 +688,15 @@ untouched, because a reader who trusts that sentence would read a failing build as drift — and equally, a reader told that three pins move would go looking for two changes that are not there. -Outcome 6 changes no public surface. The `Loopex.Model` callbacks, the private -provider codec's version and frame kinds, the build manifest and ADR 0019's -process topology are all unchanged. Its one compatibility effect is on host +Outcome 6 changes one experimental public helper behavior. The +`complete_prompt/3` arity and result union remain, but an environment-only +options list now refuses; a caller composes ephemeral custody and a routing +registry and passes their token and handle. The `Loopex.Model` callbacks, the +private provider codec's version and frame kinds, and the build manifest are unchanged. +ADR 0019's provider child, Port, OS guard, private channel, launch-time +enumeration and scrubbing, failure teardown and forensic disclaimer remain; +ADR 0034 narrowly changes the credential source and resolution point and puts +managed guardian/sender processes under `owner_workers`. Its one compatibility effect is on host composition: an embedder that relied on the adapter reading the environment for it passes a credential token with the call instead, over a registry and custody it composes, and gets the adapter's ordinary refusal to dispatch rather than a silent fallback if it @@ -574,10 +709,15 @@ Concept: [Rollout and compatibility](M5.md#concept-plan-rollout). No journal migration exists in M5. The daemon reads and writes the same local log the M4 foreground server and the CLI write, under the same placement -identity, so a state root moves between the daemon and the foreground surfaces -by stopping one and starting the other. Prove that an orderly daemon stop -releases the writer marker and that the foreground server and the CLI then -resume a daemon-created session with identical replay. +identity. That makes daemon-to-foreground rollback direct. The first move of a +populated M4 or `0.1.0` root with no daemon index into M5 requires the one-time +`loopex daemon prepare-index` import; ordinary daemon startup refuses it until +that succeeds. Once a valid index exists, later switches need only stop the +current surface before starting the other. On a healthy orderly daemon stop, prove +writer-marker absence and immediate foreground-server and CLI reopen rather +than inferring release from `terminate/2`; then resume a daemon-created session +with identical replay. A separate injected removal/sync failure proves the +complete residual follows verified stale-writer recovery. A root that reaches the local log's 256 MiB capacity is retired, not migrated. The daemon has already exited by then, because the capacity refusal terminates @@ -607,20 +747,15 @@ one generation would put two names on one contract, which is the thing this rename exists to stop, and it would have to be removed later anyway. **The second note is for embedded callers, and it is one behaviour.** A -caller that relied on `Loopex.attach/3` superseding its own earlier -attachment to a session — the only way core offers today, since the -dispatcher supersedes on `session_id` alone with no option to say otherwise — -must **pass `replace: true`** after core change 1, and must pass it from the -**same process** that holds the attachment it means to replace. A caller that -does neither gets two live attachments where it used to get one, which is a -resource leak rather than a refusal and so will not announce itself: the -older attachment keeps its resident window and its queue until its process -ends, and the dispatcher's `DOWN` release is what eventually collects it. -Callers that attach once per session, which is every caller in this -repository, need no change at all. **Rollback is symmetric and needs no -note**: a root carries no attachment state, attachments being runtime-local -and transient, so reverting core change 1 restores the old behaviour for -whatever is running next. +caller that relied on `Loopex.attach/3` superseding an earlier attachment to a +session retains that earlier handle and passes its attachment identity as +`replace_attachment_id`. The same stable holder must own the target, and an +unknown, foreign or different-session target is refused. Omitting the selector +creates another live attachment where the old implementation removed one, so +callers that depended on implicit replacement must change. Callers that +attach once per session need no change. Rollback is symmetric: a root carries +no attachment state, so reverting core change 1 restores the old transient +behaviour for the next runtime. **Rollback is unaffected by the rename**, because a generation string is negotiated and never persisted. A root written by a `0.2.0` daemon carries no @@ -661,12 +796,15 @@ fifteen, each time counting the carriers they had happened to look at. Rollback to `0.1.0` is stopping the daemon. Removing it restores the M4 foreground server and the CLI on the same root with no durable dependency on -residency, index or lease state, because none of those is persisted. A -daemon-owned root is an ordinary local root the moment the daemon releases its -writer marker; a root whose marker is still held by a dead daemon is released -by the adapter's existing liveness-probe discipline and its -`store_writer_active` and `store_writer_unverifiable` refusals, which M5 does -not change. Outcome 6's rollback is reverting the adapter change; nothing +residency or lease state. The daemon's bounded index is a separate advisory +file: released foreground surfaces ignore it, and rollback may leave it in +place or remove it while the daemon is stopped without changing journal or +session truth. A daemon-owned root is an ordinary local root once the daemon is +gone and the next opener either observes the placement lock and writer marker +absent or applies their verified stale-owner recovery; a root whose placement +lock or marker remains after a dead daemon is released only by that lock's +existing liveness-probe discipline and its live/unverifiable refusals. M5 does +not change either on-disk record or recovery rule. Outcome 6's rollback is reverting the adapter change; nothing durable records which mechanism delivered a credential to a process that has since exited. No in-place downgrade, installed-data migration or service-manager claim exists. @@ -682,7 +820,8 @@ foreground server's protocol mapping. The application inventory and the role rules in `apps/loopex/lib/mix/tasks/loopex.deps_budget.ex` and its cases in `apps/loopex/test/deps_budget_test.exs` change in the same reviewed change that adds the application, and `mix loopex.deps_budget` proves the direction. -M5 adds no external dependency. No transport library, socket abstraction layer +M5 adds no new dependency package; it updates the existing `req_llm` +constraint to `~> 1.24.0`. No transport library, socket abstraction layer or service-manager integration enters any application. The socket lives in a `0700` daemon-owned `daemon/` subdirectory of the state root, which the daemon creates and whose mode it verifies; the state root's own mode is read and never @@ -696,8 +835,9 @@ the classic backend exposes neither the named option nor the raw one, while over the socket backend with its handle reachable satisfies this; no library is added either way. -Supply `loopex daemon`, `loopex attach` and a live form of `loopex sessions` -in the reference CLI, on the contracts below, and extend the client in +Supply `loopex daemon`, `loopex attach`, live forms of `loopex run`, +`loopex resume` and `loopex sessions` in the reference CLI, on the contracts +below, and extend the client in `clients/node` to connect over the socket, to follow as an observer and to take over. It stays a plain client with no build step, package manifest or dependency, as the maintainer decided for M4 on @@ -719,8 +859,26 @@ from the extraction the closure candidate must build from. M5 therefore adds an archive-carried source identity that both paths accept, and one shared resolver they both call: -- a tracked `SOURCE_IDENTITY` file holding `$Format:%H$` and the commit date, - with a tracked `.gitattributes` marking it `export-subst`. What that does, +- a tracked `SOURCE_IDENTITY` file with exactly these bytes, including the + single ASCII spaces and final LF: + + ```text + commit $Format:%H$ + committer-date $Format:%cI$ + ``` + + `.gitattributes` contains the exact attribute entry + `SOURCE_IDENTITY export-subst`. In an archive the first value must be one + lowercase 40-character hexadecimal object name and the second must be the + strict ISO-8601 committer date emitted by Git's `%cI`, including its numeric + offset: the calendar-valid ASCII shape + `YYYY-MM-DDTHH:MM:SS+HH:MM` or `YYYY-MM-DDTHH:MM:SS-HH:MM`, with every + letter standing for exactly one decimal digit. The parser accepts those two fields once, in that order, with no + unknown field, duplicate, blank line, alternate separator, or trailing byte + after the final LF. Closure compares the complete expanded file with the + final-LF-terminated output of + `git show -s --format='commit %H%ncommitter-date %cI' `. + What `export-subst` does, stated because the refusals below depend on it: `git archive` rewrites `$Format:…$` placeholders **inside a file's contents** as it exports, so the extracted copy carries the exact commit while the copy in a checkout keeps @@ -741,9 +899,11 @@ and one shared resolver they both call: **changed during the build**, which is the property `git status` buys in a checkout and which the resolver has to buy some other way here, because an extraction has no git index to ask what is tracked; -- the provider build manifest embeds the resolved commit id together with that - source digest, so an identity naming a commit whose tree is not what was - built is detectable rather than merely trusted. +- the provider build manifest embeds the resolved commit id together with the + `sha256` digest of the canonical pre-build extraction manifest defined + below. That digest is the term **source digest** everywhere in this pair, so + an identity naming a commit whose tree is not what was built is detectable + rather than merely trusted. **The unchanged-tree check needs an inventory, and the inventory cannot ride inside the archive.** An earlier revision said the resolver hashes "the @@ -759,24 +919,38 @@ asked the extraction to carry an answer only the repository has. So the inventory stays **outside** the archive, with the party that has the repository: -- **the closure evidence records the candidate's inventory**: the output of - `git ls-files -z` at that commit, and its SHA-256, retained on - `docs/evidence/M5-closure-runs.md` **beside the archive's own digest and - commit**. The closure runner is in the checkout when it stages the archive, - so this costs one command it is already positioned to run; -- **the extracted-build witness compares a canonical manifest**, taken over - the extraction before the build and again after, and requires the two to be - identical. The manifest is one record per path, **NUL-separated** so no - filename containing a newline or a quote can forge a boundary — `git - ls-files -z` is read the same way — holding the **path**, its **kind and - mode** (regular with its permission bits, symbolic link, directory), and +- **the closure evidence records the candidate's source-path inventory**: the + output bytes of `git ls-files -z` at that commit are retained outside the + repository. The frozen `docs/evidence/M5-closure-runs.md` scaffold records + their source SHA, entry count, stable retained-output reference and SHA-256 + digest beside the archive's own digest and commit. The closure runner is in + the checkout when it stages the archive, so this costs one command it is + already positioned to run; +- **before the build, the extraction's regular-file and symbolic-link path + set**, excluding only `_build/` and `deps/`, is emitted NUL-delimited and + compared exactly with the recorded `git ls-files -z` inventory. Directories + are excluded from this comparison because Git does not track them; +- **the extracted-build witness separately compares a canonical manifest**, + taken over the extraction before the build and again after, and requires the + two to be identical. The manifest is one record per path, **NUL-separated** + so no filename containing a newline or a quote can forge a boundary, holding + the **path**, its **kind and mode** (regular with its permission bits, + symbolic link, directory), and either the **SHA-256 of its contents** or, for a link, its **target**. A digest over contents alone would miss a file made executable, a regular file replaced by a link to one, or a path that appeared and another that vanished; the path set, the kind and the mode are what close those, and the before/after pair is what catches a build that writes into its own source - tree. The first manifest is also compared with the inventory the closure - evidence recorded, which is what ties the extraction to the commit; + tree. Its byte grammar is fixed: records sort by raw path bytes; each record + is `kind NUL mode NUL path NUL value NUL`, where `kind` is `f`, `l` or `d`, + `mode` is the lowercase octal permission mode, `path` is relative to the + extraction root, and `value` is the lowercase SHA-256 hex digest for a + regular file, the raw link target for a symbolic link, or empty for a + directory. POSIX paths and link targets cannot contain NUL, so the stream is + unambiguous. **Source digest** is the lowercase SHA-256 hex digest of this + complete pre-build byte stream. The exact path-set comparison above is what + ties the extraction to the commit; the richer manifest proves the build did + not change kind, mode, content, link target or directory structure; - exactly **one** exclusion rule, named rather than implied: the two build-output roots `_build/` and `deps/`, which the build is supposed to create. Nothing else is excluded, and the list of exclusions is part of the retained evidence, so @@ -806,20 +980,23 @@ merely extractable. `VERSION` and the application versions move to `0.2.0` in an ordinary reviewed commit before closure, as the [milestone guide](../developer/milestones-technical.md#technical-milestones-release) -sets out; every application reads it at compile time. The release-ready source +sets out; every application reads it at compile time. + **How a run is retained immutably, since a tag does not exist yet when the -runs happen.** Every run in the closure matrix is produced *before* any tag, -so "attach it to the annotated tag" cannot be the mechanism for any of them. -The mechanism is the other one: each run's full output is written to a file -outside the repository, its **SHA-256 recorded on -`docs/evidence/M5-closure-runs.md`** beside that run's identity, platform, -toolchain, result and measured duration, and the page itself committed at the -tested implementation SHA — so the page a reviewer reads is fixed by the -commit they review, and any later edit to it is a visible diff against that -commit rather than a silent rewrite. What the tag adds is a second anchor for -the two runs that happen *at* the tag: the release's `check.sh --docs` and the -recomputed archive manifest, which the tag's own annotation can carry because -they postdate it. +runs happen.** The tested implementation SHA already contains an indexed, +unfilled `docs/evidence/M5-closure-runs.md` scaffold whose results remain +`Pending`. Every closure-matrix run's complete output is retained outside the +repository under a stable reference and SHA-256 digest. The administrative +closure commit has the tested SHA as its sole parent; it fills that +existing page with the tested SHA, each run's identity, platform, toolchain, +result, duration, retained-output reference and digest, plus the independent +review's result, reference and digest, and every M5-specific value predeclared +as `Pending`: the source inventory identity, documentation checklist including +the separate `DEVELOPMENT.md` row, Outcome 6 security review, attended-demo +provider/model identities, archive manifest identity, and graceful-stop +observation with its conditions. It adds no heading, label, row or prose. It +touches exactly the five paths and +allowed regions the milestone guide confines and carries no run of its own. The source archive is staged from the exact committed candidate with `git archive`, @@ -829,23 +1006,36 @@ commit and tree are retained with the closure runs. The release itself is one annotated `v0.2.0` tag created on the maintainer's separate decision, and the commit it names is the **administrative closure SHA** — the one carrying the closure record, and therefore the tree a reader who fetches the tag gets. -Four things are verified at the tag, in this order: `git diff --name-only -..` reaches **only -[the four confined paths](../developer/milestones-technical.md#technical-milestones-confinement)** -— all under `docs/`, so nothing outside `docs/` moved, which is what -makes everything below sufficient; `bash scripts/check.sh --docs` is green on -the tagged SHA; the archive manifest recomputed from the tagged SHA equals the -one recorded on the evidence page for the tested SHA **for every entry outside -`docs/`**, the `docs/` -entries being expected to differ and therefore not compared — which catches an -archive that includes or excludes differently from the tree, as -`.gitattributes` can without showing in any diff; and the tag object is -annotated, with -`v0.2.0^{commit}` reachable from `main` and `git show :VERSION` -exactly `0.2.0`. Nothing else re-runs — no suite, no release check, no -provider credential — because the confinement check is what proves the tagged -source and the closed source are the same source. Do not -move the tag, and publish no package, binary, installer or service unit. +Before the tag is created, four proofs run on the administrative SHA, in this +order. First, the confinement proof requires its sole parent to be the tested +SHA, requires the complete zero-context patch to reach exactly +[the five confined paths and each path's allowed region](../developer/milestones-technical.md#technical-milestones-confinement), +maps every changed byte to that table, reconstructs both marked status files +byte-for-byte from the tested files plus their canonical new blocks, and +requires the root README to be the sole path outside `docs/`. Second, +`bash scripts/check.sh --docs`, including its `mix loopex.status` step, +validates the resulting documentation structure and reconstructed status +summary. Third, the final +semantic documentation gate inventories every file under +`docs/operator/` and `docs/developer/`, records why each is relevant or not, +and checks every relevant page against the implementation, plan, accepted +ADRs and its peers, then separately rechecks the predeclared `DEVELOPMENT.md` +row against the implemented release script. Fourth, the recomputed administrative archive matches every +non-documentation entry in the tested archive except root `README.md` and +`SOURCE_IDENTITY`. The README is validated by complete-patch confinement, +marked-block reconstruction and the documentation/status gate; exactly one +source-identity file appears in each +archive and each value is validated against its own commit and source identity. +Nothing else re-runs — no suite, no release +check and no provider credential. The complete release-proof outputs and both +manifests remain outside the repository. Only after they pass is the immutable +annotated `v0.2.0` tag created on the administrative SHA; its annotation names +both SHAs and records every proof's result, retained-output reference and +SHA-256 digest, both manifest references and digests, and both validated +`SOURCE_IDENTITY` values. The evidence page is not amended, there is no third +commit, and no proof named by the annotation postdates the tag. The tag's +commit must be reachable from `main` and carry `VERSION` exactly `0.2.0`. +Publish no package, binary, installer or service unit. ### The Daemon's Operator Contracts @@ -888,41 +1078,99 @@ or the daemon refuses the arguments. #### `loopex daemon`: starting, readiness, stopping -**Composition inputs.** A daemon is a host, so it takes the same inputs the -app-server host takes today, as flags with environment fallbacks, and refuses -the same way — `LoopexAppServer.Host` documents them and halts on standard -error when one is missing or unusable. The daemon's set, each with its default -and its refusal class: +**Command grammar.** The complete startup form is: + +```text +loopex daemon [--state-root ] [--workspace ] + [--provider-launch ] [--policy ] + [--cleanup-grace-ms ] [--socket ] +``` + +The startup form takes no positional argument. Every flag takes one nonempty value, +may appear exactly once, and accepts both `--flag value` and +`--flag=value`. A bare `--` ends option parsing, after which any word is a +refused positional argument. An unknown flag, duplicate flag, missing or empty +value, or any positional argument is a parser refusal before placement, Store, +socket or component work. There is no credential flag and no project-resource +flag: those inputs have the sources below. + +The explicit offline-import form is separate: + +```text +loopex daemon prepare-index [--state-root ] +``` + +It accepts exactly the same state-root flag and `LOOPEX_HOME` precedence and +validation as startup, and no other flag or positional argument. It does not +require or read workspace, provider-launch, policy, credential, cleanup-grace, +project-resource or socket inputs because it composes none of those edges. The +`prepare-index` word must be the first argument after `daemon`; it may appear +exactly once and cannot appear after `--`. Its `--state-root` flag takes one +nonempty value, appears at most once, accepts both value forms, and follows the +same empty-flag, empty-environment and no-fallback rules below. Unknown, +duplicate, missing-value, empty-value, `--`-followed-by-word and extra-positional +forms refuse before placement or Store acquisition. The command then acquires +only those two exclusions in the order and with the cleanup contract specified +for offline import below. + +**Composition inputs.** A daemon is a host, so it takes the same input kinds +the app-server host takes today, but each input follows the exact flag, +environment, default or discovery source below. Where both a flag and +environment variable are listed, a present flag wins. The parser refuses an +empty flag value without consulting the environment; with no flag, a nonempty +environment value is used and an empty value is missing. An invalid flag value +never falls back to the environment. The daemon refuses with the typed class +and exact status below when an input is missing or unusable: | Input | Flag / environment | Default | Missing or invalid | | --- | --- | --- | --- | | State root | `--state-root` / `LOOPEX_HOME` | none | `state_root_required`, or `state_root_unusable` when it cannot be created or read | | Workspace | `--workspace` / `LOOPEX_WORKSPACE` | none | `workspace_required`, `workspace_unusable` | | Provider launch | `--provider-launch` / `LOOPEX_PROVIDER_LAUNCH` | none | `provider_launch_required`, `provider_launch_invalid` | -| Policy | `--policy` / `LOOPEX_POLICY` | **none, deliberately** — authority is the operator's to name, as the app-server host already insists | `policy_required`, `policy_unknown` | -| Provider credential | `LOOPEX_PROVIDER_API_KEY` | none | `provider_credential_required`, checked at start so an unattended launch refuses in a second rather than at the first dispatch. The daemon reads it once, deletes it from its environment and holds it in custody under ADR 0034 | +| Policy | `--policy` / `LOOPEX_POLICY` | **none, deliberately** — authority is the operator's to name. The daemon command's host-owned registry is exactly `allow-all` and `shell-allowlist`, the two policies the released reference CLI already owns; the app-server-only `ask` value is not admitted here | `policy_required`; `policy_unknown` for any other value, including `ask` | +| Provider credential | `LOOPEX_PROVIDER_API_KEY` only | none; absent and empty are the same missing input | `provider_credential_required`, checked at start so an unattended launch refuses in a second rather than at the first dispatch. The daemon reads it once, deletes it from its environment and holds it in custody under ADR 0034 | | Cleanup grace | `--cleanup-grace-ms` | the composition default | `cleanup_grace_invalid`, and the admitted domain is **an integer from 1 to `18_446_744_073_709_551_615`**, exactly core's own (`@max_cleanup_grace_ms`, `apps/loopex/lib/loopex/executor.ex:75`, and `grace_ms >= 1` at `:456`). Zero is refused, which the local executor's own validation would admit (`apps/loopex_executor_local/lib/executor.ex:897`, `>= 0`): a daemon composed with zero would carry a grace core cannot derive bounds from. A very large value is **accepted, not refused** — the daemon never passes it to a `receive … after` unsliced, for the reason the wait rule below gives | -| Project resources | as the host already takes them | as today | as today | +| Project resources | discovered from the selected workspace through `LoopexComposition.ResourcePacks`, as the app-server host does | an empty manifest when no `.agents/skills` exists | `project_resources_unusable` when workspace identity, discovery or manifest validation fails | | Socket path | `--socket` | `/daemon/daemon.sock` | `socket_path_too_long`, `socket_permission_unverified`, `invalid_socket_path` for a path outside the root's `daemon/` directory | -Every one of these is refused **before** the marker is acquired where that is +Every one of these is refused **before** the placement lock is acquired where that is possible, so the common operator mistake costs nothing and leaves nothing behind; the ones that can only fail later are covered by the reverse-cleanup rule. +The extracted host utility has one typed boundary rather than the CLI's current +rendered strings: +`LoopexComposition.Placement.acquire/1` returns `{:ok, owner_handle}` or exactly +`{:error, {:placement_active, os_pid}}`, +`{:error, {:placement_unverifiable, reason}}`, or +`{:error, {:placement_lock_failed, reason}}`; `release/1` is idempotent `:ok` +and uses the acquisition-specific owner handle, but ignores path-removal and +directory-sync results. Callers therefore treat it as a best-effort attempt, +not proof that the lock path is absent. The daemon, failed-start cleanup and +`prepare-index` run it in an unlinked monitored helper under the fixed absolute +`placement_release_ms: 5_000` deadline. Exact `:ok` followed by normal helper +`DOWN` completes the phase; malformed result, abnormal death or timeout is +`placement_lock_failed`, with timeout hard-halting and leaving the exact-handle +residual for verified stale-owner recovery. `LoopexCli.Placement` migrates +to that module and renders the same operator messages it renders today. The +daemon maps the three tuple heads to the three startup classes of the same +names, keeping diagnostic detail on `stderr` without making prose part of a +control contract. + A `--socket` override is constrained exactly as the default is — its parent directory must be owned by the daemon's user and mode `0700`, no component below the state root may be a symbolic link the daemon did not create, and the socket is created `0600` and verified after bind — **and it must resolve inside the selected root's `daemon/` directory**. A path outside it is refused -at startup with `invalid_socket_path`, before the marker is acquired. +at startup with `invalid_socket_path`, before the placement lock is acquired. That last constraint is not tidiness. Socket ownership in this design is -derived from the writer marker, and a marker is per state root: two daemons on -two different roots hold two different markers and have no exclusion between +derived from the host placement lock after the Store marker is acquired, and +both are per state root: two daemons on two different roots hold different +locks and markers and have no exclusion between them at all. An override that let them name one path would put two daemons with equal claim on one file, which no rule in this plan can adjudicate. -Inside one root there is exactly one marker holder, so there is exactly one +Inside one root there is exactly one placement holder with an opened Store, so there is exactly one daemon entitled to bind, and exactly one entitled to remove a pathname a predecessor left. An override therefore moves where the rule applies, never which root it applies within. @@ -936,14 +1184,36 @@ then be ambiguous to the process manager parsing it: {"record":"daemon_ready","root":"…","socket":"…","incarnation":"…","version":"0.2.0"} ``` -It is printed **only after** all of: the Store is open and its writer marker -held, the `0700` subdirectory and `0600` socket exist with their ownership and -mode read back and verified, and the listener is accepting. A process manager -that waits for that line is waiting for a daemon that can actually serve, -which is why it is printed there and not earlier; anything sooner would invite -a client to connect to a socket the daemon has not finished checking. Every -diagnostic, warning and failure goes to `stderr`, so `stdout` carries the -readiness line alone and stays machine-readable. +The write is launched **only after** all of: the placement lock is held, the +Store is open and its writer marker held, the `0700` subdirectory and `0600` +listening socket exist with their ownership and mode read back and verified, +and the listener owns that socket and has acknowledged its parked startup gate. A +monitored, disposable writer helper performs the one `stdout` request under the +command process's fixed absolute `startup_output_deadline_ms: 5_000`. That +command process is the lifecycle sentinel and the sole startup-disposition +arbiter. It serializes signal-handler stop, helper result or death, its absolute +deadline, the owner's component-fatal notice and the owner's post-success +release authorization. Exact helper success merely asks the owner to consume +queued exits and recheck the deadline and every required component; only the +resulting exact authorization consumed before another disposition lets the +sentinel send `begin_accept`. + +The helper, signal handler and owner are different senders, so the plan does +not infer physical order from their mailboxes. It instead fixes the sentinel's +observable first disposition. Stop, component fatal, completed IO refusal, +helper death or deadline first leaves the gate parked; later candidates are +cleanup-only, and the line may already have reached `stdout` because a completed +IO write cannot be recalled. Release authorization first lets the sentinel open +the gate; a later stop or component exit takes its running path. Deadline +hard-halts as `readiness_write_failed`, because a queued IO request cannot be +recalled safely. +Thus the line proves that every startup prerequisite had been established when +the bounded write was launched, while successful write disposition plus the +exact gate release is what permits the first accept. A client that connected +while the listener was parked remains in the kernel backlog until that release, +or is closed without creating daemon state. Every diagnostic, warning and +failure goes to `stderr`, so `stdout` carries at most the one machine-readable +readiness line. **Stopping.** Sent **to the escript**, `SIGTERM` begins the orderly shutdown below and is the only signal that does. Sent **to the launcher**, @@ -957,32 +1227,102 @@ against the process, and a client-issued stop would let one connection end every other client's session residency, which is authority the socket does not carry and this milestone does not grant. -**Exit status.** `0` when an orderly shutdown completes, whatever the sessions -were doing. Non-zero, with one reason line on `stderr`, for every fatal exit, -naming its class rather than a stack. The classes are the fatal-class map's, -in full, and this list is derived from it rather than summarising it: - -- **at startup**, before any socket exists: `store_writer_active`, - `store_writer_unverifiable`, `store_log_too_large`, `socket_path_too_long`, +**Exit status.** `0` when an operator-requested stop completes, whether it +reverse-cleans an interrupted startup before readiness or runs the full orderly +shutdown after readiness, whatever the sessions were doing. A successful `prepare-index` also exits `0`, writes nothing to +`stdout`, and never emits a readiness record; its ordinary progress and warnings +go only to `stderr`. An offline-command parser refusal uses the reference CLI's +existing status `1`, prints its bounded reason or usage on `stderr`, and performs +no placement or Store work. An operational offline-import refusal reuses the +applicable state-root, placement, Store or index class and unique integer below, +prints no readiness or wire record, and attempts one bounded diagnostic on +`stderr`. Every fatal exit uses its class's unique integer from the complete +map below; status is authoritative, and a disposable unawaited helper attempts +one reason line on `stderr`. The line may be absent when stderr is blocked. The +classes are the fatal-class map's, in full, and this list is derived from it +rather than summarising it: + +- **during startup**, before the sentinel's exact `begin_accept` send: the + readiness line may already be visible when a stop, component fatal or + readiness disposition wins, but no accepted client or wire state exists: + `placement_active`, + `placement_unverifiable`, `placement_lock_failed`, `store_writer_active`, + `store_writer_unverifiable`, `store_writer_acquisition_failed`, + `store_log_too_large`, `socket_path_too_long`, `invalid_socket_path`, `socket_permission_unverified`, - `session_index_too_large`, and one class per missing or invalid composition - input; + `session_index_too_large`, `session_index_corrupt`, + `session_index_upgrade_required`, `session_index_write_failed`, + `signal_install_failed`, `credential_plane_start_failed`, + `composition_start_failed`, `daemon_services_start_failed`, + `listener_start_failed`, `readiness_write_failed`, and the explicit + composition-input classes `state_root_required`, `state_root_unusable`, + `workspace_required`, `workspace_unusable`, `provider_launch_required`, + `provider_launch_invalid`, `policy_required`, `policy_unknown`, + `provider_credential_required`, `project_resources_unusable` and + `cleanup_grace_invalid`; +- **during offline import**, which has no readiness or wire surface: + `state_root_required`, `state_root_unusable`, `placement_active`, + `placement_unverifiable`, `placement_lock_failed`, `store_writer_active`, + `store_writer_unverifiable`, `store_writer_acquisition_failed`, + `store_log_too_large`, `store_lost`, `session_index_too_large`, + `session_index_corrupt` — including a conflicting canonical and legacy + placement identity — and `session_index_write_failed`; - **while running**, one per linked component in the fixed set: `store_lost`, `store_capacity_exceeded`, `runtime_lost`, `transfers_lost`, `workspace_lease_lost`, `executor_lost`, `registry_lost`, `custody_lost`, - `capability_lost`, `relay_lost` and `listener_lost`. A lease owner's death is **not** in this + `capability_lost`, `relay_lost`, `connections_lost` and `listener_lost`; + `drain_failed` names an orderly stop whose core census became unavailable + and therefore continued as crash-equivalent teardown. A lease owner's death is **not** in this list: it is session-scoped, closes that session's controller with `control_owner_lost`, and the daemon keeps running; -- **from the signal handler**, `owner_lost`, the one class no component - produces: a signal arrived and the owner that would run the shutdown is not - there to receive it. +- **from the command-process monitor**, `owner_lost`: the unlinked daemon owner + died before sending a matching fatal latch. A prior latch keeps its first + class and status; owner death requires no signal. #### How a session is created and driven over the socket `loopex attach` alone cannot start work, because a session has to exist and be -resumed before anything can be sent to it. The daemon forms of the two -released commands are what reach the socket: +resumed before anything can be sent to it. The complete live client grammar is: + +```text +loopex run --daemon + [--steer | --follow-up ] + [--skill ]... + [--skill-resource :