Commit Graph

18 Commits

Author SHA1 Message Date
kshitijk4poor
f4bdc3dd28 docs(state): state the route-writer prompt invariant in one line
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.
2026-09-27 00:35:39 +05:30
Uttkarsh
ae6e4428cb fix(state): stop nulling the stored system prompt on route commits
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)
2026-09-27 00:35:39 +05:30
teknium1
1a08c487be fix: scope one-shot aux usage to the branch and keep it on failed turns
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.
2026-09-16 17:03:25 -07:00
teknium1
8899aeff53 fix(oneshot): --usage-file ledger reports auxiliary LLM spend
`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>
2026-09-16 17:03:25 -07:00
teknium1
cfd752e6f7 fix(sessions): token-accounting guard stamps the agent's real source; trim salvage
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
2026-09-15 18:23:07 -07:00
finn763
a7dde8a57d fix(sessions): keep a stream-interrupt recovery inside the original session
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
2026-09-15 18:23:07 -07:00
Teknium
e83816a4d1 review-fix(comments): restore lost #NNNN rationale comments across non-test source (mechanical sweep, condensed, code unchanged)
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.
2026-09-03 09:44:26 -07:00
Teknium
cb6cc64700 refactor(state): search/schema/registry/portability/telegram/usage/titles — inline single-use helpers, contextlib.suppress ladders, pack wrappers around unchanged SQL literals 2026-09-02 21:57:21 -07:00
Teknium
c1620901ae refactor(hermes_state): AST-neutral packing of state mixins (120 cols) 2026-09-02 19:10:31 -07:00
Teknium
9c5271fa88 refactor(hermes_state_usage): derive absolute/delta token UPDATE from one template (byte-identical) 2026-09-02 18:58:03 -07:00
Teknium
ab5a64a7a4 refactor(hermes_state_usage): compact docstrings/comments 2026-09-02 18:24:01 -07:00
Teknium
831f2e542c refactor(state): fold small get_messages/reaction/publish shapes; hug trailing closers (AST-identical) 2026-09-02 17:20:16 -07:00
Teknium
1991695511 refactor(state): _cooldown_row shape helper; per-model usage kwargs via field set; small folds 2026-09-02 17:17:16 -07:00
Teknium
388fe39f55 refactor(state): compact messages docstrings (WHY kept); append_message builds msg from its own kwargs 2026-09-02 17:06:57 -07:00
Teknium
8656cc31f2 refactor(state): table-driven _rows_to_conversation column copy; unify tool-call counting; collapse defensive locals 2026-09-02 16:59:58 -07:00
Teknium
0d7acf67b5 refactor(state): pack hanging signatures/tuples in messages/compression/usage (AST-identical) 2026-09-02 16:38:21 -07:00
Teknium
5c3acca66b refactor(state): resume — verified messages/compression/titles/usage simplification 2026-09-02 16:37:21 -07:00
Teknium
d15c61b5dc refactor(state): split SessionDB into domain mixins and free-function modules; unify SQL boilerplate
hermes_state.py 17,220 -> 6,442 LOC. Behavior-neutral: every moved body is
AST-identical to the original, verified per extraction.

SessionDB core
- _write_sql / _write_rowcount / _read_one / _read_all replace ~120 copies of
  the `def _do(conn): conn.execute(...)` + `_execute_write(_do)` and
  `with self._read_ctx() as conn: row = conn.execute(...).fetchone()` shapes.
- _set_lineage_column replaces four copies of the recursive compression-lineage
  UPDATE (archived / pinned / hidden / last_read_at).
- _read_session_number unifies the three compression counter readers.
- Dead (zero refs repo-wide): restore_rewound, delete_gateway_routing_entries,
  _is_duplicate_replayed_user_message, SessionPortabilityMixin.get_first_assistant_text.

New mixins bound onto SessionDB via the MRO (logger name stays "hermes_state"):
  hermes_state_messages    SessionMessagesMixin       48 methods
  hermes_state_compression SessionCompressionMixin    30
  hermes_state_gateway     SessionGatewayMixin        26
  hermes_state_maintenance SessionMaintenanceMixin    13
  hermes_state_usage       SessionUsageMixin          12
  hermes_state_titles      SessionTitlesMixin         13
  hermes_state_telegram    SessionTelegramTopicsMixin 11
Origin-internal symbols resolve through a lazy `from hermes_state import ...`
inside the few methods that need them (no import cycle).

New free-function modules, every name re-imported into hermes_state so
`hermes_state.<name>` (and test monkeypatches on it) keep working; intra-module
calls to patched helpers go through the lazy origin import:
  hermes_state_repair   repair/backup/preflight (43 defs)
  hermes_state_wal      journal-mode / PRAGMA policy (33 defs)
  hermes_state_dbfile   header probes, zeroed-db quarantine, stats, holders (21 defs)

Existing mixins: search — shared FTS MATCH/LIKE builders, unified rebuild
status/step/finish engines, state_meta helpers; schema — one legacy/v23 FTS init
branch, shared _live_pk_columns, Row/tuple dual access dropped; portability —
shared _PREVIEW_RAW_SUBQUERY_SQL and _rich_row; common — single
stat_db_file_identity (was 3 copies), AUTO_VACUUM_MIN_FREELIST_RATIO.

Docstrings/comments hand-compacted (AST-identical) keeping every invariant,
ordering rule, failure mode and WHY. Schema SQL, migration order and PRAGMAs
untouched. test_repair_path_has_no_bare_connects repointed to hermes_state_repair.
2026-09-02 13:32:13 -07:00