Skip to content

Schema retrieval embeds only the current message, missing 38% of follow-ups - #1821

Merged
malibio merged 3 commits into
mainfrom
issue-1810-schema-context-blend
Jul 30, 2026
Merged

malibio merged 3 commits into
mainfrom
issue-1810-schema-context-blend

Conversation

@malibio

@malibio malibio commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator

Closes #1810

#1810)

Schema retrieval embedded the current user message alone, so a follow-up
that named its subject only by pronoun or ellipsis ("Set the Redwood one
to rejected", "Which ones are still out?") carried no lexical signal for
its target type and retrieved nothing. Because agent guidance tells the
model that a type absent from the RELEVANT ENTITY TYPES block does not
exist, a miss actively invited a duplicate schema rather than degrading
gracefully.

Add build_retrieval_query in context_ops, which prepends the last two
conversational turns to the current message, and use it at the ai-chat
turn call site. Measured recall over multi-turn conversations goes from
77% to 100%, with topic-switch recall holding at 100%.

Raw text is concatenated verbatim — summarizing or entity-extracting the
turns first was measured and made recall worse (100% -> 73%), since the
abstraction discards the surface words the embedder matches on. Only
user/assistant turns are blended; the synthetic completed-writes records
are boilerplate that would dilute the query.

This changes the embedding input only. The rendered prompt block is built
from the retrieved schemas, so emitted prompt tokens are unchanged.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01C2fwCrhS3Bfq4uDGM61iCr
@malibio

malibio commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1821

Review Type: Initial Review
Scope: df63e2b7 only (2 files, +150/−1). origin/main has advanced by two unrelated commits; those are excluded.


Summary

This is a tight, well-reasoned change that does exactly what the issue asked and no more. The core helper is pure, total (no panics, no unwraps), and correctly ordered; the doc comments record why the constant is 2 and why extraction was rejected, which is precisely the kind of comment that earns its keep. The negative result from the extraction experiment is captured in prose so the next person doesn't re-run it. Token neutrality holds under tracing. Test coverage of the pure helper is genuinely good — the assertions test the property the recall gain rests on, not string equality theater.

Two things keep this from being a clean pass without comment: the call-site wiring (the half that can actually regress silently) is untested, and blending removes the only implicit bound on query length feeding an untruncated embedding path. Neither is a merge blocker on its own; both are cheap to address.

Net assessment: clear improvement to code health. Recommend merge after considering the 🟡 items.


Requirements Check

Acceptance criterion Status Evidence
Retrieval query concatenates last 2 turns with current message ✅ build_retrieval_query (context_ops.rs:87-102), BLENDED_HISTORY_TURNS = 2; verified oldest-first by retrieval_query_blends_turns_oldest_first.
Raw text only — no summarization/extraction/rewriting ✅ Only trim() + join("\n"). No NLP call on the path. Doc comment records the measured 100%→73% regression that motivates this.
Emitted prompt tokens unchanged ✅ Traced: retrieval_query → build_workspace_context(query) → semantic_search_nodes_of_type (embedding input only). The prompt receives ctx_str = format_for_prompt(4000), built from retrieved SchemaNodes. The query string never reaches format_for_prompt, and dynamic_context (agent_loop.rs:424) is fed the formatted block, not the query.
Tests cover pronoun follow-up, ellipsis follow-up, topic switch (no regression) ✅ retrieval_query_keeps_discriminating_words_for_pronoun_reference, ..._for_ellipsis, retrieval_query_preserves_topic_switch. All 14 context_ops tests pass locally.
No lint suppression / #[allow] / #[deprecated] / compat shims ✅ None present in the diff.
No issue numbers in code comments or docs ✅ Verified by grep across the diff — the only #1810 is in the commit subject, which is permitted GitHub mechanics. Doc comments cite measured percentages, not tickets.
No new docs added to this repo ✅ No .md files touched.

Code Review Findings

🟡 Important

1. The call-site wiring is untested — and it's the half that can regress silently
📁 packages/daemon/src/services/local_agent_service.rs:440-448

The pure helper has 8 tests. The daemon wiring — building prior_turns, applying the role filter, and passing the result rather than user_message — has zero. grep for retrieval_query|prior_turns|build_retrieval in that file returns only the four production lines; nothing in its mod tests.

This matters more than typical untested glue because the failure mode is invisible. If someone later reverts Some(&retrieval_query) to Some(&user_message) during a refactor, or the role filter drifts to include Role::System, every test still passes, clippy stays clean, and the pre-push gate stays green. The only signal is a recall number nobody measures on every commit. The measured 77%→100% win silently evaporates.

The file already has the machinery — test_service() builds a real LocalAgentServiceImpl over a temp SqliteStore, and load_node_history composes the loaders. A test that seeds an ai-chat node with a user turn, an assistant turn with completed_writes, and a follow-up user turn, then asserts the string handed to retrieval contains the first turn's words and not the completed-writes boilerplate, would pin both the wiring and the filter. That likely requires extracting the prior_turns construction into a small named function (e.g. blended_turns(&prior_history)) so it's callable from a test without standing up inference — a worthwhile seam in its own right.

Principle: test at the seam where the behavior lives. A pure function tested in isolation proves the algorithm; it proves nothing about whether the algorithm is reachable. Untested wiring around well-tested logic is where regressions hide.

2. Blending removes the only implicit bound on embedding-query length
📁 packages/core/src/ops/context_ops.rs:87-102

build_retrieval_query concatenates prior turns verbatim with no length cap. The consumer chain has no cap either: semantic_search_nodes_of_type (embedding_service.rs:952) passes the query straight to generate_embedding → embed_document, and generate_embedding_llama (embedding.rs:595) tokenizes the whole thing with no truncation. The chunking logic that bounds stored content at MAX_TOKENS_PER_CHUNK = 512 (models/embedding.rs:26) applies to indexing only — query embeddings bypass it entirely.

Before this change the query was one user message, which is short by construction. Now it's up to three messages, and one of them is an assistant turn — model output, which can be long-form prose, a pasted list, or a code block. Two concrete consequences:

  • Context thrash. get_or_create_context (embedding.rs:304-312) recreates the LlamaContext whenever required_batch_size > current_batch_size, with n_batch = n_ubatch = required_batch_size. A single long assistant turn permanently inflates current_batch_size for the process, and the recreation itself is a model-context allocation on the inference hot path. This is a latency spike, not a crash, but it fires at exactly the worst moment.
  • Semantic dilution. A 2000-token assistant turn will dominate the mean-pooled embedding over a 10-token follow-up, which is the opposite of the intended effect. The doc comment asserts "the latest message still dominates the embedding" — that holds for the short conversational turns the experiment measured, but it is not a property of the code, and nothing enforces it.

A per-turn character budget (e.g. take the trailing ~400 chars of each prior turn, which is where the referent of a pronoun almost always lives) would preserve the measured win, bound the input, and make the doc comment's dominance claim structurally true rather than incidentally true. Cheap to add inside the existing helper, and unit-testable.

Principle: don't let an unbounded input reach a resource-proportional operation. The measured experiment used well-behaved conversational turns; production will eventually supply a pathological one.

🟢 Suggestions

3. BLENDED_HISTORY_TURNS = 2 counts messages, not exchanges — worth naming explicitly
📁 packages/core/src/ops/context_ops.rs:63-70

Because node_history_from_messages emits one ChatMessage per persisted message, two "turns" in a normal conversation is (previous user message, previous assistant reply) — i.e. exactly one prior exchange, and the assistant half is model prose rather than user intent. The constant's doc says "the last two turns," which a reader will plausibly interpret as two user turns / two exchanges.

This is not a bug — it's what was measured, and the measurement is the authority. But the ambiguity will cost the next person a debugging session when they tune the constant expecting exchange granularity and get message granularity. One clarifying sentence ("two messages, i.e. typically the previous user/assistant pair, not two exchanges") removes the trap.

Principle: constants that were tuned empirically should document the unit they were tuned in.

4. Consider whether assistant turns earn their slot
📁 packages/daemon/src/services/local_agent_service.rs:441-443

Following on from #3: with a budget of 2 messages, the assistant reply consumes half of it. In the PR's own test fixtures the assistant turns are "Added the Redwood Summit proposal." and "Created the invoice type." — they echo the user's vocabulary and contribute little the user turn didn't already supply, while being the turn most likely to be long (see #2).

Filtering to Role::User only, with BLENDED_HISTORY_TURNS = 2 then meaning two prior user turns, is plausibly strictly better: more discriminating user vocabulary, tighter length bound, no model-prose noise. I'm explicitly not asking for this change — the current arm is what was measured at 100%, and swapping it unmeasured would be trading a known result for a guess. Flagging it as the obvious next experiment if retrieval is revisited.

Principle: prefer the measured configuration; record the untested alternative rather than silently adopting it.

5. The role filter is correct and complete — verified, no action needed
📁 packages/daemon/src/services/local_agent_service.rs:441-443

Recording the verification since it was called out for scrutiny. node_history_from_messages (local_agent_service.rs:1583-1602) maps persisted roles through a match that emits only Role::User and Role::Assistant, returning Vec::new() for anything else, then optionally appends completed_writes_message, which is hardcoded Role::System. So prior_history contains exactly those three roles, and Role::Tool cannot appear (tool calls are never persisted — documented at local_agent_service.rs:1526-1531). Filtering to User | Assistant therefore excludes precisely the synthetic boilerplate and nothing else. The matches! form also fails closed: a future Role variant is excluded by default rather than silently blended. Good.

6. Empty-query degradation is safe — verified, no action needed
📁 packages/core/src/ops/context_ops.rs:100-101, :142

build_retrieval_query returns "" when everything is blank. build_workspace_context guards with query.filter(|q| !q.trim().is_empty()) at line 142, so the match falls to _ => vec![] and yields schema-free context rather than embedding a blank string. Defense in depth holds even if that guard were removed: semantic_search_nodes_of_type rejects empty queries with an error (embedding_service.rs:946-950), and the caller's Err arm logs and returns vec![]. Three independent layers, all degrading gracefully. Confirmed by retrieval_query_trims_and_tolerates_empty_current_message.

7. &[&str] at the crate seam is the right call
📁 packages/core/src/ops/context_ops.rs:87

Keeping nodespace-core free of ChatMessage (which lives behind the optional nlp feature) and doing the ChatMessage → &str projection in the daemon is correct layering — the pure helper stays trivially testable with string literals, which is visibly why the tests read as well as they do. The Vec<&str> allocation is one small vec of borrowed pointers per turn, on a path that is about to perform model inference costing four to six orders of magnitude more; optimizing it would be misplaced. impl Iterator would buy nothing here and would make the call site noisier.

Nit: pub fn build_retrieval_query is exported from nodespace-core but has exactly one consumer. That's fine — it's the natural home for the logic and the seam is what makes it testable — just worth not growing a general-purpose API around it speculatively (YAGNI).

8. Test assertions are meaningful, not tautological
📁 packages/core/src/ops/context_ops.rs:377-464

Worth calling out positively. The three scenario tests assert on discriminating vocabulary survival ("conference proposal", "invoices"), which is the actual mechanism behind the recall gain, rather than on exact output strings. The topic-switch test asserts ends_with, pinning recency ordering — the property that makes the no-regression claim hold. The comment block above the tests explains what property is being defended and why. The exact-equality tests (blends_turns_oldest_first, uses_only_the_last_two_turns) are appropriately placed on the mechanical properties where exact output is the contract. This is how scenario tests should be written.


Recommendation

COMMENT — approve-with-comments in spirit.

The change is correct, minimal, well-documented, faithful to the measured result, and a clear net improvement. Nothing here is a blocker. My one substantive ask before merge is finding #1 (a test pinning the call-site wiring), because the regression it guards against is completely silent and the file already has the fixtures to make it cheap. Finding #2 (per-turn length cap) is a real robustness gap I'd want tracked as follow-up even if not fixed here.

Automated review — posted as a comment, not a formal approval.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pragmatic Code Review (initial) posted as a PR comment: #1821 (comment)

Recommendation: COMMENT — approve-with-comments in spirit. All 4 acceptance criteria verified ✅, no standards violations, no blockers. Two items worth addressing: (1) the daemon call-site wiring is untested and its regression mode is silent; (2) blending removes the only implicit bound on embedding-query length on an untruncated path.

…ests

Cap each blended prior turn at 400 chars (trailing, char-boundary safe).
Blending had removed the only implicit bound on the embedding query: it
was one short user message before, and is now up to three messages, one
of which is model output with no natural length bound. The query path
applies no truncation of its own — semantic_search_nodes_of_type hands
the string straight to generate_embedding, and the 512-token chunking
bounds stored content only — so a long assistant turn would both dominate
the mean-pooled embedding and permanently enlarge the embedding context's
batch size via get_or_create_context. The current message is never
truncated. Trailing chars are kept because a referent introduced mid-turn
sits nearest the end.

Extract schema_retrieval_query so the role filter is reachable from a
test, and cover it by driving real AiChatMessages through
node_history_from_messages: the earlier turn's discriminating words reach
the query and the synthetic completed-writes boilerplate does not. The
test asserts the System message is present in the fixture first, so it
fails rather than passes vacuously if that record stops being emitted —
verified by mutation (disabling the filter fails the test).

The call site itself still is not unit-pinned: reaching that line needs
live inference, so mutating it to embed user_message directly does not
fail these tests. Rather than carve a test-only seam into model
selection, the risk is called out at the call site and in the test doc,
with the ADR-048 seam test covering it end to end.

Also clarify BLENDED_HISTORY_TURNS counts messages, not exchanges.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01C2fwCrhS3Bfq4uDGM61iCr
@malibio

malibio commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

Review addressed — 2443bfe1

🟡 #2 — Unbounded embedding-query length: fixed

Verified both claims before acting: semantic_search_nodes_of_type (embedding_service.rs:953) passes the query straight to generate_embedding with no truncation, and get_or_create_context (embedding.rs:308-312) grows current_batch_size monotonically. The 512-token chunking bounds stored content only.

Each blended prior turn is now capped at MAX_CHARS_PER_BLENDED_TURN = 400, taking trailing characters (a referent introduced mid-turn sits nearest the end). The current message is never truncated. Truncation is char-boundary safe via char_indices().nth_back() — slicing "é".repeat(1000) on a byte index would panic, so there is a test for exactly that.

4 new tests: cap applies to prior turns but not the current message; the end of a long turn survives; char boundaries respected; short turns untouched.

🟡 #1 — Untested call-site wiring: partially fixed, with an honest caveat

Extracted schema_retrieval_query(&[ChatMessage], &str) so the role filter is reachable, and covered it by driving real AiChatMessages through node_history_from_messages rather than hand-built ChatMessages. The test asserts the synthetic Role::System record is in the fixture before asserting it is absent from the query, so it fails rather than passes vacuously if that record stops being emitted.

I mutation-tested this: disabling the role filter (.filter(|_m| true)) fails the test. ✅

But it does not fully close the finding, and I want to be straight about that. I also mutated the call site to let retrieval_query = user_message.clone(); — and the tests still passed. Reaching that line requires live inference, so a unit test cannot observe it without mocking the engine — precisely the test-only seam into model selection that this file's own header argues against. Rather than carve that seam, the risk is now called out at the call site and in the test's doc comment, with the ADR-048 seam test covering it end to end.

If you'd rather I build the mock and pin it hard, say so and I'll do it — I judged the seam to cost more than it buys, but that's a judgement call worth your veto.

🟢 #3 — BLENDED_HISTORY_TURNS granularity: fixed

Doc now states it counts messages, not exchanges (two ≈ one prior round trip).

🟢 #4 — Drop assistant turns from the blend: not done, deliberately

Agreed it's plausibly better, but the current arm is what measured 100%. Changing it unmeasured would trade a verified result for an untested hypothesis. Worth a follow-up experiment.

🟢 #5–#8

No action needed — these confirmed existing behaviour.


Verification: test:all green — frontend 171 files / 4112 tests (identical to pre-change baseline), 20 browser, 1621 Rust (up from 1615: 6 new tests), 0 failures. cargo clippy -p nodespace-core -p nodespace-daemon --all-targets clean. Full pre-push gate passed, including the ADR-048 ai_chat_send_to_idle_test against a daemon built from this branch.

🤖 Generated with Claude Code

@malibio

malibio commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1821 (Re-Review)

Review Type: Re-Review
Scope: 2443bfe1 only (git diff df63e2b7..2443bfe1, 2 files, +178/−18). The base commit df63e2b7 was reviewed previously and is not re-litigated except where this commit changes it.


Previous Review Summary

# Finding Claimed Verified
🟡 #1 Call-site wiring untested Partially fixed, caveat documented ✅ Accurate — partial, and honestly labelled
🟡 #2 Unbounded embedding-query length Fixed via 400-char cap ✅ Fixed for prior turns (see #10)
🟢 #3 BLENDED_HISTORY_TURNS granularity Doc wording fixed ✅ Confirmed
🟢 #4 Drop assistant turns Declined deliberately ✅ Correct call

4 prior recommendations: 2 fully addressed, 1 partially addressed (with an accurate caveat), 1 knowingly declined on sound grounds. 2 new minor findings, neither blocking.

I re-derived every claim rather than taking the response at face value: I extracted trailing_chars into a standalone crate and exhaustively enumerated its edge cases, replayed the daemon test fixture through a faithful reimplementation of build_retrieval_query, ran the role-filter mutation myself, and diffed the old call site against the extracted function token by token.


Verification of the Claims

trailing_chars is correct. I ran it over the full edge-case matrix rather than reasoning about it:

Input max_chars Returns
"" 3 "" — no panic
"ab" 3 "ab" — under cap, untouched
"abc" 3 "abc" — exactly at cap, untouched
"abcd" 3 "bcd" — trailing, exact
"abcde" 3 "cde" — trailing, exact
"éàüñz" 3 "üñz" — 3 chars, no byte-boundary panic
"🙂🙂🙂🙂" 2 "🙂🙂" — 4-byte chars handled
"x".repeat(5000) 400 400 chars

No off-by-one at the cap boundary (len == cap and len == cap+1 both behave), no panic on multi-byte, no panic on empty. nth_back(n) counts back n+1 elements, so nth_back(max-1) correctly lands on the max-th-from-last char. The core logic is right.

Cap ordering is right. Verified trim() → filter(non-empty) → take(2) → trailing_chars in that order. This matters in two ways the response didn't spell out: trimming before capping means padding never consumes budget, and filtering before take means blank turns don't burn a history slot. Confirmed ["oldest", "", " ", "middle", "newest"] yields "middle\nnewest\ncur" — the blanks are skipped, not counted.

Worst-case bound is real. Two prior turns contribute at most 800 chars (3203 bytes with 4-byte emoji). Previously unbounded.

The refactor is behavior-preserving. schema_retrieval_query is a verbatim lift of the four lines from df63e2b7 — same matches!(m.role, Role::User | Role::Assistant) filter, same map, same call. No semantic drift.

The role-filter mutation genuinely fails. I replayed the daemon fixture with the filter disabled. The query becomes "Added the Redwood Summit proposal.\nRecord of graph writes already completed…\nSet the Redwood one to rejected" — which fails both assertions: contains("conference proposal") → false (the user turn is pushed out of the 2-message window by the system record) and !contains("Record of graph writes") → false. Two independent assertions catch it. This is a real guard.

The vacuity guard is sufficient. assert!(history.iter().any(|m| m.role == Role::System)) runs before the negative assertion, so if completed_writes_message ever stops emitting, the test fails loudly instead of passing for the wrong reason. This is exactly the right construction for a "must not contain X" assertion, and it is the detail most such tests get wrong.

Standards clean. No #[allow], no #[deprecated], no lint suppression, no issue numbers in the new comments (ADR-048 is an ADR reference, which is the sanctioned form), no .md files touched, no console.*. The only expect() calls are in test code. cargo test -p nodespace-core --lib context_ops → 18 passed.


Findings

🟢 Minor / Optional

9. trailing_chars: the start > 0 guard is provably dead code
📁 packages/core/src/ops/context_ops.rs:90-95

Some((start, _)) if start > 0 => &text[start..],
_ => text,

I differentially tested the guarded version against an unguarded one across ["", "a", "ab", "abc", "abcd", "éab", "🙂x", " "] × max_chars ∈ 0..6. They never differ.

The reason is structural: start == 0 occurs only when nth_back(max-1) lands on the first char, which happens exactly when text has precisely max_chars chars — and in that case &text[0..] == text, so both arms return the same thing. The guard cannot change the result for any input.

It isn't wrong, and a reader may find it reassuring, but it reads as defending against something, which invites a future reader to hunt for the case it handles. Either drop it (Some((start, _)) => &text[start..]) or, if kept, say what it's for — my read is that it's redundant with Some(..) and the plain form is clearer.

Principle: a guard that cannot change behavior is documentation pretending to be logic. Dead conditionals cost future readers more than they save.

10. max_chars = 0 returns one character, not zero
📁 packages/core/src/ops/context_ops.rs:90-95

trailing_chars("hello", 0) returns "o". saturating_sub(1) maps 0 → 0, and nth_back(0) is the last element, so a zero budget yields one char rather than none.

This is unreachable today — the sole caller passes the constant 400. It is not a bug in the shipped path, and I am not asking for a fix. But the function is a private free function with a general-looking signature (fn trailing_chars(text: &str, max_chars: usize) -> &str) and a doc comment that reads as a general contract ("Last max_chars characters of text"). The next caller who passes a computed budget that can reach zero gets a silent off-by-one.

Cheapest fix is one line in the doc comment: note that max_chars is assumed ≥ 1. A debug_assert!(max_chars > 0) would also do. Not worth an if max_chars == 0 { return "" } branch on a hot path for a case that cannot occur.

Principle: a helper's doc comment is its contract. If the contract has a precondition, state it — the compiler won't.


Assessment of the Judgement Calls

#1 — the partial fix is defensible; I would not build the mock. The response is right that fully pinning the call site requires mocking the inference engine, and it's right that this file's own header argues against that seam. But the stronger argument is one the response undersold: the extraction itself is the durable win. The role filter and blend logic — the parts with real conditional behavior, and the parts a refactor is most likely to get subtly wrong — are now behind a named, tested function. What remains unpinned is a single argument at one call site, and it now carries an explicit comment naming the exact regression ("passing the bare message here is the regression this call site exists to avoid"). That is a good trade: high-value logic hard-pinned, low-complexity glue guarded by a comment plus the ADR-048 end-to-end seam test.

Building an engine mock to pin one argument would add a test-only abstraction over model selection to buy coverage of a line with no branching. That is the kind of test that makes future refactors harder while catching nothing the E2E test misses. Declining was correct, and flagging the limitation openly rather than quietly claiming the finding closed is the right professional behavior — that transparency is worth more than the coverage would have been.

#4 — declining to drop assistant turns remains correct. Trading a measured 100% for an unmeasured hypothesis is exactly the wrong direction. Right call, unchanged from my prior review.

Is 400 chars defensible? Yes, and the trailing-not-leading choice is the load-bearing detail. The concern worth taking seriously is that truncation could cut the discriminating vocabulary the whole feature depends on. It doesn't, for a specific reason: keeping the trailing chars aligns with where referents actually live. In "…filler… the Redwood Summit proposal" the entity survives precisely because it sits near the end, adjacent to the follow-up. Keeping the leading 400 would have been the wrong choice and would have quietly degraded the feature.

On mid-word truncation: the cap can split a word (my replay of the long-turn test starts the kept span mid-token). Word-boundary-aware truncation would be tidier, but I don't think it's worth adding here. The embedder tokenizes sub-word anyway, so a split token degrades into subword pieces rather than producing garbage; the effect is one noisy token at the start of a 400-char span, furthest from the current message that dominates the pooled embedding. Adding a split_whitespace scan would be added complexity for an effect below the measurement noise floor. YAGNI applies — leave it.

Where 400 could genuinely bite is a turn that is one long unbroken entity list where the referent sits early. That's a real but narrow case, the cap is a named constant that is trivially tunable, and the alternative (unbounded) has the worse failure mode. Correct trade.

One thing the cap does not close, worth stating plainly so it isn't mistaken for fixed: the current message is still unbounded, and it flows to the same untruncated embedding path. So the get_or_create_context batch-growth concern from prior finding #2 is reduced, not eliminated — a single 50,000-char user paste still inflates current_batch_size for the life of the process. I verified this is pre-existing (user_message reached retrieval unbounded before this PR too), so it is explicitly not a regression from this change and not this PR's job to fix. The commit correctly bounded the exposure it introduced and correctly left the current message alone. Flagging only so it isn't assumed handled.


Test Quality

Meaningful, not theater. Six new tests, each pinning a distinct property:

  • caps_each_prior_turn_but_never_the_current_message — asserts both halves of the contract in one test, including the negative (current message untruncated at 5,000 chars). Good.
  • keeps_the_end_of_a_long_prior_turn — pins the trailing-vs-leading decision, which is the design choice most likely to be silently inverted by a well-meaning refactor. This is the highest-value test of the six.
  • truncation_respects_char_boundaries — "é".repeat(1000) would panic on a naive byte slice. Tests a real failure mode with the input that produces it.
  • leaves_short_turns_untouched — asserts the precondition (short.chars().count() < MAX_CHARS_PER_BLENDED_TURN) before the behavior, so it can't rot into vacuity if the constant changes. Nice detail.
  • retrieval_query_blends_history_and_excludes_completed_writes — genuinely guards what it claims (mutation-verified above), with a correctly-ordered vacuity guard.
  • retrieval_query_for_first_turn_is_the_message_alone — pins the no-regression claim for first turns as byte-identical to pre-blend behavior.

Driving real AiChatMessages through node_history_from_messages instead of hand-building ChatMessages is the right call — it pins the query builder against the real history shape, so a change to how completed-writes are interleaved surfaces here rather than in production.

Nit: both new daemon tests are #[tokio::test] but neither awaits anything. #[test] would do. Harmless — likely copied from the surrounding async tests — and not worth a commit on its own.


Recommendation

APPROVE.

Both 🟡 findings from the prior review are addressed as well as they reasonably can be: #2 is genuinely fixed for the exposure this PR introduced, with correct logic I verified exhaustively rather than by inspection; #1 is addressed at the layer where it pays (the logic is now extracted and hard-pinned, mutation-verified) with the residual gap named honestly instead of papered over. The two new findings are cosmetic — a dead guard clause and an undocumented precondition on an unreachable input — and neither justifies another round trip.

The change is a clear net improvement to code health: it is more robust than the base commit, better tested, better documented, and behavior-preserving where it refactors. Ship it.

Automated review.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pragmatic Code Review — PR #1821 (Re-Review)

Review Type: Re-Review
Scope: 2443bfe1 only (git diff df63e2b7..2443bfe1, 2 files, +178/−18). The base commit df63e2b7 was reviewed previously and is not re-litigated except where this commit changes it.


Previous Review Summary

# Finding Claimed Verified
🟡 #1 Call-site wiring untested Partially fixed, caveat documented ✅ Accurate — partial, and honestly labelled
🟡 #2 Unbounded embedding-query length Fixed via 400-char cap ✅ Fixed for prior turns (see #10)
🟢 #3 BLENDED_HISTORY_TURNS granularity Doc wording fixed ✅ Confirmed
🟢 #4 Drop assistant turns Declined deliberately ✅ Correct call

4 prior recommendations: 2 fully addressed, 1 partially addressed (with an accurate caveat), 1 knowingly declined on sound grounds. 2 new minor findings, neither blocking.

I re-derived every claim rather than taking the response at face value: I extracted trailing_chars into a standalone crate and exhaustively enumerated its edge cases, replayed the daemon test fixture through a faithful reimplementation of build_retrieval_query, ran the role-filter mutation myself, and diffed the old call site against the extracted function token by token.


Verification of the Claims

trailing_chars is correct. I ran it over the full edge-case matrix rather than reasoning about it:

Input max_chars Returns
"" 3 "" — no panic
"ab" 3 "ab" — under cap, untouched
"abc" 3 "abc" — exactly at cap, untouched
"abcd" 3 "bcd" — trailing, exact
"abcde" 3 "cde" — trailing, exact
"éàüñz" 3 "üñz" — 3 chars, no byte-boundary panic
"🙂🙂🙂🙂" 2 "🙂🙂" — 4-byte chars handled
"x".repeat(5000) 400 400 chars

No off-by-one at the cap boundary (len == cap and len == cap+1 both behave), no panic on multi-byte, no panic on empty. nth_back(n) counts back n+1 elements, so nth_back(max-1) correctly lands on the max-th-from-last char. The core logic is right.

Cap ordering is right. Verified trim() → filter(non-empty) → take(2) → trailing_chars in that order. This matters in two ways the response didn't spell out: trimming before capping means padding never consumes budget, and filtering before take means blank turns don't burn a history slot. Confirmed ["oldest", "", " ", "middle", "newest"] yields "middle\nnewest\ncur" — the blanks are skipped, not counted.

Worst-case bound is real. Two prior turns contribute at most 800 chars (3203 bytes with 4-byte emoji). Previously unbounded.

The refactor is behavior-preserving. schema_retrieval_query is a verbatim lift of the four lines from df63e2b7 — same matches!(m.role, Role::User | Role::Assistant) filter, same map, same call. No semantic drift.

The role-filter mutation genuinely fails. I replayed the daemon fixture with the filter disabled. The query becomes "Added the Redwood Summit proposal.\nRecord of graph writes already completed…\nSet the Redwood one to rejected" — which fails both assertions: contains("conference proposal") → false (the user turn is pushed out of the 2-message window by the system record) and !contains("Record of graph writes") → false. Two independent assertions catch it. This is a real guard.

The vacuity guard is sufficient. assert!(history.iter().any(|m| m.role == Role::System)) runs before the negative assertion, so if completed_writes_message ever stops emitting, the test fails loudly instead of passing for the wrong reason. This is exactly the right construction for a "must not contain X" assertion, and it is the detail most such tests get wrong.

Standards clean. No #[allow], no #[deprecated], no lint suppression, no issue numbers in the new comments (ADR-048 is an ADR reference, which is the sanctioned form), no .md files touched, no console.*. The only expect() calls are in test code. cargo test -p nodespace-core --lib context_ops → 18 passed.


Findings

🟢 Minor / Optional

9. trailing_chars: the start > 0 guard is provably dead code
📁 packages/core/src/ops/context_ops.rs:90-95

Some((start, _)) if start > 0 => &text[start..],
_ => text,

I differentially tested the guarded version against an unguarded one across ["", "a", "ab", "abc", "abcd", "éab", "🙂x", " "] × max_chars ∈ 0..6. They never differ.

The reason is structural: start == 0 occurs only when nth_back(max-1) lands on the first char, which happens exactly when text has precisely max_chars chars — and in that case &text[0..] == text, so both arms return the same thing. The guard cannot change the result for any input.

It isn't wrong, and a reader may find it reassuring, but it reads as defending against something, which invites a future reader to hunt for the case it handles. Either drop it (Some((start, _)) => &text[start..]) or, if kept, say what it's for — my read is that it's redundant with Some(..) and the plain form is clearer.

Principle: a guard that cannot change behavior is documentation pretending to be logic. Dead conditionals cost future readers more than they save.

10. max_chars = 0 returns one character, not zero
📁 packages/core/src/ops/context_ops.rs:90-95

trailing_chars("hello", 0) returns "o". saturating_sub(1) maps 0 → 0, and nth_back(0) is the last element, so a zero budget yields one char rather than none.

This is unreachable today — the sole caller passes the constant 400. It is not a bug in the shipped path, and I am not asking for a fix. But the function is a private free function with a general-looking signature (fn trailing_chars(text: &str, max_chars: usize) -> &str) and a doc comment that reads as a general contract ("Last max_chars characters of text"). The next caller who passes a computed budget that can reach zero gets a silent off-by-one.

Cheapest fix is one line in the doc comment: note that max_chars is assumed ≥ 1. A debug_assert!(max_chars > 0) would also do. Not worth an if max_chars == 0 { return "" } branch on a hot path for a case that cannot occur.

Principle: a helper's doc comment is its contract. If the contract has a precondition, state it — the compiler won't.


Assessment of the Judgement Calls

#1 — the partial fix is defensible; I would not build the mock. The response is right that fully pinning the call site requires mocking the inference engine, and it's right that this file's own header argues against that seam. But the stronger argument is one the response undersold: the extraction itself is the durable win. The role filter and blend logic — the parts with real conditional behavior, and the parts a refactor is most likely to get subtly wrong — are now behind a named, tested function. What remains unpinned is a single argument at one call site, and it now carries an explicit comment naming the exact regression ("passing the bare message here is the regression this call site exists to avoid"). That is a good trade: high-value logic hard-pinned, low-complexity glue guarded by a comment plus the ADR-048 end-to-end seam test.

Building an engine mock to pin one argument would add a test-only abstraction over model selection to buy coverage of a line with no branching. That is the kind of test that makes future refactors harder while catching nothing the E2E test misses. Declining was correct, and flagging the limitation openly rather than quietly claiming the finding closed is the right professional behavior — that transparency is worth more than the coverage would have been.

#4 — declining to drop assistant turns remains correct. Trading a measured 100% for an unmeasured hypothesis is exactly the wrong direction. Right call, unchanged from my prior review.

Is 400 chars defensible? Yes, and the trailing-not-leading choice is the load-bearing detail. The concern worth taking seriously is that truncation could cut the discriminating vocabulary the whole feature depends on. It doesn't, for a specific reason: keeping the trailing chars aligns with where referents actually live. In "…filler… the Redwood Summit proposal" the entity survives precisely because it sits near the end, adjacent to the follow-up. Keeping the leading 400 would have been the wrong choice and would have quietly degraded the feature.

On mid-word truncation: the cap can split a word (my replay of the long-turn test starts the kept span mid-token). Word-boundary-aware truncation would be tidier, but I don't think it's worth adding here. The embedder tokenizes sub-word anyway, so a split token degrades into subword pieces rather than producing garbage; the effect is one noisy token at the start of a 400-char span, furthest from the current message that dominates the pooled embedding. Adding a split_whitespace scan would be added complexity for an effect below the measurement noise floor. YAGNI applies — leave it.

Where 400 could genuinely bite is a turn that is one long unbroken entity list where the referent sits early. That's a real but narrow case, the cap is a named constant that is trivially tunable, and the alternative (unbounded) has the worse failure mode. Correct trade.

One thing the cap does not close, worth stating plainly so it isn't mistaken for fixed: the current message is still unbounded, and it flows to the same untruncated embedding path. So the get_or_create_context batch-growth concern from prior finding #2 is reduced, not eliminated — a single 50,000-char user paste still inflates current_batch_size for the life of the process. I verified this is pre-existing (user_message reached retrieval unbounded before this PR too), so it is explicitly not a regression from this change and not this PR's job to fix. The commit correctly bounded the exposure it introduced and correctly left the current message alone. Flagging only so it isn't assumed handled.


Test Quality

Meaningful, not theater. Six new tests, each pinning a distinct property:

  • caps_each_prior_turn_but_never_the_current_message — asserts both halves of the contract in one test, including the negative (current message untruncated at 5,000 chars). Good.
  • keeps_the_end_of_a_long_prior_turn — pins the trailing-vs-leading decision, which is the design choice most likely to be silently inverted by a well-meaning refactor. This is the highest-value test of the six.
  • truncation_respects_char_boundaries — "é".repeat(1000) would panic on a naive byte slice. Tests a real failure mode with the input that produces it.
  • leaves_short_turns_untouched — asserts the precondition (short.chars().count() < MAX_CHARS_PER_BLENDED_TURN) before the behavior, so it can't rot into vacuity if the constant changes. Nice detail.
  • retrieval_query_blends_history_and_excludes_completed_writes — genuinely guards what it claims (mutation-verified above), with a correctly-ordered vacuity guard.
  • retrieval_query_for_first_turn_is_the_message_alone — pins the no-regression claim for first turns as byte-identical to pre-blend behavior.

Driving real AiChatMessages through node_history_from_messages instead of hand-building ChatMessages is the right call — it pins the query builder against the real history shape, so a change to how completed-writes are interleaved surfaces here rather than in production.

Nit: both new daemon tests are #[tokio::test] but neither awaits anything. #[test] would do. Harmless — likely copied from the surrounding async tests — and not worth a commit on its own.


Recommendation

APPROVE.

Both 🟡 findings from the prior review are addressed as well as they reasonably can be: #2 is genuinely fixed for the exposure this PR introduced, with correct logic I verified exhaustively rather than by inspection; #1 is addressed at the layer where it pays (the logic is now extracted and hard-pinned, mutation-verified) with the residual gap named honestly instead of papered over. The two new findings are cosmetic — a dead guard clause and an undocumented precondition on an unreachable input — and neither justifies another round trip.

The change is a clear net improvement to code health: it is more robust than the base commit, better tested, better documented, and behavior-preserving where it refactors. Ship it.

Automated review.

The `start > 0` arm could never change the result — when start is 0 the
slice `&text[0..]` is the input, which is what the fallthrough already
returned. Collapse to Some/None and note the max_chars >= 1 contract,
since 0 yields the final character rather than an empty string.

The two new daemon tests await nothing, so drop them to plain #[test].

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01C2fwCrhS3Bfq4uDGM61iCr
@malibio

malibio commented Jul 30, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review nits addressed — 096d0667

Both 🟢 findings from the re-review are fixed. Approve was already given; these were cheap enough to just do.

#9 — dead start > 0 guard: removed. Confirmed the analysis: when start == 0, &text[0..] is text, which is what the fallthrough already returned, so the arm could never change the result. Collapsed to Some/None.

#10 — max_chars = 0 contract: documented. saturating_sub(1) maps 0 → 0 and nth_back(0) is the last element, so a zero budget yields one character. Unreachable today (sole caller passes 400), but the signature looks general, so the doc now states the max_chars >= 1 expectation rather than pretending otherwise.

Nit — two daemon tests awaited nothing: dropped from #[tokio::test] to #[test].

Re-verified after the change that the role-filter mutation still fails the test (.filter(|_m| true) → retrieval_query_blends_history_and_excludes_completed_writes FAILED), so the guard removal didn't weaken coverage.

Verification: test:all green — 171 files / 4112 frontend (identical to baseline), 20 browser, 1621 Rust, 0 failures. Clippy clean. Full pre-push gate passed.

One note on the gate: it failed on the first two push attempts with unrelated timeouts under concurrent load from other agents on this machine, then passed cleanly once the machine was quiet — same load-sensitivity seen earlier with architecture-benchmarks.test.ts (25 ms threshold) and the ADR-048 inference test. No code change was involved in the difference.

🤖 Generated with Claude Code

@malibio
malibio merged commit f3c78eb into main Jul 30, 2026
2 checks passed
@malibio
malibio deleted the issue-1810-schema-context-blend branch July 30, 2026 15:11
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.

Schema retrieval embeds only the current message, missing 38% of follow-ups

1 participant