* fix(sessions): proactive prune rewrites only the changed rows, in place
A prune edits the content of a few existing messages and never adds, drops or
reorders one, yet every commit went through archive_and_compact, which
archives all active rows and re-inserts the full list: state.db grew by the
whole live transcript per commit (#124102).
SessionDB.rewrite_pruned_rows resolves each changed message to its live row
(_row_id, else its tool call id or tool-call ids, else the single active row
with the same role and stored content), checks the row still holds the
original, inserts one archived twin of the pre-prune row (active=0,
compacted=1, still searchable) and updates the changed columns under the same
id. The prune tries it after the stale-history watermark check and falls back
to archive_and_compact when a row cannot be named exactly or an unwritten
message sits before durable ones.
Fixes#124102
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
* fix(sessions): in-place prune twin keeps the live row's display slot
The content UPDATE fires messages_display_identity_update, which nulls
display_identity/display_order on the live row and on its freshly inserted
twin. The lazy backfill then gives the twin its own id as display_order, so
every demoted full body renders at the END of the transcript page, after the
newest user turn (3 x 24 KB bodies below "from desktop" in the probe).
Re-stamp both rows with the pre-update identity and order inside the same
transaction: the page projection shows one row per display_order (the live
stub, in place) and the twin stays a searchable archive. This is the same
stored-identity shape #117824 proposes for the archive writer (#117750), so
the resume projection collapses the pair once that lands.
Review-fix for #124273; one assertion added to the growth invariant
(red on the PR head: 20 page rows for 17 messages).
* fix(sessions): in-place prune keeps each display slot through later compaction and backfill
Review follow-up (ehz0ah): the rewritten live row kept the archived body's
identity, so a later archive_and_compact gave its copy a fresh slot and the
full body resurfaced in the old one. The live row now takes the identity of
what it stores and keeps the slot; the twin and any earlier generation's
copies (all nulled by the identity trigger) are restamped with their own
identity and slot, and the display backfill keeps a row's stored slot when
its stored identity is still correct. The prune pre-fills slots for legacy
rows so it never carries a missing one.
* fix(agent): fail closed when an in-place prune finds the row rewritten
rewrite_pruned_rows raised one PruneRowUnresolvedError for two different
conditions: the row cannot be named (ambiguity — the full writer handles it)
and the row IS named but its stored body changed. The second means another
surface already rewrote this generation, which is what StaleHeldHistory
exists to catch; the in-place prune preserves row ids, so
_archive_watermark_for cannot see it. Returning None there handed the stale
pruned_msgs to archive_and_compact, which archives rows it never compared
and republished the held text over a newer durable edit.
Split the stale case into a PruneRowStaleError subclass and raise
StaleHeldHistory from the in-place helper so the existing handler skips the
pass instead of committing. Ambiguity keeps the fallback.
Replaces the prune-fallback regression with the two cases review asked for:
a changed stored body skips the prune and leaves the newer body active; a
genuine ambiguity over current content still commits through the full writer.
* fix(agent): make an in-place prune visible to the other lease-less writer
rewrite_pruned_rows keeps every row id and activity flag, so the id/activity
staleness gate in held_archive_watermark cannot see that a prune already
committed. A second lease-less surface (micro-compaction) holding the pre-prune
transcript passes the gate and archive_and_compact republishes the pruned-away
bodies over the winner, undoing the prune.
stale_raises now also compares the held bodies against the stored ones via the
new SessionDB.rewritten_held_row_ids, so every lease-less writer sees the
in-place generation change, not just the prune caller that owns the exception.
* fix(state): compare durable row versions, not raw content, in the in-place stale guard
Reviewers on 631c897b converged on one root defect: the stale-write guard compared
raw SQLite bytes against a loaded/normalized view, which both missed real rewrites
and invented phantom ones.
- rewrite_pruned_rows._resolve: the staleness check is now the repo's stored-row CAS
digest (transcript_row_snapshot over a SELECT * row, covering every owned column
including assistant tool_calls arguments) when the held dict carries DB_ROW_SNAPSHOT,
and the loader-lens identity compare (_row_identity, the same representation
_stamp_kept_live_prefix uses) otherwise. Raw storage bytes are never compared
against a loaded view.
- The rewritten row's replacement dict is stamped with the row's new digest, and the
commit runs under _execute_transcript_write so a rollback restores the stamps.
- rewritten_held_row_ids takes full held dicts and applies the same two-leg compare;
only tool/assistant rows (the roles the in-place writer touches) are compared.
- held_archive_watermark(stale_raises=True) checks the durable prefix BEFORE the
ids[-1] is None early return, so an unstamped trailing message caps the watermark
but can no longer suppress version checks for the rows the caller holds exactly.
Closes the P0 stale tool_calls path, the P2 false-stale on freshly resumed
whitespace-padded rows, and the unstamped-tail blind spot (#124102).
* fix(state): gate the lease-less stale check on every role the fallback republishes
The staleness gate behind held_archive_watermark (rewritten_held_row_ids)
compared only tool/assistant held rows, but the fallback it guards —
archive_and_compact, reached whenever the in-place rewrite refuses (an
unwritten message before later durable rows, an unnamed row) — re-inserts
held rows of every model-transcript role verbatim. A user row another view
rewrote in place (set_user_message_content, the repair batch's in-place
rewrite) slipped the gate: the stale pre-edit body was republished active
and the newer edit left with zero active copies.
Compare every model-transcript role (user/assistant/tool); the per-row
comparison (DB_ROW_SNAPSHOT CAS, else the loader-lens identity) is already
role-agnostic. Bookkeeping roles stay excluded — they never reach the
model-facing list. Covers the prune fallback and micro-compaction, the two
lease-less callers of _archive_watermark_for (#124102).
Sabotage-run: reverting the role filter makes
test_a_concurrent_user_edit_stays_active_when_the_prune_falls_back fail
(stale body published); restored, the file is 22/22 green.
* style: use builtin generics in the in-place prune commit annotations
* refactor(compression): split the proactive prune and its commit into topical siblings
The code-health ratchet (CI) flags this PR's own growth: hermes_state_messages.py
(2190 > 2000), agent/context_compressor.py (5911 > its main value 5852) and
agent/conversation_compression.py (4585 > 4564). The remedy the repo prescribes:
move the PR's own code into topical siblings, keeping the facade as the seam.
- agent/context_compressor_prune.py: ProactivePruneMixin (prune_tool_results_only
+ _rewrite_pruned_rows_in_place), bound into ContextCompressor; origin-module
symbols read through _cc() at call time (the micro_compaction.py pattern) so
tests patching agent.context_compressor.X stay effective; logger keeps the
agent.context_compressor name for caplog parity.
- agent/conversation_compression_watermark.py: held_archive_watermark; the origin
module imports it and keeps _held_watermark (its only caller).
- hermes_state_prune_rewrite.py: SessionPruneRewriteMixin (rewrite_pruned_rows +
rewritten_held_row_ids), bound into SessionDB; every SessionDB call site and
test patch seam (db.rewrite_pruned_rows / db.rewritten_held_row_ids) unchanged.
Verified: scripts/check --only health --base origin/main -> 0 blocking; ruff clean;
prune/compaction batches green (test_proactive_prune_restart_safety 22/22,
test_micro_compaction 48/48, five proactive-prune files 25/25). The 4 failures in
test_compaction_prompt_rebuild / test_compression_review reproduce identically on
origin/main (pre-existing).
* fix(state): re-verify held rows inside the full writer's commit transaction
The lease-less stale gate (rewritten_held_row_ids) runs outside the write
transaction, so a second SessionDB connection that rewrites a covered row
AFTER the precheck but BEFORE archive_and_compact's BEGIN IMMEDIATE was
invisible to it: the commit archived the newer row and republished the stale
held text, leaving the newer edit with zero active copies (#124102, review
finding on 8c6da464).
- archive_and_compact takes held_for_cas: the caller's held dicts,
re-verified against the live rows INSIDE the commit's transaction before
any row moves; a mismatch raises HeldRowRewrittenError, which the two
lease-less callers (proactive prune fallback, micro-compaction sync)
treat exactly like StaleHeldHistory - nothing written, the pass is a
no-op and the newer generation keeps the session. The lease path leaves
it None: its lease rules out an overlapping rewrite.
- held_row_mismatches(conn, ...) is the compare lifted out of
rewritten_held_row_ids so both the read-path precheck and the
in-transaction fence share one implementation. It now chunks the id IN
query via _id_chunks (a history past SQLite's host-parameter limit
failed the pass instead of reclaiming) and resolves rows that have no
_row_id but do carry the persist marker + CAS snapshot by their logical
message_uid (idx_messages_session_uid) - the unaddressed live-replay
loader shape, whose rows were previously exempt from the fence entirely.
- regression: test_a_user_edit_landing_after_the_precheck_stays_active_in_the_commit
drives a second SessionDB connection's set_user_message_content at the
archive_and_compact call boundary; sabotage (gate disabled) makes it
fail exactly as the finding predicts.
* refactor(compression): drop the duplicate _held_watermark from the module split
The 8c6da464 sibling extraction left two identical _held_watermark
definitions back to back in agent/conversation_compression.py; Python
silently kept only the second, so editing the first had no effect (dead
code, root AGENTS.md). Remove the added copy.
* refactor(state): split the api_content sidecar writers into a topical sibling
hermes_state_messages.py crossed the FILE_LINES ratchet (2010 > 2000) after
the commit-window fence landed in it. Move set_latest_user_api_content /
set_message_api_content into hermes_state_api_content.py
(SessionApiContentMixin, bound into SessionDB in the same MRO slot): the
two row-addressed api_content sidecar UPDATEs are one topic, no behaviour
change, every call site and test patch seam unchanged.
* fix(state): flatten _archive_and_compact_on_conn onto the caller's transaction after the main merge
Main flattened this helper to run directly on the caller's write connection
(no nested _execute_transcript_write); the merge resolution had kept the old
nested shape, which opened a second BEGIN IMMEDIATE inside the live one and
deadlocked every archive_and_compact. Re-flattened while keeping the #124102
held_for_cas in-transaction CAS fence.
* fix(state): carry the held-row CAS fence through the worker RPC path
RuntimeSessionCompressionMixin.archive_and_compact rejected held_for_cas,
so a worker-side micro-compaction commit raised TypeError inside the mixin's
generic except and silently skipped the whole persist (unstamped marker,
durable transcript left un-compacted). Accept held_for_cas, project it onto
the closed handoff fields plus the persistence marker the CAS compare reads,
validate it in worker_archive, and thread it into
archive_on_connection -> _archive_and_compact_on_conn (#124102).
* test(micro): a stale held generation without row ids aborts the micro-compact
Review follow-up (ehz0ah/greptile-apps, PR #124273): ACP restore and OpenAI
session continuation load through the unaddressed live-replay projection
(get_messages_as_conversation without include_row_ids=True) — the persist
marker, durable message_uid and the stored-row CAS digest, but no _row_id.
held_row_mismatches already resolves that shape by logical message_uid, so
the lease-less fence still sees another surface's in-place prune. Pin it with
the regression both reviewers asked for: after another surface prunes in
place, micro-compaction from that stale no-row-id history is a true no-op —
the pruned stubs stay the only live generation and the pre-prune bodies are
not republished (#124102).
Sabotage: disabling the by-uid branch in held_row_mismatches fails this
test (the sync republishes the stale bodies); restored, 49/49 pass.
Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>
* fix(sessions): the uid-resolved stale fence CASes the newest active row
held_row_mismatches resolved an id-less held dict by its logical
message_uid with a bare fetchone(): when a carried or concurrent
compaction has cloned the row back beside its archived twin, one uid
names several active physical rows, and the uid index returns them
oldest-first. The fence then CASed the oldest copy — which still held
the payload the held digest was stamped from — and cleared a held
generation as current although another writer had rewritten the newest
row; the lease-less fallback republished the stale held payload over
that newer generation (#124102).
Resolve with the same newest-active rule as the loader's
_active_logical_message_row (ORDER BY id DESC LIMIT 1). Two
regressions pin it: two active rows sharing a uid where only the
newest was rewritten in place must abort the micro-compact naming the
newest row id, and where only an older duplicate moved the held
digest must stay current.
Review follow-up to greptile-apps' 2026-10-17 P1 on PR #124273.
---------
Co-authored-by: defurniture2025 <301948806+defurniture2025@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: teknium1 <127238744+teknium1@users.noreply.github.com>
Co-authored-by: Austin Pickett <pickett.austin@gmail.com>
Co-authored-by: Austin Pickett <austinpickett@users.noreply.github.com>
Co-authored-by: ehz0ah <ehz0ah@users.noreply.github.com>
Prompt reading on llama-server pushes the fence deadline back
(CompressionCommitFence.extend_deadline). The stall fallback still got the
primary attempt's original precommit_deadline_monotonic, so a long prompt
read followed by a stall skipped the configured fallback ("shared pre-commit
ceiling is spent") while the fence still had time. Neither the v0.22.2
prompt-reading change nor main's shared pre-commit budget had the bug alone;
it appeared when the forward port combined them.
Pass the fence's current deadline into the fallback chain.
A press reviewer ran Qwen 27B on a 64 GB RTX Spark and saw single queries take hours. The
causes, and what each part of this change does about them:
- llama-server reads a long prompt for minutes before the first token. Local requests now
always stream and ask for prompt-reading progress, so the stall timers see the server
working and the router notices a hang-up within seconds. They no longer fall back to a
non-streamed request, which the router can't cancel. The status line shows how much of
the prompt the server has read.
- A laptop that sleeps mid-request froze the request, and the stall timer cut it on wake.
Stall timers for a server on the same machine now skip time the process was stopped
(sleep or Modern Standby). Background-call watchdogs run on the awake clock.
- After repeated stalls the breaker failed every later message at once, even after the local
server recovered. At turn start, a local server that answers its health check gets one more
attempt; one more stall shuts the breaker again.
- On Windows unified memory, the GPU carve-out is invisible to Windows, and the model plus
llama-server's default 8 GiB prompt cache overran commit. Free commit now narrows the launch
window (never refusing a model the pool can hold), caps how many models the router holds at
once, and sizes the prompt cache, split across those models.
- Hermes's status reads named the model, and the router loads any model a request names, so
Eject and the idle unload reloaded the model at once. Status reads pass autoload=false; an
unloaded model counts as idle, and the context probe reads the router's launch args.
- The smart-approval verdict has a 16-token budget, and a thinking model spent all of it
thinking (45 of 45 verdicts came back empty). The verdict asks for no thinking unless the
operator set auxiliary.approval.reasoning_effort.
- Compression's 600 s limit counted the time the server spent reading a 150K-token
conversation, which alone can exceed it on a laptop GPU. Prompt reading now pushes the fence
deadline back (CompressionCommitFence.extend_deadline), only while the server reports newly read
tokens, and never past a fence the host closed or one a commit holds. The agent and gateway
hygiene waits read the moved deadline after every slice.
- Desktop keep-awake defaults to "while working". When a timed sleep interrupts a turn with
keep-awake off, the next wake offers it once per computer; the offer survives the next prompt.
(cherry picked from commit 518ce272b9)
Follow-up to #139923 (salvage of #105100), from its review:
- When a compression-exhausted turn left a queued event, _run_agent_drain_pending returned before
_merge_leftover_steer, so a /steer the agent had already taken out of its buffer
(result["pending_steer"]) vanished. _defer_past_exhaustion_reset now queues it ahead of the
deferred event, the same steer-first order as the normal path.
- conversation_compression re-exported every helper moved to conversation_compression_checkpoint.
Internal moves get no re-export shims: callers and tests import from the new module, and the
facade keeps only the two names it uses.
- test_total_ceiling_exhaustion_does_not_start_fallback used a 0.3 s budget; raised to the 2 s
floor from tests/AGENTS.md.
Reported-by: greptile-apps
Code-health ratchet: conversation_compression.py and run_turn.py may only
shrink and _run_agent_drain_pending was at its CC cap. Move the pre-compress
checkpoint gate into conversation_compression_checkpoint.py (re-exported, same
logger) and the leftover-/steer merge into run_busy's FIFO helpers. No
behaviour change.
One conflict: agent/context_compressor.py imports. Main's a62979dc36 dropped the
now-unused _safe_int import; the branch's retryable_user_text import is kept.
Review threads on #136050 and #136051 (agent/conversation_compression.py,
"Overlapping calls erase attempt details" / "Skipped calls erase active
records"). `_begin_compression_attempt` cleared the compressor's three
attempt-telemetry fields and rewrote its seed at entry, before the
automatic gate and the session lease. A second automatic call that stopped
at the gate (e.g. a cooldown while overflow recovery ran with
`bypass_cooldown=True`) therefore erased the running attempt's record. That
attempt could still commit, but logged `method: none` with no counts and no
fallback class, so a fallback commit read as a clean shared-metric success.
The previous-attempt clear (#118580) now runs in `_run_summary_phase`, under
the lease, just before the summary dispatch. The same statement writes this
attempt's own seed, so the entry-time seed write goes. Calls that stop at a
gate, the lease, or a stale snapshot never touch the shared fields.
A rewrite that survives a later bookkeeping failure (`failed_not_indexed`
after the atomic archive) also gets its counts finalized from the saved
transcript, using the same `rewritten` result that names the Relay mark
(thread "Saved tails disappear from counts" on #136051).
Review thread on #136083 (agent/conversation_compression.py, "Committed
rewrites look failed"). The commit-path attempt record decided
`history_rewritten` with `compressed is not messages`. A context engine may
compact its input list in place, so the returned list IS the input even
after `archive_and_compact` stored it. If a later bookkeeping write
(`update_system_prompt`) then fails, the record read
`history_rewritten: false`, the Relay mark was `compaction.attempt`, and
Relay skipped the history-freshness reset although the model now sees the
compacted transcript.
Use `commit.compacted_in_place`, which `_commit_compaction` sets on the line
after the atomic archive returns, alongside the identity check.
Overflow recovery calls the automatic gate with `bypass_cooldown=True`, so
the summary-failure cooldown cannot be what blocked it. But
`_compression_block_reason()` always reported the cooldown first, so with a
cooldown also active:
- the attempt record said `blocked:cooldown` while the structural backoff
or the ineffective breaker was the real blocker, and
- `_mark_compression_blocked_transient` marked an `ineffective` block as
transient, so overflow recovery deferred instead of counting toward
exhaustion, which #97488 says must never happen.
`_compression_block_reason` takes the gate's `ignore_cooldown` flag.
`_automatic_compression_gate_blocks` reads the reason once, with the same
flag the gate got (older engines keep the no-argument calls), and returns it;
the transient signal and the blocked attempt record both use that one
reason, so the telemetry module no longer re-derives the guard order.
Follow-up to #136083 (salvage of #135807):
- `agent._compression_attempt_seed` had one reader, the `_attempt_seed`
fallback, which every production emit bypasses by passing `attempt.seed`;
the only seedless emit (pool saturation) passes `attempt_began=False` and
never matched it. Removed.
- Both attempt emitters log through `_log_attempt_record`, so the line
`scripts/micro_compaction_report.py` parses has one source.
- The in-place coverage call reuses `original_messages`, and the
`_commit_compaction` docstring lists the anti-growth guard before memory
extraction, matching the order #135866 introduced.
Three conflicts:
- apps/desktop/electron/updater/checkout-source.test.ts: main's 354fe11d7e is the
same releases/latest fixture fix this branch carried as c300c295c1 (#135944); main's
version (it also drops the unused release-candidates route) is taken.
- agent/context_compressor.py: both sides added one import line; both kept.
- gateway/run_turn.py: main's 4c7ab8b2a0 added trigger="gateway_hygiene" to the hygiene
_compress_context call this branch moved to gateway/run_turn_hygiene.py; the branch side
of run_turn.py is kept and the trigger is carried onto the moved call.
A wedged Relay pipeline made every compaction block for SCOPE_OP_TIMEOUT
(10s) while it still held the compression lease, with no breaker. The
first stalled mark now trips a process-wide flag and later marks return
immediately; marks are observability and must never tax compaction.
Also: make relay_runtime.SCOPE_OP_TIMEOUT public (relay_compaction reads
it), fold the commit-time telemetry hold into _hold_attempt_telemetry
with one _ATTEMPT_TELEMETRY_FIELDS tuple, and drop the mapping-table
change-detector tests (the ATOF freshness and failure invariants stay).
overflow_reason is a v1 field, but it was always null: both overflow
callers passed only trigger="overflow", although each already holds the
error classifier's verdict for the provider rejection it recovers from.
A consumer could not tell a 413 from a context-length rejection or the
Anthropic long-context tier gate.
Both callers now pass the classified reason through _compress_context
into the attempt seed, so the attempt log line and the compaction mark
carry it. The mark keeps it in a closed set (context_overflow,
payload_too_large, long_context_tier, else other) and leaves it null for
every other trigger. The Relay docs list the set instead of calling the
field reserved.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit c3ad6f7fb8bfcc8f9c350f3a4272029d63333c7f)
Review of the first cut of the marks found four places where the record
said something the attempt did not:
- A split that failed after it had stored the compacted history
(failed_not_indexed without a rollback) returns the compacted
transcript, so the model sees it next, but the record read
aborted/failed and was named compaction.attempt. Relay then never
reset freshness and the compacted history was never recorded. The
commit path now logs history_rewritten (whether the returned
transcript replaced the input), and such a record is a committed
compaction with failure_class session_split_failed and split_status
failed_not_indexed.
- in_place and session_rotated read false/false on a commit without a
session database. They are now set only when split_status is
in_place_committed or rotated_committed, and null otherwise.
- trigger_class read auto for a record with no trigger or an unlisted
one. It now reads unknown there; an unlabelled automatic caller
(trigger_source auto) keeps trigger unknown with trigger_class auto.
- The v1 sets listed values Hermes never emits (kind request_truncation
and window_reduction, scope request, trigger recovery, outcome noop,
token_count_method provider_usage, split_status pending and unknown).
Consumers treated them as live. They are dropped from the v1 sets and
documented as reserved for later versions.
session_ownership_unreadable joins the attempt-only failure classes.
The Compaction Marks docs now list the four sources exactly, what does
not emit a mark yet (OpenAI Responses native compaction and its
pre-checkpoint pruning, image shrinking after a provider rejection,
request-only truncation), the closed sets and null policy, why a Codex
app-server compaction keeps the compaction name (Relay records no LLM
start for those turns, so the freshness reset only affects a later
Hermes-side call) and is never marked twice, and two known gaps around
rotating compactions.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 6e6bc81fc0e074c88d1d632e8110d7490e203015)
Finalize effect counts from the transcript that crosses the commit boundary, including retained partial-compression tails and boundary anchors. Explicitly discard bypassed shared-metric state so a later refusal cannot consume stale attempt metadata.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit ddf3b229a9e2fdee651f36afbec974717d334f76)
The candidate guard refused an empty transcript from a context engine and
returned without an attempt record, so that compress_context call logged
nothing and the shared metric never counted it. Every other refusal in the
guard logs its own class.
Log it as an aborted attempt with failure_class empty_transcript; the shared
metric counts it once as failed under its closed-set "other" class.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 3f6a58fb3f2695a58d67fedb9f7410abff95ad58)
The attempt record read its identity from the agent's current-attempt fields,
which the next attempt overwrites when it begins. A stalled attempt that
unwound after its stall fallback had started therefore logged the fallback's
attempt_id, session_id and trigger_source, so two records claimed one attempt
and the stalled one disappeared.
Each attempt now carries its own seed on _Attempt and passes it to every
emit, so the record always describes the attempt that wrote it. Emits with no
attempt in hand (pool saturation) keep reading the agent's copy.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit a36db44d63888406702cab44d3ca29335727a6e2)
Every returning exit of the Codex route logs one attempt record, but
two exits raised after the attempt began and logged nothing: an
exception from compact_thread() only stopped the heartbeat and
re-raised, and compress_context raised CompressionCheckpointUnavailable
for a Codex-owned thread with compression.checkpoint_required set. A
consumer counting attempts saw neither.
Both exits now log one codex_app_server record, aborted with
exception:<Type>, the same class shape the Hermes route records when its
summary phase raises. The record carries the type name only, never the
error text, and the caller still receives the original exception object.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 17e55b05801624ea16f034b31e2408d386ee19f0)
_adopt_if_parent_rotated returns the same sit-out result for two
different exits: the lease found the parent already rotated by another
path (ownership lost), and the ownership lookup itself raised
("skipping compression this cycle", ownership unknown). Both were logged
as session_ownership_lost.
Each exit now writes its own record from inside the helper: a rotated
parent is skipped / session_ownership_lost, and a failed lookup is
aborted / session_ownership_unreadable, the same shape as the existing
cooldown_state_unreadable exit. Both records name the session the
attempt started in, not the child an adoption switched the agent to.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 83dfe1eaf6e630198734a65d8c13a26945ff43d9)
An attempt record that is written before compress() seeds this
attempt's telemetry, or after a pre-commit restore, did not describe
that attempt:
- snapshot_stale and the early commit_fence_cancelled exit run after the
attempt-start clear, so the record had no trigger_source;
- a commit fence refused after the summary restores the compressor's
pre-attempt state, which puts the previous attempt's dict back, so the
record carried the previous attempt_id, trigger, method and reclaimed
tokens with this attempt's failure class;
- pool_saturated fires before any attempt begins, but still took the
previous attempt_id from the agent.
_begin_compression_attempt now keeps the attempt seed (attempt_id, the
session the attempt started in, trigger) on the agent as well, since a
restore replaces the compressor's copy. When the compressor's telemetry
is not this attempt's own, the emitter starts the record from that seed
with method none and no token counts, and ignores the compressor's
fallback flags, which belong to the same earlier attempt. A refusal with
no attempt begun gets a fresh id and trigger unknown. Bypassed exits read
the same seed, so they also name the session the attempt started in
rather than a child it adopted.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit c29dba73a4c07c833951666f517a237e1e0fc65d)
The content-free attempt record is the one place that says why a
compaction ran and what it did, but it could not answer either question:
- Every automatic caller passed no trigger, so idle, turn-start
threshold, engine preflight, pre-API, post-tool and gateway hygiene
attempts all logged trigger_source=auto. Each call site now passes its
own label; the shared metric still buckets them as auto.
- tokens after, message counts and how the summary was made were
computed and logged as prose but never reached the record. A finished
rewrite now records messages_before/after, tokens_before/after,
tokens_reclaimed (signed; a summary can grow a short transcript),
token_count_method=estimate_rough, method (llm_summary,
aux_fallback_main, deterministic_fallback), items_dropped, and the
tool_results_pruned / reasoning_items_pruned pass counts.
- Attempts that never reached the local compressor returned silently:
the automatic breaker gate (before and under the lease), every Codex
app-server exit, a lease that found the session already rotated, and
an unreadable durable cooldown. Each now logs one record with a
commit_status (blocked, skipped, failed, aborted, committed), a route,
and a class such as blocked:cooldown. These stay out of shared metrics,
which never counted them.
Test doubles for _compress_context gain the trigger keyword the call
sites now pass.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 1795993d1a01d91dd76e6ec824cb606f8a03b897)
context_compressor.py and conversation_compression.py are both past the
2,000-line cap, so the attempt-telemetry fixes that follow need room in
them. Move code that already has a topical home, unchanged:
- ContextCompressor's per-attempt telemetry methods (_begin_compression_telemetry,
_record_compression_regions, _record_aux_compression_call) and _safe_int
become CompressionTelemetryMixin in agent/context_compressor_telemetry.py.
- The Codex app-server compaction route (_compress_context_via_codex_app_server,
_record_codex_compaction_failure) joins its cooldown lookup in
agent/conversation_compression_codex.py and late-imports the facade's
shared helpers.
No behavior change.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 91d981495f6baee699316d5e843276b32d6a6b9e)
The commit-time hold keeps the telemetry trio for its own attempt's
success emit. Clear it at the start of the next attempt (and keep
pool-saturation refusal emits from inheriting the last attempt's
payload) so a later emit cannot report the previous attempt's numbers.
Follow-up on the #118580 review.
[Ported onto main, where _emit_compression_attempt_telemetry now lives in
agent/conversation_compression_telemetry.py: the include_last_telemetry
parameter moved there with the same behavior.]
(cherry picked from commit 1c05c6a6e713cd77aee3111d5a809572ad3f7d0c)
(cherry picked from commit 5a551af25a643d0d6c1f1ded2ce9d9c4a52276ba)
_commit_compaction calls commit_memory_session before the success emit.
The engine session-end notification answers with a full per-session
reset, nulling _last/_active_compression_telemetry, so the emit fell
back to {} and every committed line carried emitter defaults only.
Closes#118580
(cherry picked from commit b2242e0aa79dbc9ce2995e1a0cf8a88867869801)
(cherry picked from commit 865ace8293ec8138c309a02d8fc18b34f7e6fffb)
Restore the pre-compression transcript when a context engine raises. Evaluate growth against the immutable input snapshot and defer memory publication until the candidate passes every refusal gate, so in-place mutation cannot bypass refusal or leak side effects.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit 969371c564c172046934b535b3488610171726de)
Context engines may mutate the message list they receive, and the
context-engine plugin guide says that mutation only becomes visible if
the pass commits. Callers that pass their own commit fence (gateway
session hygiene) or set compression.context_timeout_seconds to 0 hand
the live list to the engine without the facade's deep snapshot.
compress_context restored the pre-compression snapshot on the
no-progress and superseded refusals, but the compressor-abort,
empty-transcript and would-grow refusals returned the live list as the
engine left it. An engine that cleared its input and returned [] made
compress_context return an empty transcript while warning that the
conversation continues unchanged.
Restore the snapshot in compress_context whenever _candidate_rejected
refuses a candidate or the commit refuses a grown one, so every refusal
returns the original transcript. The no-progress and superseded
branches no longer restore on their own because the caller now does it
for every refusal. Warnings, telemetry and the commit path are
unchanged.
Signed-off-by: mnajafian-nv <mnajafian@nvidia.com>
(cherry picked from commit d14fc7c96031d15f85acb00d433bcfdd39804554)
17 conflicts, all from main's lint sweep (ruff UP007/UP017/UP022/UP028/UP031/UP037/UP041,
FURB188/FURB192); 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). ruff.strict.toml takes main's copy. The pool-retirement live fixture stays
deleted with the pooled backend this branch retires.
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).
Conflicts:
- gateway/run_turn.py: the branch moved the block to run_turn_prepare; main's b1a39a1b1b
restore_session_yolo call ported there.
- Desktop pool (main 167e9fdb84 no-idle-reap): the branch removed the local backend pool;
pool-retire.{ts,test.ts} and pool-limits-setting.tsx stay deleted, main.ts keeps no pool.
main's MSIX relaunch-waiter logging (bdb8f92f3b) auto-merged.
- e2e/core/no-idle-reap.spec.ts rewritten for the single local gateway: a profile dial stays on
the same gateway pids and descriptor past the old pool idle window (1 passed, 3.6m).
One /yolo contract: gateway-owned sessions (session_busy_controls.yolo_config -> toggle_session_yolo)
and managed workers (restore_session_yolo) use main's tools/approval_yolo.py; the launch --yolo seed
(apply_launch_yolo) moved there and is skipped under a process-wide --yolo.
The persist / restore / carry logic for session YOLO had grown three copies
(the CLI mixin, tui_gateway, the gateway runner), each with its own key choice,
ordering and error handling. tools/approval_yolo.py now owns it:
- toggle_session_yolo: flip or set, persist BEFORE the live flip (a racing
restore never revives an OFF), stored-copy-aware so a toggle after a restart
turns it OFF; a failed write logs a warning and never blocks the flip.
- restore_session_yolo: re-arm a persisted flag in a fresh process; skipped
under the frozen process --yolo.
- transfer_session_yolo: move the live flag to a continuation id.
- with_session_yolo: a row being created records a live flag (lazy first row,
compression child, /branch).
Each surface keeps only its storage: the session row for CLI/TUI/Desktop, the
routing entry for the gateway. Removed: HermesCLI._transfer_session_yolo /
_persist_session_yolo, GatewayRunner._restore_session_yolo, the TUI-only
restore helper, and the TUI's post-publish set_session_yolo carry (the
compression publish now writes the child row with the flag).
Closes a gap the unification exposed: a CLI manual /compress that rotated the
session dropped YOLO (the next dangerous command prompted, and a --resume of
the continuation came back with it off).
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.
The split-out conversation_compression_codex imports only logging/typing, so there is no cycle to
dodge: move the function-local import into the top-level block beside
conversation_compression_telemetry and fix the sibling's docstring to match. Drop the
client_lifecycle comment that repeated rotate_runtime_main_api_key's own docstring.
_refresh_main_credential keeps its api_mode pre-check and _swallow wrapper: the callee returns
False off anthropic_messages but does not swallow exceptions from its holder moves / aux rotation.
Fold finding C15 #4 (gate quality review).
compress_context ran _refresh_main_credential before _announce_compression_start, so an expired
Claude Code token's blocking network refresh left the Desktop working row a bare spinner -- the
exact delay #111294 moved the announce first to avoid. Refresh right after the announce instead;
nothing between the two touches the client, and it still precedes the feasibility probe and the
summary call. The kept compression test now also asserts the announce saw the pre-refresh state.
Fold finding C15 #3 (gate efficiency review).
Code-health ratchet: the pre-compression credential refresh grew agent/conversation_compression.py
to 4591 lines, over its 4579 cap on main. Pure move (body byte-identical), late-imported at its one
call site; no test or doc references the old path.
The main loop re-resolves the Anthropic OAuth token before each request, but a compression that runs
before the next request (manual /compress, preflight compaction) still summarised with the token the
last request used. compress_context now runs the same refresh first.
(cherry picked from commit 63e22d597340aa042c3c736062e1190e31a9f96e, agent/conversation_compression.py hunk only)
* fix(agent): free-tier rate limits end an attended turn at once
A free-tier (no sign-in) session that hit the service-wide rate limit slept
up to 600 s, retried into the same refusal, slept again, and then sent its
third attempt on a guest JWT that had expired during the wait. The welcome
host answered 403 "invalid jwt", which read as the tier being switched off.
The user watched a spinner for about 18 minutes and then saw the wrong card.
- An attended session (desktop, TUI, the interactive CLI, ACP) on the free
model ends the attempt cycle at once when the cooldown is longer than
60 s: fallback first, else the reset time and the sign-in / model doors.
"Attended" is keyed on the session source, so `hermes chat -q`, cron and
messaging sessions keep the long wait. The source vocabulary moves from
run_agent.py into agent/session_source.py, which adds is_attended().
- on_free_model() (welcome host + anonymous credential) is the one free-tier
check, used by the cutoff, the "free model is busy" wait copy and the
outage copy.
- A welcome-host 403 "invalid jwt" is its own route kind, session_expired:
the existing one-shot route heal re-exchanges the credential and retries;
if that fails the card is the retryable outage card.
- interruptible_backoff_sleep adopts a fresh Nous key after each wait.
_adopt_nous_key_before_expiry owns its refresh failure, so both call
sites drop their try/except.
- A retry wait over 60 s is announced in the transcript when it starts, for
every provider; shorter waits stay buffered. Every wait line names the
attempt that runs after it.
- max_retries_exhausted_result's max_retries becomes attempts (what it
carries); a one-attempt rate-limit end gets its own lead.
- One Retry-After reader, retry_utils.provider_retry_after_seconds, shared
by compute_error_backoff and the recovery ladder.
- _session_default_route replaces _session_default_model everywhere in
tui_gateway, so a not-yet-built free-tier session reports nous/welcome on
create, reuse, resume, branch and row persist, not the silent default.
* fix(agent): free-tier cutoff no longer ends subagent or library turns, paid waits look like main (review)
A delegated child of a TUI/Desktop session and a library caller (no platform) are unattended, so they keep waiting.
Rate-limit wait lines keep main's attempt numbers and stay buffered for every provider; only a non-rate-limit Retry-After over 60 s is announced, as on main.
The unattended free-tier wait line keeps the reset time beside "The free model is busy".
The free-tier cutoff names the reset time for any cooldown it fires on (over 60 s), not only from 120 s.
session.info for an env-seeded model off the free tier carries the model alone again, as on main.
Behaviour tests for the cutoff, the subagent and unattended waits, and a paid long wait.
explicit_interrupt was emitted for every AuxiliaryExplicitCancellation, including
the host cancelling the commit fence on timeout (gateway hygiene 30 s budget, the
600 s total ceiling while still streaming). Those are real failures, but the
skipped set made them read as a user stop. Use explicit_interrupt only when the
user's stop event is set; a fence cancel without it reports
commit_fence_cancelled (already a failed class).
The generic-verdict deferral now defers only to the current attempt's recorded
class, so a snapshot restore cannot hand it the previous attempt's class.
The attempt emitters move to agent/conversation_compression_telemetry.py (same
logger name) so the facade stays under its line cap.
The attempt-telemetry emitter let the caller's generic abort verdict
overwrite the class the compressor recorded for the same outcome. A
transcript that fits inside the tail budget was logged as "no_progress"
instead of "no_compressible_window" (#131412), and a terminal summary
failure as "summary_generation_aborted" instead of its documented class
("summary_auth_failure", "summary_overload_failure", ...).
Only those two caller labels defer to a recorded class; every other label
names an event the compressor cannot see (fence cancelled, superseded,
rollback, pool saturated) and still wins. The shared-metrics sink receives
the same resolved class as the log line.
Refs #131412
Review fixes for the per-module plugin load lock:
- A second caller waits at most 10 s for another thread's load of the same
module, then refuses with a named warning and returns None. While that
import is still stuck, later callers refuse at once. A hung provider import
no longer blocks every gateway turn, and there is no inline fallback load.
- The wait polls a wait-for graph spanning the loader locks and importlib's
own module locks. When thread A holds a helper's import lock and waits on
the plugin while thread B loads the plugin and imports that helper, the
cycle is detected and the waiter takes the partial module, the same way
importlib handles a concurrent circular import. Before, both threads hung.
- The lock is still a same-thread RLock with no worker thread, so recursive
loads and ContextVars are unchanged.
- conversation_compression.py: compact the fork-checkpoint exemption so the
file stays under its line cap after the rebase.
Gate quality (BS02 r1, Low): the rotation branch re-imported
rejoin_compressed_head_and_tail and stamp_db_persisted_markers locally, which
the in-place branch already imports. Import both once above `if in_place:`
(net -2 lines for the file). The duplicated test setup the same finding
named belonged to the fallback test removed earlier in this stack, so no
helper is needed. No behaviour change.
Rotation published only head + summary; compress_now rejoined the kept
verbatim tail in memory and the gateway's second rewrite was what made it
durable. With that rewrite now skipped for a published child (it deleted
the atomically cloned foreign tail), a rotated `/compress here N` lost the
kept exchanges from the child. CLI/TUI/ACP never rewrote, so they already
persisted head-only.
Publish rejoin_compressed_head_and_tail(compressed, verbatim_tail) in the
rotation handoff exactly like the in-place branch stores it, and stamp the
tail rows so compress_now skips its in-memory rejoin. Fixes every surface.
gateway/run.py copied the merged/unnamed/retired durable-row stamps by
string literal; a rename of the constants in conversation_compression_archive
would silently stop the gateway replay from carrying them. Loop over the
constants instead.
The in-place tail widening in _commit_compaction counted
`_absorbed_row_ids` by hand under a comment about merged users only. Since
the stack, that list also holds the orphan tool/assistant rows the repair
drops, so reword the comment, and use ABSORBED_ROW_IDS and _positive_id
(which also rejects bools) rather than re-rolling them.
The dropped-tool-call repair test asserts the exact repair count (1)
instead of hedging with >= 1.
A prompt that never got its reply leaves a durable user;user pair. The
alternation repair hands the compressor one dict for both rows, and the
in-place commit counted it as one original.
On a reload without row ids (gateway) the merged dict matched no row, read
as an unpersisted turn, and its two rows were re-sequenced after the
compacted set: the old prompts landed behind the running turn, and the
tail rewind reached one row into the summarized region and hid it.
With row ids the absorbed row was covered but not counted, so the oldest
carried original stayed compacted=1 beside its live copy.
The commit now resolves a merged user dict to the run of active rows it
was built from, and the tail rewind covers every row a tail dict absorbed.
(cherry picked from commit ba02ecf54487ca5235b99f70e6370db66aba94f4)
(cherry picked from commit 09715419ac7de957b757b5446208d05e26e75f3b)