SessionDB.get_session / list_sessions_rich / get_recent_session_model_route /
list_gateway_sessions drained the async token queue first and waited up to
5 s for the background writer. Gateway handlers make these reads on the event
loop, and the writer can sit behind another connection's write lock, so one
read froze every socket on the gateway (#141966). Measured on a real
multiplex gateway under load: 36 stall samples (~0.7 s) in one 90 s run were
get_session waiting in flush_token_counts.
Reads now use flush_for_read(): on a thread running an asyncio loop it drains
nothing it would have to wait for and reads the committed totals (stale by
the queued deltas, which the next read sees). Off the loop it still waits,
and write barriers (model switch, meta update) keep calling
flush_token_counts and still wait.
record_auxiliary_usage resolved _own_profile_name() up front, so the
missing-row path paid for it even though only the existing-row backfill
uses it (insert_session_row_in_transaction stamps the profile itself).
Resolve it in that branch.
The comment also credited "the upsert's profile_name backfill"; for an
existing row the fill is the explicit UPDATE in _write. Say so.
record_auxiliary_usage read row existence outside the write, then the
placeholder insert re-checked it inside a second transaction, and the
usage landed in a third. Do the check, the placeholder insert (or the
NULL profile_name backfill for an existing row) and the usage write in
one transaction. A missing row is still created as 'unknown' through
insert_session_row_in_transaction, and an existing row still keeps
source and created_source.
Two things do change. The usage write now runs with the transcript write
patience (_TRANSCRIPT_WRITE_PATIENCE_S, 60 s) instead of the default
20 s, because it shares the transaction that the placeholder insert
already ran with that patience. _own_profile_name() is also resolved on
the missing-row path, where nothing uses it.
Three comments said an auxiliary-usage 'unknown' created_source "never
moves". Since the creator upsert's NULLIF(created_source, 'unknown') in
this series that is false; only commit_local_session's ON CONFLICT DO
NOTHING insert leaves it, which is why that insert stamps the surface.
Say that instead.
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.
Main made the strict ruff config the default (`ruff check .`, blocking), and
the branch's code carried 278 findings under it (main itself is clean). Fixed:
- PLW1510 (86): `check=False` on each subprocess.run, preserving behaviour,
as main's own sweep (0006a5e229) did.
- ASYNC220 (9, test fixtures only): `noqa` with the reason, main's convention
for a Popen that returns at once and whose handle the test drives.
- ruff's safe autofixes plus the narrow unsafe ones (UP006/UP037/RUF100/RUF013/
PLR0402/RUF059 underscore renames/UP031/UP041/UP017/FURB167/PIE807/RUF007/
RUF015/RUF022/FURB162), and by hand: four %-formats to f-strings, three
unused unpacked names, one fixture loop over `.items()`.
No behaviour change. `ruff check .` passes; scripts/check passes; the 412 test
files mirroring every edited file pass (3 tests/pm files that fail only under
that batch's uv lookup pass solo, before and after this commit).
8 conflicts, all from main's lint sweep (#135281 "Harder linter fixes" + the RUF series:
implicit-Optional, unused-unpacked-variable, next(...) for [...][0]). No other main commit touches
a conflicted file. Resolution: the branch side of each file plus main's exact autofix
(ruff 0.15.10, main's ruff.strict.toml, --fix --unsafe-fixes) on it. ruff.strict.toml takes main's
copy (the newly enabled rules). tests/cron/test_bot_chat_delivery_child_env.py stays deleted
(1cc9cb9199 retired its lane).
45 conflicts, all from #135177 (lefthook + `ruff check --fix` over 2,366 files). No other main commit
touches a conflicted file. Resolution: the branch side of each file, then main's exact autofix
(ruff 0.15.10, `--config ./ruff.strict.toml --fix`) on it — rewrites only (typing generics, noqa
drops, import forms), no import removed. tests/cron/test_bot_chat_cli_home.py stays deleted
(1cc9cb9199 retired its lane).
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.
Voice replies had to come from the session's main model, so a heavy model made every spoken
answer slow (#83894). A new auxiliary slot, voice_chat, picks the model for voice turns:
- CLI/TUI voice mode, the Desktop voice conversation (prompt.submit voice_turn) and messaging
voice notes mark the turn; agent/voice_turn_route.py binds the route after the prompt, row and
preflight compaction were settled against the main model and undoes it before memory sync and
background review, so the next typed turn and the review run on the main model.
- A turn larger than the voice model's compression threshold stays on the main model with a
one-time notice: switching to voice never compacts the conversation.
- Usage lands in session_model_usage under task voice_chat; it never rewrites the session's
recorded model/route, so resume keeps the model the user picked.
- Slot appears in Desktop Settings -> Models, the dashboard, and `hermes model`; GPT-Live
delegations keep using the session model.
Merge #8: 2,771 commits from main (4b05f764fa). Ports main's moved code into the
unified runtime (run.py/run_turn.py splits, tui_gateway server, backup/restore
split), keeps the detached-daemon Desktop lifecycle, and adapts main's new tests
to the owner/authority contracts (canonical session deletes, retired-id
tombstones, zero-writer browsing, hermes_yaml, platforms() markers).
The writer docstrings narrated why the NULL was removed; one line stating
the invariant (route writers never touch the stored prompt, the runtime
identity check decides staleness) is what a reader needs.
update_session_model (every /model commit), update_session_runtime_lock
and update_session_billing_route nulled the session's stored system
prompt snapshot unconditionally. The snapshot is a long-lived session's
provider cache prefix; nulling it makes the next turn take the broken-row
rebuild in _restore_or_build_system_prompt (the 'Stored system prompt
... is null' WARNING) and re-bills the whole prefix at ~0% cache.
The nulling predates _stored_prompt_matches_runtime, which now rebuilds
and re-persists exactly when the embedded Model:/Provider: footer is
stale and reuses the stored bytes otherwise. The DB-side nulling is
redundant for real switches and harmful for no-op route re-commits
(picker re-selects), runtime locks and billing-route writes.
Fixes#121840
(cherry picked from commit 07462e23c3b593d80546172a72f8385697c60c4c)
Review follow-up for #113119.
auxiliary_usage_by_task walked parent_session_id past an explicit /branch
copy, so a resumed branch one-shot's per-run delta absorbed aux spend that
another process billed to the source session in the meantime. The walk now
stops at the nearest explicit-branch node (inclusive), mirroring the cutoff
hermes_state_messages applies for resume; compression children of the branch
still count because they never carry _branched_from.
_attach_auxiliary_usage read the tip id from the result dict, which a failed
turn (billing/entitlement failure return) does not carry, so the ledger's
auxiliary block came back empty exactly when the docs promise it is written.
The caller now passes agent.session_id (or the start id) as a fallback.
`hermes -z --usage-file` copied only the main-loop result, so title generation,
vision, compression, web_extract and background-review calls — recorded per task
in session_model_usage — never reached the pipeline ledger the flag advertises
as "so pipelines can always account for spend". The Insights page already folds
those rows in (#23270); the ledger is now consistent with it.
- SessionDB.auxiliary_usage_by_task(session_id): per-task sums over the
session's compression lineage (aux calls bill to the id the turn started with
while compression mints child ids mid-turn).
- oneshot snapshots aux usage before the turn and attaches the delta after it,
so a resumed session's earlier runs are not re-billed.
- The report gains `auxiliary` (totals + `by_task`) and
`total_including_auxiliary`; every existing key keeps its main-loop meaning.
- The auto-title upgrade runs on a daemon thread and can still be writing when
the turn returns: title_generator tracks in-flight upgrade threads and
oneshot joins them (bounded) before reading — no sleep, no eager read.
Fixes#112848. Direction shared with #112852 (@KoNit-K), which folded aux into
the headline counters; this keeps them backward compatible instead.
Co-authored-by: KoNit-K <124019182+KoNit-K@users.noreply.github.com>
When every row create of a turn loses to the SQLite lock, the queued token delta's
"ensure the row exists" guard becomes the session's first writer and minted the row as
source='unknown'. That placeholder was permanent on the real path even with the upsert
repair from #112045: the turn lease (turn_facade_lease.admit_durable_turn) treats an existing
row as proof the create already happened and sets _session_db_created, so the creator never
returns to repair it. Live probe: a platform="desktop" AIAgent whose create_session raised
"database is locked" for the whole first turn ended with a source='unknown' row on base AND
on the contributor head; with this change the row is minted 'desktop' by the guard itself.
Producer fix: update_token_counts gains an optional source= that the two agent call sites
(agent/turn_usage.py, agent/codex_runtime.py) fill from _session_source_for_agent(platform),
the same value _ensure_db_session would stamp. record_auxiliary_usage has no surface and
keeps the placeholder, which the creator's upsert now repairs.
Salvage trims: the contributor's SimpleNamespace dispatch test is replaced by a real-AIAgent
invariant test under tests/agent/ (the dispatch hunk in _run_prompt_submit is kept; the
INSERT-OR-IGNORE is idempotent under prompt.submit's own persist); narration comments cut
to the WHY; docs list 'unknown' among the startup-sweep sources.
Refs #111999
A stream that dies mid-answer could leave an orphan session behind: source='unknown', its
first message an assistant message and no user prompt anywhere — invisible to the startup
orphan sweep, unrepairable by the session's own creator. Three links made it permanent:
* the token-accounting guard (hermes_state_usage.update_token_counts, the only writer that
mints source='unknown') mints whenever the row is missing — which is exactly the state a
recovery dispatch resumed from: _run_prompt_submit (the crash auto-continue, the
queued-prompt drain) went straight into the turn without persisting the session's own row,
unlike the prompt.submit handler, so the first durable writer for that session was the
accounting side effect, and the turn's prompt could not be written at all (the messages FK
needs the row);
* _insert_session_row's upsert deliberately keeps what the first writer set, so the real
creator could never repair that placeholder;
* _ORPHAN_SWEEP_SOURCES skipped 'unknown', so such a row stayed ended_at IS NULL forever.
Every dispatch now binds its own row (original session_key, real source) before the turn
writes anything; the upsert repairs the placeholder source when the session's real creator
arrives; the sweep collects a phantom an older build already left on disk. Regression tests
(red before, green after) in tests/tui_gateway/test_stream_interrupt_recovery_orphan.py.
Refs #111999
For each issue anchor present in BASE 63279301bc non-test .py and absent on HEAD, the BASE comment/docstring block was re-attached at the HEAD location of the code it explained (matched by the distinctive code line / enclosing def). Sentences already covered by an existing HEAD comment were deduped; the issue number always survives. Insert-only: no code lines changed.