Skip to content

refactor(runtime): split sessions.rs by concern (H21.2) - #44

Merged
lg2m merged 3 commits into
mainfrom
refactor/h21-2-sessions-split
Sep 15, 2026
Merged

lg2m merged 3 commits into
mainfrom
refactor/h21-2-sessions-split

Conversation

@lg2m

@lg2m lg2m commented Sep 14, 2026

Copy link
Copy Markdown
Collaborator

H21.2: split sessions.rs by concern (mechanical)

Spec: docs/plans/speed-first-extensible-agent-harness.md § D9 (the "then moves into sessions/{…}.rs" paragraph) · Design ADR: ADR-0012 (already accepted; this PR is its filing, no new ADR)

The last non-structural Phase 6 slice. No behavior change. No PROTOCOL_VERSION, store schema, or descriptor bump. Based on e5892a8 (v0.1.0).

What changed

crates/qq-core/src/sessions.rs (34,608 lines: ~7.3k persistence body + ~27k tests) becomes:

File Lines Holds
sessions.rs 215 imports, module decls, public re-exports, the constants, a glob of each concern module
sessions/commands.rs 1,744 execute_command, child-run creation, steering, deletion, workspace bookkeeping
sessions/settlement.rs 1,032 settle_run + guard, queued/reserved/prepared finishers, panic and recovery settlement, owned-child cancellation
sessions/claim.rs 961 RunIdentity/ClaimedRun, reserve_next_run, prepared audit, context-occupancy basis
sessions/tool_calls.rs 913 tool-call rows, spills, grants, policy, denial, reviewer resolution, grant promotion
sessions/transcript.rs 687 load_model_context, pruned assembly, legacy replay, runtime notice, history search
sessions/snapshots.rs 541 workspace/session snapshots, summaries, accounting folds
sessions/streaming.rs 467 assistant message rows, chunks, persist_model_turn, activity, reasoning, truncation
sessions/compaction.rs 449 summary validation, auto-compaction start/reload, complete_compaction, instruction
sessions/codec.rs 296 column string forms, run limits/correlation JSON, PersistedContentBlock
sessions/events.rs 182 EventContext, append_event, replay/page readers
sessions/tests.rs 4,983 shared harness: scripted loaders/providers, fixtures, collectors
sessions/tests/*.rs (13) 22,159 the 292 tests by theme: accounting, approvals, budgets, commands, compaction, context_capacity, contract, delegation, feeds, migrations, runs, settlement, streaming

Module list is exactly D9's. ChildAdmission (added by the tool-layer work after D9 was written) went to commands with the other child-run types.

How it was done, and how "mechanical" was verified

The split was scripted, not hand-moved: a pass that cuts the file at top-level items (attributes and doc comments attach forward), maps each body item to a module by name and each test to a theme by position, and rewrites only visibility — pub(super) on moved items, their struct fields, and inherent methods. Then cargo fmt.

Verification: a token-multiset diff of old vs new (ignoring whitespace and pub(super)) differs only by the new mod/use lines, the module doc comments, and the mod tests { } braces. rustfmt reflowed ~25 signatures that the 4-space dedent brought under 100 columns; those are the only line-shape changes.

One naming decision: the delegation tests are tests::delegation, not tests::subagents, because a subagents theme module would shadow the sibling sessions::subagents those tests reference by path.

Design note

The concern modules import each other via use <module>::*; globs in sessions.rs. This is deliberate and called out in a comment there: the body was one file and its halves reference each other freely; the split is by concern for navigation, not a dependency layering. Introducing explicit imports between them would be a second, non-mechanical change and would fight the next behavioral edit.

How verified

  • cargo test --workspace — 1,401 passed / 4 ignored (identical to main); qq-core lib 556 before and after
  • fmt; clippy --workspace --all-targets --all-features -D warnings clean; cargo build --workspace

Measurements

None — no hot path touched. Line count is flat (34,608 → 34,649); D9's "~700 fewer lines" assumed fixture deduplication, which a mechanical commit doesn't do and this one doesn't claim.

Docs

  • architecture.md crate map: the qq-core entry now names the session modules and what each holds
  • Plan: status block (Now → H21.2, Last closed adds H19 53bca7d perf(provider): frame SSE bodies per chunk with one allocation per event (H19) #39, Next → H22.2), task index (H19 Done, H21 row), D9 as-built note, Phase 6 order
  • Ledger: H19 → Shipped, H21.2 → In review + receipt. Closes the H18 follow-up (persist_model_turn re-measure) as won't-do: carrying the loop's measurement across AssistantTurnCompleted adds a public-event field to save one O(blocks) fold.

Follow-ups

  • H22.2 (structural bundle) is the last Phase 6 slice.

Mechanical move of the 34.6k-line sessions.rs into ten concern modules
(claim, codec, commands, compaction, events, settlement, snapshots,
streaming, tool_calls, transcript) and a tests tree (shared harness in
tests.rs; 292 tests in thirteen theme modules). Every moved item became
pub(super) with its fields and inherent methods; nothing else in the
moved text changed, and rustfmt reflowed only what the visibility prefix
and the dedent required. sessions.rs keeps the constants, the module
declarations, the public re-exports, and a glob of every concern module
so the halves import each other as before.

Slice: H21.2
@lg2m
lg2m merged commit f905d68 into main Sep 15, 2026
4 checks passed
@lg2m
lg2m deleted the refactor/h21-2-sessions-split branch September 15, 2026 16:19
lg2m added a commit that referenced this pull request Sep 16, 2026
…h fixes across eight crates (#46)

* refactor(server): route commands from one protocol table (H22.2)

SessionCommandKind::route() and COMMAND_ROUTES in qq-protocol are the one
source for the thirteen command paths. The server registers its handlers
from the table and checks the decoded kind against the route's; the client
posts to kind.route(). command_routes_match_the_protocol_table drives every
kind through its own route and its neighbour's, so a route added to one
side without the other fails in the test. decode_bounded replaces the four
copies of the permit + body-limit + strict-decode preamble.

Slice: H22.2

* refactor(protocol): box event summaries, one hash newtype macro, shared body limits (H22.2)

The eight SessionEvent variants that carry a SessionSummary box it: the
enum drops 536 -> 328 bytes with no wire change (Box is serde-transparent;
the wire and headless goldens are unchanged). A size test pins both facts.
InstructionHash and ContentHash come from one sha256_identity! macro
instead of two identical 70-line impl blocks. The client's per-route
response bounds move to qq_protocol::limits so the server bounds what it
emits by the same constants instead of a private copy.

Slice: H22.2

* perf(cli): plan cache hits borrow the key and re-stat sources without allocating (H22.2)

PlanCache::load takes &PlanKey: a hit clones nothing, and the key (two
PathBufs and an optional inline config document) is copied only into the
in-flight guard list and a new slot. SourceFingerprint::is_current observes
the path in place instead of building a whole fingerprint with a cloned
PathBuf per source per lookup.

Slice: H22.2

* perf(provider): size the request body buffer, share headers, enum authorizer (H22.2)

sse_exchange encodes into a Vec sized from ModelRequest::wire_size_hint (the
payload bytes the codecs embed verbatim plus fixed framing) instead of
letting reqwest's .json() double from empty: request heap peak drops from
1.55-1.80x to 1.39-1.60x the payload on provider_encode (five interleaved
pairs, encode time flat). Adapters hold Arc<HeaderMap> so an attempt clones
the map once, not twice. RequestAuthorizer is an enum of the one mechanism
that applies; an attempt whose authorizer adds no secret shares the static
redaction list, which HttpExchange::new now normalizes once. The Bedrock
event size check counts the text, tool-input, id, and name bytes it will
keep instead of Debug-formatting the SDK event.

Slice: H22.2

* perf(runtime): keep blocking catalog capture off the executor; one bounded read; slim tool-result retention (H22.2)

- The direct run path captured every host's blocking catalog on the async
  task before spawn_blocking; the capture now runs inside it.
- The embedded-host, shell, and MCP call loops pin one deadline timer for
  the whole call instead of registering a fresh sleep_until on every poll
  tick or output chunk.
- The run loop retains a RetainedResult (bounded text, error flag, spill
  handle) per tool call and moves file states, display payload, and the
  spilled text into the finished event instead of cloning the whole output.
- workspace::read_bounded is the one size-then-take-then-check read behind
  instructions, guidance, personas, input attachments, and editable files.
- AgentPlanDescriptor::encode serializes once for both the digest and the
  persisted JSON (previously three serializations per compile).
- session_files eviction runs only when a new path pushes a session over
  MAX_SESSION_FILES; updates and under-bound sessions skip the ordered
  sub-select. Regression test pins the bound and the update case.

Slice: H22.2

* perf(config,auth): built-in presets once per process, memoized ancestor checks, shared read locks (H22.2)

qq-config: the seven built-in provider presets (each a filtered copy of the
model table) are built once behind a LazyLock and cloned per load instead
of rebuilt on every load. Probes memoizes the directories whose ancestors
it has already checked for symlinks, so candidates under one tree do not
re-stat their common prefix; a test shows a symlink below a verified prefix
is still rejected.

qq-auth: reads (resolve, epoch, status, list) take the lock file shared so
concurrent compiles do not serialize on each other; writers keep the
exclusive lock and every verification after the lock is unchanged. The data
directory chmod runs only when the verified mode differs from 0700.
resolve_with_epoch returns the secret and the epoch of the index it was
read from in one lock cycle, for callers that record both.

Slice: H22.2

* perf(tui): keep the tree index across streaming deltas; per-frame work only for visible rows (H22.2)

qq-client: SessionStore::body_mut is mutable access that leaves the derived
tree index alone; every streaming reducer (text, reasoning, tool output,
activity, run stats, message lookup) uses it, so the sidebar order is not
rebuilt on every frame while a run streams. get_mut still drops the index
for summary changes. Tool-call timings are evicted with the calls they
describe. Regression test pins that deltas keep the same index allocation
and a summary change still rebuilds it.

qq-tui: the sidebar plan asks has_status_line (no allocation) for every
session and builds the status text only for rows inside the window. The
transcript keeps the unsettled tail collected by refresh_live so live_lines
in the same frame lays it out instead of collecting it again. Default
command chords are parsed once behind a LazyLock instead of per keypress.
expanded_tool_calls is bounded at 256, dropping expansions for calls no
session retains first.

Slice: H22.2

* docs(h22.2): record the structural bundle; close H21.2 (#44)

Slice: H22.2

* docs(ledger): link H22.2 bundle PR #46
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