An attachment send that reached the owner but whose landed check missed comes back as text under its
original submission id. Enter on it was refused `admission_conflict` (same id, other payload): the
words stayed in the composer under a "Prompt failed" card, although the send had run once.
`admission_conflict` alone proves nothing (route, binding and lineage checks raise it too), so the
three checks that DO prove "this principal's id on this target is already admitted" now name it:
`field=request_id` (hermes_state_runtime.ADMITTED_REQUEST_CONFLICT) in admit_session_input,
retry_terminal_admission and the attachment-bytes check. Desktop settles exactly that refusal as the
dedupe it is (a `terminal` receipt: bubble dropped, journal retired, draft cleared, no new id).
Every other conflict, and a backend that names no field, stays a visible failure. An edited restored
draft already drops its id (matchingDraftRetry), so a deliberate edit is a new message.
The tool gateway now tags execute results with dataUse.requires (no_training,
zero_retention). Hermes keeps that as `data_use` metadata on the tool message
(content unchanged; a batch carries the union), persists it inside the existing
display_metadata column (no migration; /branch, resume and compaction copies
keep it), and strips it from every provider request. The Nous profile reads the
union over the outgoing messages and sends provider.data_collection=deny (+ zdr
for zero_retention) on both the chat-completions and Anthropic Messages paths;
no other provider sees it. A 403 data_policy_denied classifies as its own
non-retryable reason with no fallback and copy that tells the user to switch
model, compress, or start a new session.
Since #106742 every Kanban card runs in a gateway managed worker, and
ef52a09a55 removed the delegation toolset there: a delegated child needs
its own owner-registered execution (review r4224751560 / r4230769955), and
_open_child_session_db refused with worker_child_registration_required.
The rule stays; the missing owner side is built:
- child.reserve (gateway/session_worker_child.py): a worker asks on its own
fenced receipt stream. The owner verifies the parent's claim, mints the
child's session row (source subagent, parent lineage, parent profile,
_delegate_from marker) and a kind='child' execution bound to the parent's
verified pid/birth, the worker's fresh secret and the connection
principal, under the parent's id prefix. Caps come from the root
session's frozen policy (delegation.max_concurrent_children,
max_spawn_depth); a refusal or draining owner is a receipt, so the
parent's journal never sticks.
- ChildSessionStore (agent/runtime_session_child.py): the child persists
through ordinary worker.persist under its own claim, writes only its own
row, never binds the process delegation ledger, finishes on close.
- Retirement: every terminal transition of an execution (finish, loss,
settlement) retires its live children and ends their rows; an owner
restart retires old-epoch children (never adoptable) while the root alone
becomes unknown.
WORKER_DISABLED_TOOLSETS is gone because the only child path in a worker
now goes through the reservation.
Fixes#141793
The creator upsert (`COALESCE(NULLIF(created_source,'unknown'), excluded)`)
let any upsert carrying source='local' turn an 'unknown' placeholder into
'local'. A later real creator could not repair it, and the compression
ancestor stamp copied 'local' onto unset ancestors. On main the row stayed
'unknown'.
created_surface() already says 'local' is not a surface. The store side now
names one unset set (_UNSET_CREATED_SOURCES / _UNSET_CREATED_SQL: NULL, '',
'unknown', 'local') and uses it in the creator upsert, the managed-worker
heal and the ancestor stamp. An upsert never writes 'local' over anything,
and a row already holding 'local' is repaired by its creator.
Test: test_routing_label_local_is_not_creation_provenance (red on the
previous head).
The managed-worker usage heal matched `created_source IS NULL OR
created_source = 'unknown'`, a third spelling of the unset set next to
the creator upsert's NULLIF(created_source, 'unknown') and
_UNSET_CREATED_SOURCES. Use `NULLIF(created_source, 'unknown') IS NULL`,
which matches exactly the same rows.
The managed-worker usage heal only filled created_source IS NULL. A row
whose column auxiliary usage had set to the 'unknown' placeholder was
never repaired on this path and stayed out of every surface listing,
while the creator upsert (NULLIF(..., 'unknown')) and
stamp_compression_ancestors already treat 'unknown' as unset. Treat it
as unset here too.
An earlier commit in this series (fix(cli): list a compression tip by its own
created_source) let a filtered list admit a compression
root whose chain tip matched, through a correlated EXISTS(WITH RECURSIVE ...)
OR'd into _source_match_clause. That predicate defeats the MULTI-INDEX OR
plan on idx_sessions_local_created_started, so every `--source` list
(in-chat /sessions, `hermes sessions list/browse`, TUI pickers) scanned the
table and walked a chain per row. It also copied _CHAIN_STEP_SQL's edge and
order SQL into hermes_state_common, two copies that could drift (#114271).
Move the guarantee to the writer instead. When a write fills a session's
created_source (the creator upsert behind update_token_counts, or the managed
worker's usage.main heal), stamp_compression_ancestors copies it onto
compression ancestors that are still NULL/'unknown', in the same transaction.
Each hop must be the parent's preferred continuation per the one
_CHAIN_STEP_SQL. In this commit the walk stops at the first ancestor that
already has a surface. Later commits in this series walk through ancestors
already on the same surface, so a NULL root behind a stamped segment is still
repaired, stop at another surface or a non-continuation edge, and skip the
walk after one query when no ancestor is unset. The list filter is back to main's indexed predicate, and the
duplicated chain SQL is gone.
Measured on a 32k-row store (local benchmark, limit 50,
best of 3):
--source walk on this commit origin/main
acp 93.4 ms 0.8 ms 0.8 ms
gui 94.9 ms 4.6 ms 0.8 ms (now also matches desktop rows)
cli 14.3 ms 13.8 ms 13.3 ms
Chains whose tip was healed before this commit keep a NULL root until the
next usage write on the tip. On main that conversation was not listed
either.
Copy a real parent surface. local and unknown are not stored. Automatic
compression does not create the child again, so a NULL column stays open
for update_token_counts(source=...) and for the managed worker's usage
payload. Auxiliary usage must not write unknown into that NULL first.
A turn the gateway restart/shutdown interrupts before any assistant text is
already closed by the agent's core closer (_close_durable_failed_turn) with
"Send it again". Settlement then appended the restart notice on top, so the
transcript held two Hermes boundaries, and an automation turn kept the resend
advice next to the neutral copy.
The claim now records the transcript high-water mark (messages.id is
AUTOINCREMENT across sessions). When settlement writes an owner-stop notice and
the tail is a failed_turn row above that mark, it is this turn's own boundary:
its copy is replaced in the same transaction. An earlier turn's boundary stays
and the notice is appended as before.
Test drives the real AIAgent flush and the real core closer on a real SessionDB.
Refs #134889 (GW-21)
F1's owner-stop reason rode only on the live message.complete frame, so a
viewer that reconnected after the restart (the usual Desktop case) read an
interrupted turn with no reason. finish_result now commits the same notice
as a Hermes transcript row (display_kind failed_turn, through GW-10's
close_discarded_turn) inside the settlement's own write:
settle_session_input takes a same-transaction _terminal_write like
resolve_unknown_session_input does. A rolled-back settlement takes the
notice with it, and a retry that finds the row terminal returns before
writing, so it is never written twice. The live warning stays. A user Stop
writes nothing; an unattended turn gets the neutral automation copy (GW-20).
Refs #134889 (GW-21)
Refs #134889 only
A second `hermes peer dm` that arrived in the local Bot Chat while an
oversized DM's turn ran stayed queued as a `local_automation_v1` row whose
descriptor `target` named the pre-reset transcript. LC-23's deferred reset
rotated the route and rehomed only `messaging:` rows, so the drain refused
the queued DM (`admission_conflict`) and paused the Bot Chat's FIFO for good,
across gateway restarts: every later DM, bot relay and cron delivery into it
wedged.
A LOCAL FIFO's owner is its receipt id and survives the reset, so nothing
moves between FIFOs. The reset now rotates the route and, in the same ordered
worker step, retargets the owner's queued `automation:<route>` rows that name
a transcript of the old lineage at the fresh one (`retarget_local_automation`:
one SQLite transaction, admission id, request id and seq kept, digest
re-keyed, nothing moved behind an `unknown` head). /new and /stop are
unchanged (they cancel on purpose).
Red -> green: a real-daemon race test beside the LC-23 one fires the oversized
DM, a racing DM 0.4 s later, then a third DM. On a40e0c7b15 the racing DM
never answers and the log shows `paused: admission_conflict`; now both are
answered on the fresh session, stored there once, and no row stays queued.
Review finding (package 10 independent review, round 2) on #140968
Refs #134889 (LC-23)
Refs #140719
- Dispatch under the store's own profile home: `sessions repair-profiles`
deletes from another profile's store, and the event now reaches that
profile's plugins instead of the launch profile's.
- Archive events list every hidden chain row (deleted_ids), on both the
SessionDB and the runtime-receipt path; the requested id stays primary.
- Fire right after the commit, before media/transcript cleanup that can
raise, so a cleanup failure no longer swallows the event.
- mutate_runtime_session's write returns (result, SessionGoneEvent | None)
instead of filling a shared list.
- Drop the leftover duplicate hook reference block in hooks.md.
Finn's state-layer hook missed the paths Desktop actually uses: single
delete and archive go through the canonical mutation receipt
(mutate_runtime_session), not SessionDB.delete_session, so a plugin never
heard about either. Archive (the "this is done" signal #132639 asked for)
fired nowhere.
- mutate_runtime_session fires after its write commits for operation
'delete' and for a real unarchived -> archived sidebar flip; an exact
retry replays the receipt and stays silent.
- set_session_archived fires reason="archive" on a real flip, so TUI
session.archive, `hermes sessions archive` and deferred TUI archives are
covered from one place. Repeats, un-archives, the idle auto-archive
sweep and profile adoption (notify=False) stay silent.
- Payload is now session_id + reason + profile on every path (profile
from the store's home), deleted_ids when more than one row went;
primary id is the one the caller asked for, not the alphabetically
first.
- One fail-open seam (emit_session_deleted) calls lifecycle.invoke_hook
directly; the extra notify_session_deleted wrapper is gone.
- Tests trimmed to two invariants against the real hook registry.
Co-authored-by: Lucas Piera <pieralukasz@gmail.com>
prompt.cancel can read a row queued just before prompt.steer_queued commits
it as terminal 'steering'. cancel_session_input then treated the row as an
ordinary terminal no-op, cancel_or_claimed returned None (its "cancelled"
answer), and the cancel succeeded while the transfer went on and settled
steered.
A steer in transfer reads as its running claim (`started`) and settles with
it, so cancel_session_input now refuses it the way it refuses a started row:
stale_generation. Nothing is committed, the cancel obligation is released,
and cancel_or_claimed passes the named refusal on rather than stopping the
receiving turn, which is a different prompt's execution. The prompt.cancel
contract ("a started one is unaffected") is unchanged.
Refs #134889 (RT-35)
Refs #140208
Review nits on the queued controls: the transfer requeue SQL was written
twice (settle_steer_transfers, revert_steer_input), retire_replaced_input
repeated cancel_session_input's UPDATE, and the steer exact-retry test
appeared both in steer_session_input and in prompt.steer_queued. Each now
lives once (_requeue_transfer, _CANCEL_QUEUED, steer_replayed). No
behaviour change.
Refs #134889 (RT-35)
Refs #140208
Desktop's queue panel rendered only Delete for a server-owned (canonical)
queued row. The guard was deliberate: the gateway had no verb that could
steer or edit a queued admission, and composing prompt.cancel with
session.steer or with a resubmit is two writes. The drain can claim the row
between them, so the prompt either runs twice or is lost.
Add two owner verbs that consume the still-queued admission in the owner's
own write transaction:
- prompt.steer_queued {admission_id}: only while the running claim has
adopted its agent (else steer_unavailable, before the row is touched: it
stays queued and runs in FIFO order). The row goes queued -> terminal
'steering' bound to that claim's (owner_epoch, generation), so the drain
can never also claim it, and the text is then handed to the claim's agent
while that execution still runs. The transfer settles in the claim's own
terminal write: 'steered' when the claim completed with the text
delivered, 'interrupted' when it ended any other way (never replayed),
and queued again in its own FIFO place when the text never reached the
agent (the turn ended first). An owner restart settles a transfer left
open as 'interrupted'. Until settled the receipt reads 'started'. The
fence is an in-memory transfer record changed under the session stream
lock; the SQLite writes run outside that lock, so a held writer never
stalls the owner loop (loop-side receipts, attaches and publication take
it).
- prompt.replace_queued {admission_id, submission_id, text, ...}: cancel
the queued row inside the admission write of its successor, which joins
the back of the FIFO under a NEW admission identity. That write also
binds the new identity to the row it retired; the exact-replay path
checks the binding inside the same transaction, so a retry naming the
same old admission answers the same replacement and any other old
admission under that submission_id is admission_conflict. Ordinary
prompt.submit payloads are unchanged.
Refusals: admission_started, session_idle, steer_unavailable,
admission_conflict, queue_full, unsupported_control, not_found.
Each pending row names the queued-row verbs its owner serves (controls:
steer/replace): text-only rows of sessions launched from an interactive
local surface (cli, tui, gui, acp), whose observers settle a steered or
cancelled row. Hosted-room, cron, kanban and a2a producers read a saved
result for any other outcome, so their rows are never offered either verb
and both verbs refuse them (unsupported_control). Desktop shows Steer and
Edit on a canonical row only when the row lists them, so an older gateway
keeps Delete only. Canonical rows never get Next: reordering would break
the owner's one FIFO. Local rows are unchanged.
Edit loads the row into the composer; Save calls prompt.replace_queued and
keeps the edit open until the owner answers. A refusal, or the owner
starting the row mid-edit, keeps the edited text in the composer as an
unsent draft (followed by the draft it interrupted) with a short notice.
The composer holds presentation state only; the owner's FIFO never pauses.
Both verbs are declared in tui_gateway/contracts (generated TS/OpenRPC
regenerated).
Refs #134889 (RT-35)
Refs #140208
Each gateway.admission.result.v1 row kept the reply twice: in
final_response and again as the content of this turn's closing assistant
message in the compacted suffix. Rows are reclaimed only when the session
is deleted, so on a live session result storage grew at about 2x the
reply per turn (2,000-char reply: 4,307 bytes per row).
The store's one result writer (settle_session_input and the
resolve-unknown capture) now runs encode_result after compact_result.
When the last assistant message's content is exactly final_response, it
stores that content as null and adds a top-level envelope,
_stored: {v: 1, reply_ref: <message index>}. The row's top level is
gateway-built (result/usage), so no message field can be mistaken for it;
a result that already has the key is stored verbatim. load_result decodes
only a row carrying that exact envelope, back to the identical dict;
every other row, including all rows written before this, is returned as
stored, whatever fields its messages carry.
Every read of a stored row goes through load_result: admission_result
(Bot receipt outcome, Responses/chat replay, run projection, cron, A2A,
hosted RPC), finish_result's delivery-after-settlement read, and
retirement, which decodes before dropping the transcript fields, so a
deleted session keeps the same exact-retry outcome as before. A reply
that differs from the message (media tags, sanitizing) is stored
verbatim. No expiry, no new verdict, no change to admission identity.
A build from before this change reading a new row sees the reply only in
final_response (the last assistant message's content is null), so a
rollback across this change is not transparent.
Same probe: 2,341 bytes per row, about 1x the reply.
Refs #134889 (LC-9)
Refs #140208
When a native messaging turn exhausted its context, the auto-reset rotated
the route to a new standalone session but left the messages already queued
behind that turn (B, C) on the old owner. The old drain then refused them
(admission_conflict) and paused, so they never ran, while a message
admitted after the reset (D) ran on the new session ahead of them.
The reset now re-homes the old owner's still-queued messaging:* admissions
onto the fresh session in one SQLite transaction (rehome_queued_inputs):
each row keeps its admission id, request id and seq, so FIFO order holds
and a transport retry of a moved message still dedupes. The reset and the
re-home run under the old owner's mutation_lock, and the write is ordered
with native admissions. The exhausted turn is started, so it is never moved
or replayed. Reset semantics are unchanged (new standalone session, no
lineage edge); /new and /stop still cancel queued messages.
Salvage of #139673 by @helix4u (smaller redo: re-home the queued admissions
instead of modelling the reset as compression lineage). Headline test
adapted from theirs.
Co-authored-by: helix4u <4317663+helix4u@users.noreply.github.com>
Accepting a pick on a running session now writes the request's
gateway.mutation.v1 receipt in the same transaction as the pending
pick. An exact retry of pick A after pick B was accepted returns A's
original result and no longer overwrites B. The stored pick also
carries a stable application id ('deferred-pick:<request_id>'). A
restart between committing the model and deleting the pending pick
finds that receipt and does not apply the pick a second time.
mutation_receipt_key() is now shared by mutate_runtime_session and
defer_pick.
Review finding on #139604 (Greptile)
kanban.run decided whether a retry keeps its pre-finite payload by listing
every admission of the session (pending_only=False) and filtering in
Python, with a synchronous SQLite read on the owner loop.
SessionAuthority._submit already ran the exact-key query inline for
attachment retries.
Move that query into hermes_state_runtime.find_session_admission(), one
indexed read on the UNIQUE (principal_id, target_session_id, request_id)
key, and use it in both places. session_authority keeps the same behaviour
(same SQL, same row shape, None when absent). kanban.run now runs the read
off the loop. The store's conflict check is unchanged. A retry still
resubmits the committed payload under the same identity.
Tests: a kanban_owner fixture replaces the duplicated setup in the durable
Kanban tests. The pre-finite retry test now fails if the session listing
is used. A new test pins the helper to the exact key.
Refs #134889 (KB-1)
Refs #139162
Addresses review by @kshitijk4poor on #139274.
From @kshitijk4poor's review of #139275:
- An explicit pick of a DISABLED MCP server matched no allowlist entry
and fell through to every enabled server. It is refused by name, as
main refused it (a disabled server never registers).
- A server literally named `mcp-foo` beside `foo` keeps its own name
in _merge_mcp_servers.
- An unusable editor MCP server spec no longer echoes pydantic's
`input_value=` (a server's argv may hold a credential): the detail
is `loc: type` pairs, or the exception type.
- RuntimeStoreError itself bounds and flattens `field`/`detail` (one
line, printable only, 80/160 chars), so every raiser, not only
session_policy's _refuse, is safe to log and fits the client frame.
- A bypass launch validates an explicit pick against the in-process
registry alone, never the profile's plugin state.
From @dvbaecker's follow-up (c66cf0d16e): the create path's remaining
bare refusals name their check: `hidden`, a bypass launch with no
`model`, `request_id`, a resumed `request_id` with a different frozen
request, and skipped `-s` rendering.
Co-authored-by: Daniel V. Baecker <295684751+dvbaecker@users.noreply.github.com>
`session.create` refused with a bare `invalid_params`: `gateway/session_policy.py`
carries 17 `raise RuntimeStoreError('invalid_params')` sites and no logger, so the
client printed the code alone and `gateway.log` stayed silent. Three reports in one
morning (#138670, #138748, #134889) could not tell which check had rejected the
launch, and the message reads like a provider failure rather than a rejected launch
argument.
`RuntimeStoreError` now carries `field` and `detail` beside the reason. The reason
string does not move (callers compare `str(exc)` against reason codes), the JSON-RPC
error's `data` gains both when the raiser named them, and
`gateway/session_controls.py` logs one line per refusal. The CLI's copy reads the same
two keys off `GatewayRPCError.data`, so the panel reads
`invalid_params (run_budget: must be a positive number of seconds)` instead of
`invalid_params`.
All 17 sites name their field, with the value that broke the check wherever there is
one: the unknown create key, the unknown toolset name, the unreadable cap. A test
walks the module's AST and fails on a new bare raise, so the next create check cannot
land unnamed.
Refs #134889
Review follow-ups:
- An ACP session/load with mcpServers=[] on a session holding editor
servers runs the editor_mcp removal and stops the held processes; a
resume that omits the list keeps them.
- A branch runs its prepare-only fences (receipt, revision, generation,
idle) before discovering the child's editor servers, so stale, busy and
exact-retry branches start no servers.
- The admission-start re-freeze goes through session.mutate's own writer
(write_mutation) instead of a second copy of it.
Refs #134889
Mechanism: retirement moves a deleted session's terminal evidence into
state_meta (gateway.terminal_admission/identity/worker, the compacted
gateway.admission.result with final_response, gateway.retired_session) and
nothing ever deleted those keys. prune_sessions and the empty-session sweep
go through retire_prunable, so automatic maintenance of a cron-heavy store
moved rows into state_meta instead of reclaiming them, and a deleted
session's reply text stayed on disk indefinitely. Main's delete/prune kept no
copy.
Fix (maintainer ruling: exact-retry horizon 7 days, keep final_response so a
retry inside it replays byte-exact): every tombstone write stamps retired_at
(terminal admission, terminal worker, retired-session marker; re-retiring a
recreated id restarts its horizon). prune_retired_tombstones(conn,
older_than=7d) deletes expired terminal admissions together with their
identity pointer and compacted result, expired workers and markers;
tombstones from before the stamp existed are stamped on the first pass and
age from there. prune_sessions (the maintenance prune pass) calls it in the
same transaction as retire_prunable. _row drops the stamp so replays keep
their shape.
Test: tests/hermes_state/test_terminal_retirement.py::
test_tombstones_past_the_retry_horizon_are_reclaimed_by_the_prune_pass is red
on r13-integ1 (a session deleted 8 days ago keeps all four tombstone rows; one
deleted 6 days ago still answers its exact retry with the original reply).
Review: ahrazzle B2-06
Mechanism: admit_session_input skipped ADMISSION_QUEUE_MAX whenever the session had an `unknown`
admission (round-12 exemption: "recovery decides that backlog"). An unknown turn persists until an
operator Discard, so a busy chat or API client kept adding queued rows without limit, and every one
of them ran as its own agent turn after Discard. Main's busy queue (_BUSY_QUEUE_MAX_PENDING=32) is
unconditional.
Fix: count only queued rows and refuse past the cap in both states with the same queue_full
(messaging already maps it to the plain "too many messages are waiting" notice). The unknown head
is the in-flight turn, which main never counted either.
Red on r13-base2: tests/gateway/test_admission_queue_cap.py::
test_queued_inputs_past_the_cap_are_refused_queue_full_and_retries_replay (DID NOT RAISE while paused).
Review: ahrazzle B2-07
Mechanism: every surface admits through hermes_state_runtime.admit_session_input,
which inserted with no pending-count check. Main capped a session's busy
queue at _BUSY_QUEUE_MAX_PENDING=32 (run_busy.py); the authority FIFO bypasses
that path, so a flood during one long turn grew the queue without bound.
Fix: inside the admit write transaction, after the exact-replay lookup (a
retry of accepted input is never refused), count the session's `queued` rows
and refuse a NEW admission at ADMISSION_QUEUE_MAX (32, main's value) with
RuntimeStoreError('queue_full'). A FIFO paused behind an `unknown` turn is not
capped: recovery owns that backlog.
Red on r12-integ1:
tests/gateway/test_admission_queue_cap.py::test_queued_inputs_past_the_cap_are_refused_queue_full_and_retries_replay
(real SQLite admissions through authority.submit; the 33rd queued input was accepted).
Review: dokterdok N62
(cherry picked from commit 21321817c9e30bd84361e1edbaeae6ef0928dc4e)
A managed worker's AIAgent holds a RuntimeSessionStore as its session_db. The store is new
in this PR and was built call by call, so reviewers found the gaps one at a time (the lease
refresh's patience_s keyword, d93039f5b4a). A mechanical sweep of every <x>._session_db /
session_db / lease-facade db call in run_agent.py and agent/*.py against the store found two
more SessionDB methods the store lacked:
- latest_conversation_role: _close_durable_failed_turn's idempotence probe. The
AttributeError was swallowed by its best-effort guard, so a failed managed turn never got
its Hermes-authored boundary and the next prompt merged into the failed request.
- get_message_role: in-place compaction's held-row liveness checks
(held_archive_watermark, the absorbed-row tail count). The AttributeError aborted the
in-place commit, so a managed worker's in-place compaction always rolled back.
Both are closed, read-only receipt operations on the owner's transaction
(session.tail_role, session.row_role), scoped to the worker's own transcript like every
other worker read.
Test: tests/agent/test_runtime_session_store_surface_parity.py parametrizes over every core
call site (fails on r11-base for get_message_role, latest_conversation_role and
refresh_session_turn_lease), plus an owner-parity check of the two reads.
Review: Adolanium reg-1 (class sweep)
(cherry picked from commit 4e7b4ff8cfc23a01c6dc98f33fca64cee626b423)
_claim_next validates the queued head it read (first): the hosted source owner's
reauthorization, the native sender's roles and route, local provenance, the API
turn. Then claim_session_input claims whichever queued row is first when its
write transaction runs. The re-reads after the awaited checks (8d6d486f4a, X4)
assume a cancellation can only commit at those awaits, but cancel_queued writes
from a worker thread (9dadd0be5b) without the session mutation lock, so it can
commit after the head's last re-read. Since f2a717d8c6 the claim itself runs in
a worker thread through tracked_write, which widens the window to the whole
wait for the state.db writer. The claim then takes the successor, which never
passed its own check, and _drain runs it: a hosted task whose source binding
was revoked, or a native message whose sender lost its role, runs once. The
_guard passed since f2a717d8c6 is the owner admission gate and does not compare
the head.
claim_session_input takes the admission id the caller validated (head=; None
when it saw nothing queued). Inside the claim transaction a different queued
head claims nothing and returns False, which _drain already treats as
"re-read", so the row that is now first is validated on its own before it can
run. _guard is unchanged. _stamp_claim (the claim's then=) stamps only a real
row, not False. Callers that pass no head keep the old behaviour.
Red on 837f50b3da:
test_head_cancelled_after_its_last_preclaim_check_does_not_hand_the_claim_to_its_successor
(the X4 fixture: hosted:A authorized, hosted:B revoked; the claim write is held
in its worker thread until A's cancellation commits through cancel_queued)
executes hosted:B with only hosted:A validated. Green after: B is validated,
refused and stays queued; A is cancelled.
The mechanism was first reported by Xipong as X4 (https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5188234271); 8d6d486f4a re-checked the head only after the awaited checks.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6093848744
(cherry picked from commit ea1a93c8b4f76b4747bf446224448dcd52b84d8e)
7fef5d8b6c and 9dadd0be5b moved settlement and queued-cancel writes off the
owner event loop because a held state.db writer (_WRITE_PATIENCE_S = 20 s)
froze every session, timer, socket, Stop and approval. The three hottest
writes were still synchronous on the loop: admission (submit, admit_native,
cron submit, automation), the FIFO claim (_claim_next) and Discard
(resolve_unknown). Each takes SessionDB._lock and retries BEGIN IMMEDIATE with
time.sleep, so a 1.5 s foreign hold delayed a 50 ms loop callback by ~1.5 s.
session_runtime_workers.tracked_write runs the write in a worker thread with
its loop-side follow-up (publication, scheduling, the claim's execution stamp)
as ONE task tracked like track_mutation (retirement joins it) and shielded (a
cancelled caller cannot separate the commit from it). Invariants kept:
- gate: the admission gate is re-checked inside the write transaction
(_admission_gate as the admit guard, claim_session_input(_guard=...)), so a
drain or retirement that starts while the write waits still refuses it;
- epoch/generation checks are unchanged in the store;
- commit-before-ACK: the receipt, _gateway_accepted and publication follow the
commit in the same task;
- claim-to-execution-stamp continuity: the stamp and message.start are set in
the claim's task right after its commit (_stamp_claim), no loop turn between;
- admission order: admissions serialize on a per-authority lock (ordered=True),
so a later input cannot take an earlier FIFO position.
test_session_authority_cancel_settlement's hosted-preclaim case now queues
both rows before the drain starts: admission yields now, so the first
submit's drain could otherwise claim before B is admitted. Its assertions are
unchanged.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5475590057
Every managed turn starts with a compression.history read, and
apply_worker_receipt stored each receipt's full result_json. Nothing removed
worker_receipts for a live session (only retire_terminal_receipts, at delete),
so each turn left a full-transcript copy behind: 22x the transcript at 40
turns, ~1.1 GB at 1,000 (quadratic state.db growth) for every managed session
(safe-mode/bypass, Kanban, custom-provider opt-in).
In the transaction that makes an execution terminal (execution.finish, or
settlement/cancel closing it via _retire_admission_workers) its read receipts
(results carrying `messages` or a full `session` row) shrink to a
{"retired": true} marker. payload_digest stays, so a late duplicate with other
content still conflicts (admission_conflict); an exact late replay of a
retired read is refused stale_generation, as after retirement. Mutation
acknowledgements (counts, row annotations, worker_assignment) and the
execution.finish receipt stay replayable.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5475590057
When every bounded settlement attempt fails (3cda1ec / 524316b retries a transient error
twice first), the drain fences the claim `unknown`, keeps the exact structured result in
authority.pending_results and pauses the FIFO. prompt.resolve_unknown then committed the
row terminal/interrupted and dropped that result: the model's finished answer was thrown
away although only its receipt write had failed, and the PR's own test asserted the loss.
resolve_unknown now prepares the captured result (prepare_result: same compaction and
redaction as normal settlement) and resolve_unknown_session_input commits it in the same
transaction as the terminal transition, with the result's own outcome (completed / failed /
interrupted). Only a row stamped unknown by this same owner epoch takes a captured result;
an unknown inherited from a previous owner (restart) still resolves interrupted exactly as
before, since no answer exists. Viewers receive the committed message.complete. An exact
retry of a resolution that committed a result returns the same receipt.
tests/gateway/test_live_settlement_recovery.py: the existing discard assertion is replaced
by the new contract (terminal/completed, stored final_response, one completion frame). This
is strictly better: the operator action still unblocks the FIFO exactly as before and the
lost-row boundary still commits atomically; the only change is that a produced answer is
kept instead of discarded. Red on the previous head (both parametrizations):
('terminal', 'interrupted') != ('terminal', 'completed'); green after.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6073624820
(cherry picked from commit bc1a469e0f9f42e2b8ee99c30627de47fbd012d9)
`status!='terminal'` cannot bound the session_admissions_pending (target, status, seq) or
idx_worker_executions_session_status (session, status) index, so every pending listing, idle
check (require_idle, require_not_executing, end_idle_local_session) and prune live-ledger probe
walked a session's whole finished ledger. That ledger only grows, and these probes run inside
the writer transaction on every turn / delete / idle end. Measured at 200k terminal rows: 6.35
ms per probe before, ~0 after. The predicates are now an explicit IN over the live
statuses of each table's CHECK domain ('queued','started','unknown' /
'registered','running','unknown'), same rows and an index range seek. The regression counts
SQLite VM steps against 40k finished rows: about 120k steps on r6-base, under 20k here.
Same predicate in gateway/session_worker_reservation.py and gateway/platforms/webhook_ingress.py
is in other lanes' files (NOT_COVERED.md).
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5462648005 (section 3: pending/claim checks)
The owner's _insert_message_rows mints message_uid (and per-call
_tool_call_uids/_tool_call_uid) and stamps them on the caller's dict; the
direct path therefore keeps one logical identity for a message through every
later in-place compaction / rotation copy. Worker receipts returned only
_row_id/timestamp/snapshot/canonical-row annotations, and archive/publish
returned bare row_ids, so the worker's live dicts never learned their uid:
each later archive or rotation re-sent the dict uid-less and the owner minted
a fresh identity per generation (context engines keyed on message_uid saw a
new message each compaction).
row_annotations now carries MESSAGE_UID, TOOL_CALL_UIDS and TOOL_CALL_UID,
and compression.archive / compression.publish return the same annotations as
transcript.append (applied with apply_row_annotations, which already handles
_row_id). No new input field is accepted owner-side: these keys were already
in the closed message field set.
Probe (real SessionDB + worker receipt txn, r6-base): DIRECT append/archive
live uid == stored uid [True,True,True]; WORKER [False,False,False]. After:
WORKER [True,True,True], marker uid stable across re-archive.
Test test_owner_minted_message_uid_round_trips_through_append_and_archive:
red on r6-base `assert [None, None] == ['edd9da2f...', ...]`, green after.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6067585232
Micro-compaction (_sync_micro_compact_to_db) and proactive prune
(prune_tool_results_only) hand their LIVE message list to
archive_and_compact. Those dicts carry worker-local bookkeeping the
SessionDB insert never reads: the post-commit `_db_persisted` stamp,
`_micro_compact_marker` on the rolling summary, a tool row's wire `name`
and `_tool_output_risk`. The managed facade forwarded them verbatim to
compression.archive / compression.publish, the owner's closed validation
(_handoff_messages) refused the receipt with invalid_params, and because the
journal entry stays pending + failure is sticky, every later persist of the
session (appends, usage, finish) raised. Direct SessionDB accepted the same
call.
The boundary stays closed: the worker facade now projects each handoff
dict onto HANDOFF_MESSAGE_FIELDS (the owner's exact accepted set, now one
named constant shared by both sides) before the RPC, and keeps stamping
results onto the caller's live dicts. No new fields are accepted owner-side.
Probe (real SessionDB + worker receipt txn, real
MicroCompactionMixin._sync_micro_compact_to_db, r6-base):
DIRECT durable ['u1','[CONTEXT SUMMARY] micro','u2'], later append ok
WORKER failure=invalid_params, later append FAILS invalid_params
Test test_micro_compaction_live_dicts_persist_through_the_worker_like_direct:
red on r6-base `KeyError: '_db_persisted'` (archive never committed so the
post-commit stamp never ran), green after with durable worker == direct.
Also applies ruff.strict UP006 autofix (List/Dict -> list/dict) to the two
signature lines in hermes_state_worker_compression.py: pre-existing on
r6-base, but the lefthook strict lint checks whole staged files.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6067585232
apply_worker_receipt bumped sessions.runtime_revision unconditionally for
every worker.persist op, including read-only handlers (session.context,
session.lifecycle, compression.history/lineage/context/watermark,
lock.holder ...). runtime_revision is the CAS fence mutate_runtime_session
checks (expected_revision != revision -> revision_conflict), and viewers
learn it from session.info. So a client rename/archive/sidebar edit built on
the revision it last saw was refused because a managed worker merely READ
its own context, while the same reads on the direct path leave it flat.
The receipt transaction now samples conn.total_changes around the handler
and bumps the fence only when the handler changed durable rows, plus always
for execution.finish (closing the execution is a state change the fence
must reflect). Every mutating handler (append, prompt/tools/sidecars,
title, activity, usage, compression archive/publish/locks, turn leases,
delegation ledger) still writes rows and still bumps. Receipt bookkeeping
(worker_receipts / worker_executions) is not session state and is excluded
because it is written after the sample.
Probe (real SessionDB, r6-base): get_session 2->3, lifecycle 3->4,
history 4->5, then mutate_runtime_session(expected_revision=pre-read) ->
revision_conflict.
Test tests/hermes_state/test_runtime_worker_read_fence.py:
red on r6-base `assert 5 == 1` (four reads bumped), green after; it also
pins that a real write and execution.finish still advance the fence.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5460639040
Review W4 (andrexibiza) says the worker outbox cannot rebind after an owner epoch
advance or a parent->child rotation, that RuntimeSessionStore.adopt() has no
production caller, and that the admission stays `started`. I checked each part
on r6-base with real SQLite, a real child process and the real owner
worker_request (claim/verify/adopt) seam.
What is reachable in production:
- The only production RuntimeSessionStore is the admission-reserved managed
worker (agent/managed_worker.py::execute). It is per-turn and reports over its
owner's stdin/stdout pipes, so it dies with its owner (pipe EOF -> stop, and
the result/finish handshake can never reach a new owner). No worker outlives
an owner restart doing useful work, so a post-restart rebind-and-replay has
nobody to serve. RuntimeSessionStore.adopt() is the standalone worker.register
protocol's rebind step (persistence_worker / rotation_persistence_worker /
delegation-receipt fixtures). That path works end to end: adopting on the
current physical child after a lost compression.publish ACK and replaying the
journal once rebinds scope to the child (probe_w4_standalone.py). It is not
dead, it is the protocol's API, so it stays.
- The "outbox_scope_mismatch on reopen" premise cannot happen: the outbox dir is
keyed by the unique per-admission execution_id and only the same process
constructs it.
The real defect is narrower. Suppose the owner reserves and bootstraps a child,
then dies before the child's first `worker.adopt` lands. WorkerRPC rediscovers
the endpoint on every call, so that handshake reaches the RESTARTED owner, and
adopt_worker_execution flips the recovered `unknown` admission back to `started`
(owner_epoch = new). The child then sees owner_epoch != its bootstrap epoch,
raises stale_epoch and exits. The admission stays `started` under an owner with
no pipe to it: the FIFO is blocked, prompt.resolve_unknown refuses `started`
(stale_generation), and only a further owner restart recovers it.
Fix: adopt_worker_execution refuses an `admission-worker:` row whose
owner_epoch is not the adopting epoch (stale_epoch). The same-epoch bootstrap
handshake and every standalone worker.register adoption are unchanged.
Red on r6-base (hermes_state_runtime.py swapped to r6-base):
test_late_bootstrap_handshake_cannot_rearm_a_recovered_admission
E Failed: DID NOT RAISE RuntimeStoreError
(probe: after_late_adopt admission=('started', 2), resolve_unknown=refused:stale_generation)
Green: 2 passed. Probe: late_adopt refused stale_epoch, admission stays
('unknown', 1), resolve_unknown ok, follower claimable after Discard.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5460639040
Storage modules imported gateway/ to compute their own identities:
hermes_state_runtime -> gateway.session_admission (module level, so importing
any canonical-store module loaded the gateway package), and function-level
hermes_state_worker_compression -> gateway.session_admission,
hermes_state_local_lineage / hermes_state_mutation_branch ->
gateway.session_local_recovery.local_identity (a module that itself imports
gateway.session/config), hermes_state_mutation_branch ->
SessionStore._profile_from_session_key, hermes_state_profile_repair ->
gateway.session.profile_from_session_key_namespace. The gateway imports the
store, so each edge is a latent import cycle.
New stdlib-only hermes_state_keys holds the pure helpers (admission_fingerprint,
local_identity, profile_from_session_key_namespace, profile_from_session_key).
The gateway modules re-export the same objects under their historical names
(SessionStore._profile_from_session_key delegates), so every gateway caller and
test is unchanged. The branch mutation still late-imports the gateway routing
types it publishes (SessionEntry/SessionSource/build_session_key), now with
the reason stated.
Red/green: test_storage_import_boundary asserts importing the runtime storage
modules loads no gateway module; on the parent it reports
['gateway', 'gateway.session_admission'].
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5456384314
The worker receipt block (sequence/size validation, digest, epoch fence,
assignment, owner-epoch check, exact-retry replay, live-status and next-sequence
fences, handler, receipt insert, last_sequence/status, revision bump) existed in
mutate_worker_execution and again in gateway/session_worker_delegation.py
persist_worker_delegation. (The second copy kshitij counted in
hermes_state_runtime.py was persist_worker_message, removed earlier in this series.)
hermes_state_runtime.apply_worker_receipt(..., handlers) is now that single
transaction; mutate_worker_execution and persist_worker_delegation only pick
their closed handler map.
Behaviour-preserving for delegation: it now resolves the assignment through
worker_receipt_assignment, which differs from _worker_assignment only for an
exact retry of a receipt carrying 'worker_assignment' (compression.publish);
delegation receipts never carry it and the digest includes the operation.
Its status write is 'running' either way ('execution.finish' is not a
delegation operation).
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5456384314
persist_worker_message and finish_worker_execution in hermes_state_runtime
have no production caller (git grep: only tests and the historical
evals/shared_gateway/worker-persistence-inventory.md note). Managed workers
persist through worker.persist -> mutate_worker_execution ('transcript.append'
/ 'execution.finish'), which goes through SessionDB._append_messages_in_transaction
and _insert_message_rows. The text primitive wrote `messages` with raw SQL,
bypassing that path, so its rows never got a durable message id.
Delete both and their raw-SQL append. The receipt/fence/epoch/adoption tests
now exercise the production mutate_worker_execution operations instead.
Two tests pinned only finish_worker_execution's own linked-admission settle
and media release (behaviour the production execution.finish path does not
have; the owner settles the admission via finish_result), so they go with it.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#pullrequestreview-5456384314
Persist cleanup candidates before erasing admission references. Release rejected or completed native input while keeping API image bytes referenced by retained branch history; collect them when their last owner is deleted.
Reported-by: itsflownium (https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6050777316)
Validation: tests/gateway/test_api_retired_media.py, tests/gateway/test_retired_media_ownership.py, tests/gateway/test_producer_owner_continuity.py, tests/hermes_state/test_ledger_delete_consistency.py, tests/gateway/test_api_media_retention.py
Implementation and additional regression probes were AI-assisted with GPT-6 Astra.
(cherry picked from commit 781ce26089947e5dde42f87b6ebef668090527f5)
Shield mutations from request cancellation and hold admission/claim gates until commit and live publication finish. Recheck queued submits after deletion, fence replayed projections by generation, and join mutations before profile retirement.
Depends-on: "fix(worker): retain persistence and ownership through physical shutdown" (physical worker and drain ownership)
Additional cancellation, retirement, and submit/delete regressions identified during GPT-6 Astra review.
Validation: tests/gateway/test_local_authority_transitions.py, tests/gateway/test_adversarial_mutation_lifecycle.py, tests/gateway/test_submit_after_delete_gate.py, tests/gateway/test_rewind_receipt_projection.py
Implementation and additional regression probes were AI-assisted with GPT-6 Astra.
(cherry picked from commit 564ffcb9819bb63ee34e5720b0debd1b2fbd7d6e)
An exact lost-ack Discard retry returns its committed receipt without closing or disturbing a successor turn. Failed transcript closure retains the unknown fence.
Validation: tests/gateway/test_authority_unknown_resolution.py, tests/gateway/test_unknown_receipt_boundaries.py
Implementation and additional regression probes were AI-assisted with GPT-6 Astra.
(cherry picked from commit 52c7683219915805764ad09a50583db54e3ffcf4)
A worker on a physical transcript fences its logical FIFO and second registrations. Explicit reset revokes only unlinked unknown workers, preserving live and admission-linked fences.
Reported-by: itsflownium (https://github.com/NousResearch/hermes-agent/pull/106742#issuecomment-6050777316)
Validation: tests/hermes_state/test_worker_lineage_exclusion.py, tests/gateway/test_unknown_resolution_physical_worker.py
Implementation and additional regression probes were AI-assisted with GPT-6 Astra.
(cherry picked from commit b31ed5232056100c55568d67a0c8ab6426886d4f)
Worker executions follow their physical transcript: a compression publish
moves the worker row to the child (`hermes_state_worker_compression.py`
worker_publish) and a managed reservation registers on the local physical
target. The FIFO stays keyed on the logical owner, and `claim_session_input`
looked for live/unknown workers only on that logical id. Once a worker had
rotated, the root's next queued input was claimed while the worker was still
writing the child transcript: two writers in one lineage (reproduced: claim
`started` while the child-resident worker kept persisting).
The claim now checks every session in the lineage: the forward compression
chain from the logical owner and from its local physical target (which
covers reset continuations). The same "unknown blocks, live returns None"
contract applies. The FIFO wakes when that worker's `execution.finish`
lands (previous commit).
Review: https://github.com/NousResearch/hermes-agent/pull/106742 (@itsflownium, core ledger: worker scans key on the logical id)
Discard (prompt.resolve_unknown) marked the lost admission terminal in one
transaction and appended the failed-turn boundary in a second. A failure in
between left the old user message open while the follower was already
claimable: the exact Discard retry answered stale_generation, and the
follower's provider request merged LOST_OPERATION and FOLLOWER into one user
message.
resolve_unknown_session_input now takes the owner's private same-transaction
callback (the #111216 terminal-write placement), and close_discarded_turn
writes the boundary on that connection, resolving the current physical
transcript (local reset lineage, then the compression tip) inside it. A
boundary failure rolls the resolution back, so the admission stays unknown,
the FIFO stays paused, and the exact retry completes the operation.
Review: https://github.com/NousResearch/hermes-agent/pull/106742#discussion_r4211143982
12 conflicted files, resolved in three lanes:
- gateway/run.py: take the branch split; main's tirith removal and spool-replay
ordering ported into run_runtime_init.py / run_bootstrap.py.
- config migrations: main keeps v50 (tirith); the branch's bot-chat timeout removal
becomes v51 (_config_version 51, template + test updated).
- hermes_state_usage.py: main's voice_chat task route threaded through the branch's
owner transaction; worker.persist usage allowlist accepts task.
- tui_gateway/server.py: branch side; main's edits applied where the code now lives
(agent_factory, session_registry). Desktop sessions get the catalog toolset on the
authority path; daemon-run finite CLI turns are not watched turns; lazy session info
reports nous/welcome on the free tier.
- Desktop/Ink: one branch-child spinner fix (main's route-token check); main's
uninstall i18n keys kept, pool keys stay removed; voice_turn forwarded and accepted
by the authority submit (surface_v1.voice_turn).
- chat_ws / PTY keepalive test: main's stricter test kept.