Skip to content

feat(archive): thread stop_reason to query path, derive terminal_state - #3535

Merged
Sinity merged 1 commit into
masterfrom
feature/storage/thread-stop-reason-terminal-state
Aug 2, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/storage/thread-stop-reason-terminal-state

Conversation

@Sinity

@Sinity Sinity commented Aug 2, 2026

Copy link
Copy Markdown
Owner

Summary

Completes the remaining query-path gap from polylogue-2qx.4 and lands the first real dependent-column derivation for polylogue-cuxz.8: messages.stop_reason now survives the bulk query-execution path (not just single-session reads), and session_profiles.terminal_state (plus the two delegation_facts columns that are SQL views over it) derives from it instead of falling back to unknown for a refused or truncated turn.

Problem

polylogue-cuxz.8 found the archive can't say how most sessions ended:

delegation_facts.result_status          'unknown'   99%  of 11,692
delegation_facts.parent_terminal_state  'unknown'   96%  of 11,692
session_profiles.terminal_state         'unknown'   85%  of 18,871
delegation_facts.child_terminal_state   'unknown'   56%  of 11,692

Meanwhile Claude's wire carries message.stop_reason on 608,608 assistant messages, including 70 refusal and 17 max_tokens cases that are otherwise invisible in any surface. A prior partial fix (polylogue-2qx.4) persisted stop_reason to messages.stop_reason and threaded it into the single-session repository.get() read path (storage/hydrators.py::message_from_record), but its own bd note flagged two explicit gaps: the bulk query-execution path (archive/query/archive_execution.py, behind SessionFilter.list() / the CLI-MCP find/sessions where ... query grammar) still dropped the field entirely, and no consumer derived terminal_state/result_status from it yet.

Solution

  • ArchiveMessageRow/ArchiveBlockRow (storage/sqlite/archive_tiers/write.py) gain stop_reason / tool_result_outcome_unknown_reason fields, threaded through all four read sites that construct them: the full-session envelope read, the paged-window read (_fetch_message_window), and the two block/message SQL SELECTs underneath them.
  • archive/query/archive_execution.py::_message_to_domain — the exact function the prior fix's bd note named as the missing link — now copies stop_reason onto the domain Message and the companion unknown-reason onto block dicts.
  • MessageSemanticFacts (archive/semantic/models.py) gains a stop_reason field, threaded from the domain Message in archive/semantic/facts.py, so archive/session/runtime.py::_terminal_state can see it on the last meaningful turn.
  • _terminal_state now consults the last assistant turn's stop_reason before falling back to unknown: REFUSAL -> "refused", MAX_TOKENS -> "truncated". TOOL_USE/STOP_SEQUENCE are deliberately not claimed: TOOL_USE is already fully covered by the existing pending-tool/action-outcome structural checks, and STOP_SEQUENCE alone doesn't distinguish a clean stop from truncation the way MAX_TOKENS unambiguously does.
  • Because delegation_facts.parent_terminal_state/child_terminal_state are SQL views joining session_profiles.terminal_state (not independently-guessed columns — confirmed by reading storage/sqlite/archive_tiers/index.py's delegation_facts view definition), this one change improves those two columns for free, without touching them directly.

Schema classification: no schema change. messages.stop_reason and blocks.tool_result_outcome_unknown_reason already exist (schema v46, landed by polylogue-2qx.4); this PR only threads already-stored values through previously-lossy read paths and adds a new (Python-only) derivation branch.

Deferred (follow-up)

  • delegation_facts.result_status/result_is_error derive from a different signal (the Task tool's own returned artifact block outcome, i.e. blocks.tool_result_is_error on the delegation's result block — not the assistant turn's stop_reason) and are out of scope for this PR.
  • AC refactor: split CLI into command modules and add HTML preview output #4 (refusal/max_tokens queryable via the CLI/MCP query grammar, e.g. find "stop_reason:refusal") is not done: the field now reaches the domain Message object end-to-end, but wiring a new fielded predicate through the Lark grammar (archive/query/expression.py), the field-descriptor registry (archive/query/fields.py), SQL pushdown, and the runtime post-filter is a comparably-sized follow-up in its own right.
  • AC Conversation data is scattered across four providers with no unified archive path #5 (re-measure the percentages) needs a live-archive rebuild + rerun of the original sweep query, not something this PR's unit tests can produce.

Recommend filing a Beads follow-up for the deferred scope (query-grammar wiring for stop_reason, delegation_facts.result_status/result_is_error derivation, and the AC#5 re-measurement) — not filed from this worktree per its no-bd-writes constraint.

AC matrix (polylogue-cuxz.8)

  1. stop_reason persisted per assistant message — satisfied (was already partially done by polylogue-2qx.4 for the single-session path; this PR completes it for the bulk query path).
  2. terminal_state/result_status derive from persisted evidence or are deleted — partially satisfied: terminal_state (and its two view-derived siblings) now derive from stop_reason for the refusal/max_tokens cases; result_status/result_is_error untouched (deferred, different signal).
  3. 'unknown' ceases to be dominant — partially satisfied: reduces (does not eliminate) terminal_state unknowns; needs a live re-measurement to quantify.
  4. refusal/max_tokens queryable — deferred: reaches the domain model, not yet the query grammar.
  5. Re-measure percentages — deferred: needs a live archive rebuild, out of scope for a unit-tested PR.

Verification

  • devtools verify --quick (ruff format/check, mypy --strict, render all --check) — exit 0, both pre-commit and pre-push hook runs.
  • devtools test tests/unit/core/test_semantic_facts.py tests/unit/storage/test_session_insight_profiles.py tests/unit/storage/test_delegations_view.py tests/unit/storage/test_stop_reason_queryable.py tests/unit/storage/test_title_source_queryable.py tests/unit/cli/test_archive_query.py tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_models.py tests/unit/insights/test_delegation_work_evidence.py tests/unit/storage/test_session_insight_refresh.py — 419 passed.
  • Anti-vacuity: manually reverted the stop_reason=message.stop_reason line in archive_execution.py::_message_to_domain and confirmed test_session_filter_query_path_exposes_stop_reason fails (assert None == 'max_tokens') — the production mutation this test exercises is exactly that line — then restored it and reconfirmed green.
  • Not run: devtools verify full testmon suite (testmon isn't seeded in this worktree; seeding requires a full baseline run out of scope for this change) and a live-archive rebuild/re-measurement (AC Conversation data is scattered across four providers with no unified archive path #5).

Ref polylogue-cuxz.8

Problem: polylogue-cuxz.8 found session_profiles.terminal_state 85% unknown,
with delegation_facts.parent_terminal_state/child_terminal_state (views over
it) 96%/56% unknown, while Claude's wire carries message.stop_reason on
608,608 assistant messages. A prior fix (polylogue-2qx.4) persisted
stop_reason to messages.stop_reason and threaded it through the single-
session repository.get() path, but flagged two gaps: the bulk query-
execution path still dropped it, and no consumer derived terminal_state from
it.

Solution:
- ArchiveMessageRow/ArchiveBlockRow (storage/sqlite/archive_tiers/write.py)
  gain stop_reason/tool_result_outcome_unknown_reason fields, threaded
  through all four read sites that construct them (the full-envelope read,
  the paged-window read, and their block/message SQL SELECTs).
- archive/query/archive_execution.py's _message_to_domain (the bulk
  find/`sessions where ...` query path behind SessionFilter.list(), the
  route the prior fix's gap analysis identified as missing) now copies
  stop_reason onto the domain Message and the companion unknown-reason onto
  block dicts.
- MessageSemanticFacts (archive/semantic/models.py) gains a stop_reason
  field, threaded from the domain Message in archive/semantic/facts.py, so
  archive/session/runtime.py::_terminal_state can see it.
- _terminal_state now consults the last assistant turn's stop_reason before
  falling back to "unknown": REFUSAL -> "refused", MAX_TOKENS -> "truncated"
  (both real evidence-carrying and previously invisible in any surface,
  70 and 17 cases per the bead's corpus scan). TOOL_USE/STOP_SEQUENCE are
  deliberately NOT claimed here -- TOOL_USE is already fully covered by the
  existing pending-tool/action-outcome structural checks, and STOP_SEQUENCE
  alone doesn't distinguish a clean stop from truncation the way MAX_TOKENS
  does. Because delegation_facts.parent_terminal_state/child_terminal_state
  are SQL views joining session_profiles.terminal_state (not independently
  guessed columns), this one change also improves those two columns for
  free.

Deferred (filed as follow-up, see PR body AC matrix): delegation_facts.
result_status/result_is_error derive from a different signal (the Task
tool's own returned artifact outcome, not the assistant turn's stop_reason)
and are out of scope here; stop_reason is not yet exposed as a queryable
field in the CLI/MCP query grammar (AC #4) -- only the domain Message object
carries it end-to-end so far.

Verification: devtools verify --quick (ruff format/check, mypy --strict,
render all --check) exit 0; devtools test tests/unit/core/test_semantic_facts.py
tests/unit/storage/test_session_insight_profiles.py
tests/unit/storage/test_delegations_view.py
tests/unit/storage/test_stop_reason_queryable.py
tests/unit/storage/test_title_source_queryable.py tests/unit/cli/test_archive_query.py
tests/unit/cli/test_query_exec_laws.py tests/unit/core/test_models.py
tests/unit/insights/test_delegation_work_evidence.py
tests/unit/storage/test_session_insight_refresh.py -- 419 passed. Anti-vacuity:
manually reverted both the archive_execution.py stop_reason= line and confirmed
test_session_filter_query_path_exposes_stop_reason fails without it
(assert None == 'max_tokens'), then restored.

Ref polylogue-cuxz.8

Co-Authored-By: Claude <[email protected]>
@coderabbitai

coderabbitai Bot commented Aug 2, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Sinity, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 51 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro Plus

Run ID: b5502ec5-f728-4298-b71c-29cd89cc3bd6

📥 Commits

Reviewing files that changed from the base of the PR and between 1059339 and e6469f7.

📒 Files selected for processing (7)
  • polylogue/archive/query/archive_execution.py
  • polylogue/archive/semantic/facts.py
  • polylogue/archive/semantic/models.py
  • polylogue/archive/session/runtime.py
  • polylogue/storage/sqlite/archive_tiers/write.py
  • tests/unit/core/test_semantic_facts.py
  • tests/unit/storage/test_stop_reason_queryable.py

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@Sinity
Sinity enabled auto-merge (squash) August 2, 2026 10:37
@Sinity
Sinity merged commit edb21f6 into master Aug 2, 2026
3 checks passed
@Sinity
Sinity deleted the feature/storage/thread-stop-reason-terminal-state branch August 2, 2026 10:38
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant