Commit Graph

30 Commits

Author SHA1 Message Date
Teknium
4186899a6f fix(sessions): skip a re-handed uid only when the agent saw it durable
The salvaged #134799 guard skipped any no-snapshot, no-row-id dict whose
message_uid was ACTIVE, so SessionDB.append_messages_batch dropped a fresh
message carrying a copied uid — the exact case main's contract
test_fresh_identical_message_is_never_adopted_by_payload pins ("even a copied
message_uid is not proof").

Narrow the trigger to provenance: the agent flush records the uids it itself
saw durable in its current session (rows it flushed, history it scanned as
already persisted) and marks a later marker-stripped copy of one of them
RESTORED_FROM_STORE on its batch row. The write transaction skips only those
marked rows whose uid is still ACTIVE. A direct append with a bare copied uid
inserts as on main.
2026-10-27 11:49:40 -07:00
Teknium
58cf3ee9ac refactor(agent): derive provider-named core sets from registered profiles
- auxiliary_client: the catalog-unavailable fallback of _builtin_provider_present
  no longer lists copilot/copilot-acp; a registered profile (canonical name) whose
  credentials the anonymous custom downgrade cannot carry (ambient_credentials or
  auth_type external_process) keeps its identity. Comments reworded generically.
- agent_runtime_helpers: the ack detector's "on <provider>( via acpx)" transition
  cue matches any registered provider name or alias instead of a hard-coded one.
- message_metadata: UNPRICED_REPLAY_FIELDS becomes unpriced_replay_fields(), the
  core carriers plus every declared ProviderProfile.message_carrier_* key
  (resolved lazily); model_metadata resolves it once per message.

Same answers for every Copilot input with the in-tree plugin present.
2026-10-25 19:26:48 -07:00
Siddharth Balyan
0c07f21843 refactor(data-use): trim comments to the why 2026-10-21 15:46:19 +05:30
Siddharth Balyan
22fc809869 feat(data-use): route connector results that need no-training to qualifying Nous endpoints
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.
2026-10-21 15:46:19 +05:30
Teknium
58dd5b9dc7 fix(gateway): keep the compaction summary flag on replayed rows so a proactive prune re-persists it
The first replay sent the summary unstamped but dropped _compressed_summary; prune_tool_results_only
then persisted that unflagged view and the next replay stamped the summary, changing the cached prefix.
(review on #139862)
2026-10-16 14:35:30 -07:00
Teknium
899b7df621 fix(gateway): replay the compactor's restated in-flight task unstamped too
A compaction that restates the unfinished request as a standalone user row
sends it unstamped; the next gateway turn reloaded it and stamped it like a
message someone sent, so the request diverged from the cached prefix at that
row exactly as the summary row did. The compressor now marks that row with a
producer-owned display_metadata flag (persisted by SessionDB, popped from
every wire copy) and gateway replay skips the stamp for any compaction
scaffolding; the helpers live in agent/message_metadata.py beside the
persistence-only field set.
Human-pasted header text carries no flag and keeps its timestamp.

Ported (trimmed) from #130909's restatement-provenance commits; the merged
carrier layout already carries _compressed_summary so needs no flag.

Co-authored-by: Yuan Li <dskwelmcy@163.com>
Co-authored-by: Ofir Flaisher <6105216+ofirf@users.noreply.github.com>
2026-10-16 14:35:30 -07:00
Teknium
df3c21400d fix: /steer, /branch and compaction accounting keep reasoning intact
- A steer merged into a tool_result turn no longer ends the in-flight tool loop,
  so last-turn-only Claude models keep the loop's thinking.
- CLI /branch copies reasoning_content like the gateway and TUI branches do.
- The preflight estimate prices Gemini/Copilot signatures and the Converse
  sidecar at 0 like the compaction tail walk; a mismatch loops compaction.
2026-10-10 19:22:07 -07:00
Maciej Lisiewski
d76cce4f11 ci: apply all automatic linter fixes available 2026-10-08 17:22:54 +02:00
unsupportedpastels
da88c23c02 fix(compression): a row the repair drops is named, not a reason to fall back to the watermark
On a reload without row ids, a dict that stood for rows the alternation repair
dropped or folded made coverage_for_commit return (None, None). The watermark
path then archived every active row below it, including rows another surface
appended that the compressor never saw: they left the model's history without
being in the summary (the unseen-gap contract of 1674499d00).

The repair now records role, content and tool-call ids of each row it retires
without an id, and of an assistant survivor before a fold rewrites its text.
The commit matches each to exactly one active row at or below the watermark and
keeps exact coverage; a retired row widens the carried-tail rewind like a merged
row. An ambiguous or missing match, or a count the recorded rows do not cover,
still takes the watermark path.

The approach of stashing id-less dropped rows as unresolved held coverage comes
from #129162.

Co-authored-by: JerryLiu369 <953639086@qq.com>
(cherry picked from commit 312474b424ede18f01433860309d23526c08e6b3)
2026-10-03 18:17:35 +05:30
John Paul Soliva
bbacab4201 fix(compression): the repair's row counts are persistence-only message fields
`_merged_durable_rows` and `_unnamed_durable_rows` ride on live history dicts so an
in-place compaction can count the durable rows behind a repaired dict. The request
copy built in turn_context kept both keys. The four in-tree transports drop them
while converting, but membership in PERSISTENCE_ONLY_MESSAGE_FIELDS is the contract
a transport relies on, and the token estimator priced the two keys.

Reported by JoaoMarcos44 on #125567.

(cherry picked from commit 62e24924f0db520c09681bf9d4ff757e599497ad)
(cherry picked from commit 9b66d804f2bb5f3e174810b63e583415a4c57864)
2026-10-03 18:17:35 +05:30
Halldrix
ac0b07597d fix(tui_gateway): harden the off-turn session-key fixes from a parallel review (#123545)
Four independent reviewers swept the #123635 diff. These are the findings that
changed code; each was verified before applying, not taken on report.

Register the recorded key instead of relying on the underscore sweep. The
staged dict becomes the turn's live user message, so _submit_row_session_id
rides every replay of that row. turn_context.py pops PERSISTENCE_ONLY_MESSAGE_FIELDS
from every outgoing copy and its comment says only chat-completions strips
underscore keys — an unregistered key survives to the transport, so a strict
OpenAI-compatible backend could 400 on it. Verified by execution: the registry
pop leaves the key in place and the transport sweeper is what removes it. The
membership is the contract; the underscore is the accident.

Gate each write on the key it writes to. _write_submit_user_row checked
session_key and appended to _submit_row_target_key(session); the two can
disagree after a rotation, so the guard described a write that was not the one
performed. The dead `key` local is gone.

Drop the isinstance/Any guard on _submit_row_owner_key. All three callers
narrow to a dict and check _row_id immediately before; the annotation existed
only to permit the non-dict the guard then rejected.

Log a failed model-switch marker persist at warning, not debug. Filing the
pivot in the live session means the write can now hit CompressionSessionClosedError
on a closed parent, which the old session_key target could not. At debug a
model switch silently loses its durable notice and nothing reaches errors.log —
the sibling persist one screen up already logs at warning.

Test-file: replace the E731 lambda with a named helper, and move _rotated_session
above its first use.

Verified: 7/7 in the regression file, 2113/2113 across the tui_gateway siblings
plus tests/hermes_state, 79/79 in the message-metadata/turn-context suites.
2026-09-29 19:42:46 -05:00
kshitijk4poor
536a2611c9 refactor(sessions): record_absorbed_message dedupes with dict.fromkeys
No behaviour change.
2026-09-29 04:15:21 +05:30
kshitijk4poor
dd66c132f2 fix(sessions): keep tool-call uids paired through rewrites, folds of repeated ids and chunked copies
Found by the pre-merge correctness and hermes-specific review of this stack:
- A fold after a row whose one response repeated a provider id (one shared uid) appended the
  absorbed turn's uid in the wrong slot. The shared uid now fills each of the row's own
  occurrences before the fold appends (per_occurrence_tool_call_uids). A single response keeps one
  shared uid for a repeated id: every result carries it, so no call looks unanswered.
- A digest-less re-flush of a restored fold (replay heal, adopt after a digest mismatch) let the
  stored pre-fold map overwrite the longer live list, so the later occurrence's results paired
  with nothing. A live list that starts with every stored occurrence is kept (stored uid or list).
- A dict that lost its uid map (a clone) rewrote tool_call_uids to NULL. The row-addressed
  rewrite now fills stored uids for the calls the dict still names; a call it dropped keeps none.
- append_messages_batch(chunk_rows=...) reset the pairing index per chunk, so a result in the chunk
  after its call was stored without tool_call_uid (branch/seed copies). The whole batch is paired
  before it is chunked.
- _merge_assistant_into keeps its dict guard on the absorbed turn's map (a plugin-built dict with a
  non-dict map no longer raises).
2026-09-29 04:15:21 +05:30
kshitijk4poor
2be9fa5f9d refactor(sessions): simplify-code pass over the identity helpers
- without_persistence_fields() replaces the two hand-written strips (context-engine selection,
  token-estimate fingerprint).
- mint_uid() is the one uid minter; uid_list() the one uid-list normalizer (message_metadata's
  _absorbed_uids and the codec's _uid_list share it).
- _live_or_column() replaces four copies of 'live key first, column name second'; the absorbed
  list writer takes the dict, not a (live_key, column) pair its one caller always passed the same.
- _restore_row_identity() is the one stored-identity-onto-live-dict step, shared by restore and
  the row-addressed rewrite (transcript_repair had a hand copy). Restore skips the decoders for
  NULL columns (the common row).
- index_tool_call_uids() returns the variants it named, so the flush walk stops computing them
  twice; tool_call_uid_from_history drops guards its one caller can't trip.
- rewind returns the replacement dict (the insert already stamps _row_id and message_uid)
  instead of re-querying last_insert_rowid.
- _remember_absorbed_row's folded is required, so every call site states the witness rule.
- The backfill reads/deletes state_meta through _meta_row/_delete_meta; chat_completions strips
  MESSAGE_UID by constant.
No behaviour change.
2026-09-29 04:15:21 +05:30
kshitijk4poor
d9808867c7 fix(sessions): an assistant fold keeps every occurrence uid of a reused provider id
Folding two assistant turns that reuse a provider id (llama.cpp-style constant ids) leaves
both calls in tool_calls, but the {id: uid} union kept only the later uid, so the first
occurrence lost its identity. The id now maps to a list of uids, one per occurrence in
tool_calls order (merge_tool_call_uids); index_tool_call_uids pairs each call with its own
occurrence, so a following result still pairs with the nearest call. Provider ids are never
rewritten. Persisted and restored as-is (the JSON map accepts list values).

Reported by @andrexibiza on #126307.
2026-09-29 04:15:21 +05:30
kshitijk4poor
4de41452ff fix(sessions): branch copies that drop tool_calls don't carry tool-call uid maps
message_identity copies the tool-call uid fields only for a copy that also carries
tool_calls/tool_call_id (CLI /branch); the TUI branch and lazy seed copy neither, and a
uid map on a row without its calls pairs nothing. The lazy seed now stamps and builds its
rows in one pass under the history lock.
2026-09-29 04:15:21 +05:30
kshitijk4poor
30050851f7 perf(sessions): pair tool-call uids in O(K) on flush and only when needed on restore
- The flush walk memoizes each assistant's named ids and uid index across one collect,
  so K parallel results no longer recompute K assistants' variants (O(K^2) -> O(K)).
- Restore indexes assistant maps lazily: only a result without a stored uid (an older
  build's) needs the index; rows this build wrote never pay for it. Same order, same
  shadowing. One decoder (_restore_identity_columns) for both restore paths.
- The token-estimate memo key skips persistence-only fields the estimate never reads.
- Context-engine selection strip: isdisjoint instead of per-key scans.
2026-09-29 04:15:21 +05:30
kshitijk4poor
e220dc1b83 perf(sessions): walk back to the owning assistant without copying the message list
tool_call_uid_from_history ran reversed(messages[:i]) for every flushed tool result,
copying the whole live list each time. An index walk halves the per-batch cost
(34k-message session, 32 parallel results: 5.4 ms -> 2.7 ms).
2026-09-29 04:15:21 +05:30
kshitijk4poor
c9a1c0793a fix(sessions): branch and seed copies write the identity their live history keeps
The three branch/seed copy paths (TUI/Desktop _persist_branch, the lazy _persist_branch_seed,
CLI /branch) built each child row from a fresh dict, so the insert minted new uids and
per-occurrence tool-call uids while the child agent kept running on the copied live dicts
with the parent's. After a restart the child restored identities the running agent never saw.

message_identity(msg) mints a uid onto the live dict when it has none and returns the identity
fields (uid, merge witness, tool-call uids); every copy row carries them.
2026-09-29 04:15:21 +05:30
kshitijk4poor
95b2aea9e7 refactor(sessions): one uid reader/stamper and one identity-field copier in message_metadata
The salvage carried two copies of the uid reader (message_metadata._uid_or_none and
hermes_state_messages._message_uid_or_none), two tolerant uid-map parsers
(transcript_repair._json_map and hermes_state_messages._uid_map), and the same four
identity-field copy blocks in _db_flush_row and sync_flushed_message_markers.

message_metadata now owns message_uid_or_none, stamp_message_uid (moved off SessionDB so
non-store callers can mint before a write) and copy_identity_fields; transcript_repair
reuses _uid_map.
2026-09-29 04:15:21 +05:30
Eva
c2e2150d78 fix(sessions): close the identity gaps the review found and prove the recovery paths
- Strip persistence-only fields from a select_context() selection: the request copy was stripped before
  the hook, but an engine handing back the conversation_messages clones put timestamp, _row_id and the
  new ids on the wire (pre-existing for the old fields).
- Every row carries a message_uid whoever wrote it: an AFTER INSERT trigger mints one for a row inserted
  without it (an older build writing into a v31 store); the one-time backfill is gated by its own
  state_meta marker so a store whose schema version cannot advance (no FTS5) never rescans.
- One merge-witness helper (record_absorbed_message) for every fold of a durable message: alternation
  repair's user and assistant merges, the compressor's in-flight restatement onto the carrier, the real
  user anchor folded into a scaffolding turn (the anchor's uid leads), micro-compaction's adjacent-user
  merge.
- tool_call_uids follows tool_calls: it is a payload column, so an assistant merge's unioned map is
  rewritten with the row instead of being overwritten by the stale stored map on adoption.
- A result pairs with the nearest call naming its provider id: each assistant row's ids shadow earlier
  occurrences in the batch, restore and live-list indexes, a call row without a map leaves its result
  unpaired, and nothing pairs across a user turn.
- A composite rewind returns and installs the replacement row's uid on the live scaffold.
- Tests: import_foreign_history, hermes sessions recover and backup import carry the ids; the ACP
  restore test accounts for the uid on restored rows.

(cherry picked from commit b30636a49cb29fdd21ba4100eef9d810897338be)
2026-09-29 04:15:21 +05:30
Eva
76d0ac6caa feat(sessions): give tool calls and their results a per-occurrence uid
Provider tool-call ids repeat: Hermes mints deterministic call_<12hex> ids for identical calls and models
reuse ids, so tool_call_id cannot identify an occurrence. An assistant row now carries
messages.tool_call_uids, a {tool_call_id: uuid4} map for its tool_calls, and each tool-result row carries
the matching messages.tool_call_uid. The provider-facing tool_calls JSON is untouched, so row identity,
display identity and the CAS digest are unchanged and nothing nested reaches the wire.

Minted at the assistant row's first insert; paired onto the result in the same batch, from the live list
when the result is flushed later, or on restore from the preceding assistant row; copied by every clone
and re-insert; restored as the live _tool_call_uids / _tool_call_uid; stripped from provider requests.

(cherry picked from commit aa49c0f59788676d4beca288181711c558fca165)
2026-09-29 04:15:21 +05:30
Eva
751d8526e3 feat(sessions): give every persisted message a durable message_uid that reaches context engines
The physical messages.id is re-issued by every copy (in-place compaction generations and their
concurrent-tail clones, rotation children, replace_messages), and _row_id is opt-in on restore, so a
context engine that keeps its own per-message state had nothing stable to key on across a restart or a
compaction boundary and re-identified rows by content and timestamp.

Add messages.message_uid (uuid4 hex), minted once at a row's first insert and stamped on the caller's
dict, copied by every SQL clone, kept by every re-insert of the same dict, left alone by row-addressed
rewrites, restored on every projection, and stripped from provider requests. A consecutive-user merge
survivor keeps its own uid and records the absorbed uids in _absorbed_message_uids. Schema v31 backfills
a uid onto rows that predate the column.

(cherry picked from commit 20d67ffb5e50e0ed956e56ddc7f8e28d36059e2e)
2026-09-29 04:15:21 +05:30
kshitijk4poor
57b0ed0156 fix(agent): keep the merged-turn prefix out of the token estimate
The marker recorded by _merge_consecutive_users repeats the unanswered text
already in the row's content, and the rough token estimator priced it as
payload: a merged row with a large unanswered paste was estimated at ~2x its
real size for the rest of the session, pulling compaction forward.

Name the key once in agent/message_metadata.py and put it in
PERSISTENCE_ONLY_MESSAGE_FIELDS, so the estimator skips it and every outgoing
request copy (all transports, plus the iteration-summary call) drops it —
not only the chat-completions underscore sweep.
2026-09-29 03:30:52 +05:30
kshitijk4poor
1a95a75b1a fix(persistence): adopt content only on legacy rows and stamp every inserted row
A legacy (no-digest) dict over a non-blank assistant row adopted the whole
decoded DB row: tool_calls / reasoning* / codex_* were overwritten with the
stored JSON (which still holds the escaped lone surrogate the sanitizer just
fixed, re-injecting it into the provider payload) and live-only fields were
popped. Resumed dicts (_rows_to_conversation stamps _row_id without a
digest) and compaction clones hit this path. Adopt content only, as before
this stack, via a content-only canonical handled like the metadata-only one.

_insert_message_rows dropped a clone's parent digest but only the flush
path restamped it, so clones made by archive_and_compact / replace /
rotation handoff / import reached the legacy path and the first live edit
after a clone was not persisted. Stamp the stored-row digest inside
_insert_message_rows (one batched SELECT, cold paths only; the flush path
statement count is unchanged) and drop the duplicate call in
append_messages_batch.

Define the _db_row_snapshot / _canonical_row keys once in
agent/message_metadata.py and import them everywhere instead of repeating
the literals.
2026-09-27 20:45:44 +05:30
kshitijk4poor
1a43a4ef48 fix(persistence): strip the adopted canonical row from provider payloads
Gateway/TUI/CLI callers pass their live dicts straight to
append_messages_batch, so a concurrent-winner adoption leaves the
decoded durable row (_canonical_row) on a dict that may later be sent
to the model. Treat it as persistence-only like _row_id and the digest
so the outbound builder and token estimator both drop it.
2026-09-27 20:45:44 +05:30
kshitijk4poor
4854225903 fix(persistence): version transcript rows by digest, not a row copy
The CAS row snapshot was a full copy of each message's durable payload
riding on the live dict. The rough token estimator priced it (about 2x
estimates -> premature compaction) and it doubled transcript memory.

Replace it with a 16-byte blake2b digest of the repair columns. The
compare now runs in Python against the target row already read inside
the BEGIN IMMEDIATE transaction, followed by a plain UPDATE. Also:
- add _db_row_snapshot to PERSISTENCE_ONLY_MESSAGE_FIELDS so the
  estimator and the outbound request builder both drop it
- derive _REPAIR_COLUMNS/_SYNC_FIELDS from _MESSAGE_WRITE_COLUMNS
- use hermes_state_common._placeholders
- drop the dead resume-path stamp (the SELECT has no token_count, so it
  was always None) and the dead tool name assignment in
  _decoded_repair_row
- keep the digest out of divert JSONL

The kept active-row test now pins estimate stability across a flush and
the survival of a concurrent writer's row. It goes red on the old
prod files and red when the digest compare is removed.
2026-09-27 20:45:44 +05:30
teknium1
444066b82c fix: exclude display-only message fields from token estimates
Edit tool rows now carry display_metadata.tool_result_metadata.inline_diff
(~9KB of ANSI per edit) on the live message dict. build_api_messages strips
display_kind/display_metadata/_row_id before the wire, but the local
estimator's wire shadow only dropped PERSISTENCE_ONLY_MESSAGE_FIELDS
({"timestamp"}), so estimate_messages_tokens_rough and
estimate_request_tokens_rough priced the diff: one edit row went from 32 to
2527 estimated tokens (100 edits: 3100 -> 252600). That inflates compaction
preflight, post-tool checks and turn-overflow scoring, compacts early and
breaks the prompt cache.

PERSISTENCE_ONLY_MESSAGE_FIELDS (agent/message_metadata.py) is now the single
set of local-only fields: timestamp, display_kind, display_metadata, _row_id.
build_api_messages pops exactly that set and the estimator shadow drops it,
so the two can no longer drift. The iteration-limit summary path
(_iteration_summary_api_messages) hand-builds its wire messages and stripped
timestamp but not display_*; its key set now unions the same constant, so
the inline diff never reaches the provider there either (strict gateways
reject unknown keys). The tail-budget walk (_estimate_msg_budget_tokens) is
allowlist-based and already ignored these fields.
2026-09-23 22:45:56 -07:00
Teknium
4f20954c5f refactor(agent): tighten memory/compaction/prompt-cache helpers (pass 1, corpus parity) 2026-09-02 18:28:38 -07:00
Tuck
ca77157639 fix: create message_metadata module and update chat_completion_helpers 2026-08-15 01:04:19 -07:00