Skip to content

Fixture: agent-matrix scenarios 3->4->6 key on a value the chain never persists; trace doesn't record offered tools/routed skill - #1843

Merged
malibio merged 3 commits into
mainfrom
worktree-issue-1839-matrix-chain-trace
Jul 31, 2026
Merged

malibio merged 3 commits into
mainfrom
worktree-issue-1839-matrix-chain-trace

Conversation

@malibio

@malibio malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator

Closes #1839

malibio and others added 2 commits July 31, 2026 04:33
…ill per turn (#1839)

The eval's `toolsOffered` was empty on every scored turn because
scripts/aichat.ts scraped a daemon log line -- "scoped tool list" with
`selected_tools=` -- that has never existed in the codebase. The real line
("Agent turn: system prompt and tools prepared", carrying post-scoping
`tool_names`) was already being scraped under a second marker name that the
runner never parsed, so it died at the aichat/runner seam. One marker now, fed
by the line that exists.

The routed skill was genuinely unrecorded: the routing log carried only a
candidate count, with the names reachable solely as an OTel span attribute the
eval cannot see. `routed_skills` now names the candidates clearing the score
gate -- the ones actually rendered into Stage 2's prompt.

Scenario 3's prompt implied no cost field, yet scenarios 4, 6 and 7 all key on
a replacement cost, making 6 and 7 unwinnable and scoring a correct refusal as
a failure. Scenario 3 now implies the field. Keeping cost as scenario 6's
discriminator is deliberate: re-keying to the item name would make the referent
a direct string match that plain search_nodes resolves, and the resolve_query
assertion would pass while testing less.

Re-running then showed the gap had only moved. create_node persists a bare
shell -- content and type, none of the user's particulars -- so "the 2400 one"
is still unresolvable, and scenario 4 scored green throughout because
`toolOnce` counts the call and nothing else. create_node now reports
`property_count` on its result (folded into the existing `result_field_count`
log field, alongside create_schema's `fields`), and `minProperties` asserts on
it. Scenario 4 fails as a result: the eval goes 9/12 -> 8/12, reporting a break
it was previously hiding rather than a new regression. The underlying prose
bug is filed separately as #1841.

Both aichat.test.ts and runner.test.ts already fed `[tools offered]` through
their fixtures without ever asserting on it, which is how an always-empty field
reached committed traces unnoticed. Both now assert it.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
The scrape required a quoted value, but tracing quotes a string field only when
it must, and it does not here: the value arrives bare as
`routed_skills=Organization, Research & Search, Node Creation`. The pattern
matched nothing, so `routedSkills` came back empty on every scenario of a full
eval run — the same silent-empty state the dead `scoped tool list` scrape was
in, reintroduced by the fix for it.

Skill names contain both spaces and commas, so no delimiter short of the line
end is safe; agent_loop.rs emits this field last for that reason.

The unit tests passed throughout because their fixtures used the quoted form —
they asserted the scrape against a shape the daemon never produces. Fixtures
now carry verbatim daemon output, including a case with both separators, and
the scrape is verified against a real log rather than only against fixtures.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #1843

Review Type: Initial Review

Summary

A genuinely net-positive change that does the harder version of the job. The core insight — that the eval was scoring green on assertions structurally incapable of seeing what they claimed to check — is correct, and the fix pursues it to the honest conclusion (9/12 → 8/12) rather than preserving the headline number. The commit messages and code comments are unusually good: they explain why the shape is what it is, and commit 7a449cb4 documents its own predecessor's silent-empty bug rather than quietly amending it.

I verified the load-bearing claims rather than accepting them:

  • Confirmed by experiment. I built a standalone tracing-subscriber 0.3 reproduction to check the quoting claim. record_str → record_debug → write!("{:?}"), and the % sigil wraps the value in format_args!, whose Debug impl is transparent. Both fields emit unquoted:
    ... tool_names=create_node, search_nodes system_prompt_len=1234 stage2_candidates_injected=true
    ... candidates=3 routed_skills=Organization, Research & Search, Node Creation
    
    So the diagnosis in 7a449cb4 is exactly right — and it has an unremarked corollary (finding 2 below).
  • Confirmed the dead scrape. selected_tools / scoped tool list appear nowhere in the Rust tree. scripts/results-e4b.trace.jsonl (committed at 905c5fc3) has toolsOffered: "" on every turn, which matches.
  • Confirmed clears_score_gate is the right predicate. render_candidates_for_prompt (routing.rs:247) and stage2_tools (routing.rs:335) both filter on it, so routed_skills names precisely the set that reached Stage 2's prompt and scoped its tool surface. This is the semantically correct choice over candidates or top-K.
  • Confirmed the extra shape change is safe. compareToBaseline joins on id and reads only passed/failure; extra is serialized to JSON and never rendered by a consumer that would break on array-vs-string.
  • bun run test:scripts → 74 pass / 0 fail. cargo clippy -p nodespace-agent --all-targets -- -D warnings → clean.

Standards check: no lint suppression added, no #[allow(dead_code)], no #[deprecated], no new .md files, no issue numbers in code comments or doc content (the #1841 reference lives in the commit message, which is correct — that's GitHub process mechanics, not documentation content). The console.log calls in scripts/ are pre-existing CLI stdout in tooling, not production app code, and are outside this diff.

Two findings are worth addressing before merge; neither is a security or correctness risk to the product, both are correctness risks to the measurement instrument, which is this PR's entire subject matter.


Requirements Check

AC Status Notes
1. Fix the 3→4→6 chain so scenario 6 keys on a persisted value; verify the gap isn't merely relocated ✅ Scenario 3's prompt now implies replacement cost; author verified against the live DB that the schema persists replacement_cost (number) and is_returned (boolean) — not just that the tool was called. Crucially, the "don't relocate the gap" clause was actually honored: re-running exposed that the gap had moved to create_node persisting a bare shell, and rather than declaring victory, the PR added minProperties to catch it. Keeping cost (not the item name) as scenario 6's discriminator is well-reasoned — an item-name key would collapse to a direct string match that plain search_nodes resolves, making the resolve_query assertion pass while testing strictly less.
2. Record offered tool list and routed skill per turn in the trace ✅ Dead selected_tools scrape deleted; [tools offered] repointed at the real line (post-scoping stage2_tools output — the surface the model actually saw, which is the right semantics). routed_skills added to the routing log. Both verified populated against a real daemon run. See finding 3 on "per turn."
3. Re-run affected scenarios to confirm the chain resolves end to end ✅ Clean full run on purged DB + freshly rebuilt daemon (correctly following the known "evals silently measure stale guidance" hazard): 8/12, matching the prediction exactly, with scenario 4's failure message quoted. The run also paid off immediately — it answered the issue's own availability question by showing resolve_query was offered on scenario 6, so its failure is not availability. That's the observability improvement earning its keep on the first use. One honest caveat, self-disclosed: the committed trace's routedSkills predates 7a449cb4 (see finding 4).

Code Review Findings

🟡 Important

1. property_count counts what was requested, not what was persisted — and the authoritative answer is already in hand

📁 packages/agent/src/local_agent/tools.rs:1721-1728

let property_count = properties.as_object().map(|o| o.len()).unwrap_or(0);

This is computed from the merged request map, before node_ops::create_node runs. But persistence is not pass-through. NodeService::create_node (packages/core/src/services/node_service/crud.rs:49+) can transform the map en route to storage: normalize_flat_properties_to_namespace reshapes flat keys into a type namespace, apply_schema_defaults_with_fields adds entries the model never supplied, and _schema_version is injected. Validation can also reject values.

The consequence runs in both directions, and both are bad for an instrument whose purpose is to distinguish "recorded the particulars" from "persisted a bare shell":

  • False pass: schema defaults or _schema_version inflate the count so a call that supplied none of the user's particulars still clears minProperties: 1.
  • False fail: a namespaced reshape collapses the count below the request-side figure.

The fix is nearly free, because create_node already re-fetches the created node — node_ops.rs:194-201 does a get_node and puts the result in output.node_data. Counting from that post-persistence state, rather than from the pre-flight request map, makes the field mean what its comment says it means ("what this call actually carries" → what storage actually holds).

This matters more than a normal off-by-semantics nit because the PR's own framing is "the result is the executor's report of what it persisted, while args are only the model's report of what it asked for" (agent_loop.rs:1232-1234). property_count as written is on the wrong side of the distinction the surrounding code just drew. Right now scenario 4 reports 0 and the conclusion holds either way — but the field is being added specifically so future runs can trust it, and the first run where a schema default fires is the run it misleads.

Principle: an observation must be taken at the boundary it claims to describe. Measuring the input and labeling it the output is the same class of error as the dead selected_tools scrape this PR exists to remove.


2. The tool_names fixtures encode a quoted shape the daemon never emits — the identical latent defect 7a449cb4 just fixed for routed_skills

📁 scripts/aichat.test.ts:81, and every tool_names="..." fixture in aichat.test.ts / runner.test.ts

My reproduction (above) shows real output is tool_names=create_node, search_nodes system_prompt_len=1234 — unquoted, because it uses the same % sigil as routed_skills. Every fixture in these tests writes tool_names="create_node, search_nodes".

The scrape happens to survive, and I verified this explicitly:

/tool_names="?([^"]*?)"? system_prompt_len/
  REAL    -> "create_node, search_nodes"   ✅
  FIXTURE -> "create_node, search_nodes"   ✅

The optional-quote pattern tolerates both, so there is no bug today. But the fixtures are asserting against a shape reality does not produce, which is precisely the condition the PR's own commit message identifies as the root cause of the routed_skills miss: "The unit tests passed throughout because their fixtures used the quoted form — they asserted the scrape against a shape the daemon never produces."

The PR fixed the instance and left the class. The trailing system_prompt_len anchor is currently the only thing preventing the same silent-empty failure, so any future reordering of that log line's fields — the exact fragility the author correctly flags for routed_skills — would break [tools offered] again while the tests stay green.

Suggested fix: update these fixtures to the verbatim unquoted daemon form, exactly as routed_skills's fixtures now are. It's a small edit that closes the class rather than the instance, and it's fully in the spirit of what this PR already did.

Principle: a test fixture is a claim about the real world. When it diverges, the test stops measuring the system and starts measuring itself — the specific failure mode this entire PR is about.


🟢 Suggestions

3. extra()'s per-turn arrays are inert as wired — the runner always passes exactly one turn

📁 scripts/eval/fixtures/agent-matrix.ts:381-386, scripts/eval/runner.ts:533,551

The change from turns[0]?.toolsOffered to turns.map(...) is justified in-comment by "a scenario's turns can be offered different tool surfaces." True in principle, but both call sites pass a single-element literal:

extra: fixture.extra?.(scenario, [scored]),

priorTurns are deliberately excluded (they're never scored). So these arrays are always length 1, and the shape change buys nothing today while making the results file marginally harder to read.

I checked this doesn't break anything: compareToBaseline joins on id and reads only passed/failure, and no renderer consumes extra. So it's harmless — just not yet load-bearing.

Fine either way, but worth being explicit in the comment that this is anticipatory rather than describing current behavior, or the next reader will look for the multi-turn path and not find it. (Alternatively — this is arguably YAGNI, and turns[0] was honest about what the runner does.)


4. routed_skills has no Rust test coverage, and neither does property_count

📁 packages/agent/src/local_agent/agent_loop.rs:1742-1749, packages/agent/src/local_agent/tools.rs:1728,1755

The TypeScript side of both features is now well covered (6 new tests, including the excellent "spaces and commas" and "absent vs empty" cases). The Rust side — the producer of the log field and the result field — has none.

This is what let the quoted/unquoted mismatch reach a full eval run: the only tests were downstream of the format, so nothing asserted the emitted string. A single test asserting exec_create_node's result contains property_count, and one asserting the join format of routed_skills, would close the loop that just cost a re-run. Given #1841 will change create_node's property behavior, a test pinning the result contract is cheap insurance.

Principle: test at the boundary you own. A contract asserted only by its consumer's fixtures is not asserted at all.


5. result_field_count conflating two tools is sound — but the name no longer fits

📁 packages/agent/src/local_agent/agent_loop.rs:1236-1256

I initially expected this to be a problem and concluded it isn't. The two shapes are disjoint (create_schema returns fields, create_node returns property_count; neither returns both), fieldCount is only ever interpreted per-tool downstream (schemaCallsAreSound filters c.name !== "create_schema", callPersistedProperties filters on its tool argument), and the shared field spares the scraper a reconciliation. The justifying comment is good.

The residual risk is naming: "field count" now means schema fields defined for one tool and property values supplied for another. A third tool returning a fields array with different semantics would silently join the pile. Nit-level, but persisted_item_count or similar would carry the generalization the field has actually taken on.


6. types.ts "recorded before this field existed" comments — legitimate, not a backward-compat violation

📁 scripts/eval/types.ts:46-53, scripts/eval/fixtures/agent-matrix.ts:130-133

Flagging explicitly since the no-backward-compatibility rule is strict here: these are fine, and should stay.

The rule targets code paths — dual-mode support, deprecation shims, migration layers. These comments describe data: results and baseline JSON files that are immutable historical records of inference runs, some of which cost minutes of GPU time and cannot be regenerated identically (different model state, different DB). Treating a missing fieldCount as 0 would retroactively convert archived passes into failures for runs where the property was never observed — corrupting the baseline comparison that is the eval's whole point.

callPersistedProperties's if (c.fieldCount === undefined) continue; correctly mirrors the established schemaCallsAreSound precedent, and the runner's routedSkills?: string (undefined, not "") preserves the "not recorded" vs "nothing routed" distinction — with a test for exactly that. This is sound absence-vs-zero modeling, not a compat shim.


7. property_count reaching the model as a tool result — acceptable, with precedent

📁 packages/agent/src/local_agent/tools.rs:1755

I checked this against ADR-064 rule 4 (tool results carry facts, not procedures) and against sibling tools. property_count is a fact about the completed outcome, and the codebase already returns confirmation metadata in exactly this position: update_node → "updated": true (tools.rs:1822), delete_node → "deleted" (2088), set_status → "status"/"updated" (2059). So this is consistent with established practice, not a new pattern, and the token cost is a handful.

Worth a light watch rather than a change: create_node's result was previously {id} alone, and this PR's own #1841 finding is that create_node's property behavior is prose-sensitive. If a future run shows the model reacting to seeing property_count: 0 (e.g. retrying, or narrating about it), that's the thing to look at. Not a reason to hold the PR.


Recommendation

COMMENT — approve-worthy in substance; two items worth a quick pass first.

This is careful work on the instrument the rest of the agent workstream depends on, and it holds itself to a standard most eval fixes don't: it re-ran, discovered its own fix had only moved the gap, and then went and closed the new one instead of shipping. The self-reported 7a449cb4 regression and the disclosed stale-trace caveat are both signs of a review you can trust.

Before merge I'd suggest:

  • Finding 1 (property_count measured pre-persistence, when output.node_data already holds the post-persistence truth) — this is the one with real legs, since the field is being added expressly so future runs can rely on it.
  • Finding 2 (tool_names fixtures still encode the never-emitted quoted form) — small edit, and it closes the class of defect this PR just fixed one instance of.

Findings 3–7 are optional. Nothing here is a security, data-integrity, or product-correctness risk, and the 8/12 conclusion stands regardless.

Reviewed by an AI reviewer — final merge call is the author's.

@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.

Initial review posted above. Recommendation: COMMENT — net positive and approve-worthy in substance; two items worth a quick pass before merge (property_count measured pre-persistence; tool_names fixtures still encode a quoted shape the daemon never emits). Final merge call is the author's.

Finding 1 (Important). `property_count` was computed from the merged argument
map before create_node ran, so it answered "what did the model ask for" while
claiming to report what persisted. Creation is not pass-through — schema
defaults are applied and keys are normalized into the type's namespace — so the
two disagree in both directions, and both hurt: a default can inflate the count
past `minProperties: 1` and produce the false pass the assertion exists to
prevent. It now reads `output.node_data`, create_node's own re-fetch of the
stored node, already flattened out of the namespace with `_schema_version`
filtered. Verified live: a create carrying label + status reports
property_count=2 against a node storing exactly those two.

The old comment in agent_loop.rs already drew this distinction — "the result is
the executor's report of what it persisted, while args are only the model's
report of what it asked for" — and the field had landed on the wrong side of it.

Finding 2 (Important). Fixtures encoded `tool_names="..."`, `tool="..."` and
`args_preview="..."` in quoted form; tracing emits all three bare. No live bug,
but this is the exact defect class the previous commit fixed, left in place one
line away from it. Captured the real shapes off a running daemon and replaced
the hand-written ones, with a file-level note to copy from a real log rather
than write fixtures by hand.

Finding 4 (Suggestion). The routed_skills rendering had no Rust-side test — only
downstream TS fixtures asserted its format, which is what let the quoting
mismatch reach a full eval run. Extracted it as routing::routed_skill_names and
tested it, including that it names the same set render_candidates_for_prompt
writes into the prompt.

Finding 3 (Suggestion). Marked extra()'s per-turn arrays as anticipatory.

Skipped finding 5 (rename result_field_count): the reviewer confirmed the
conflation is sound — disjoint shapes, per-tool interpretation — so this is a
naming change rippling into an unrelated log field and its scraper for no
behavioral gain. Revisit if a third tool feeds the field. Findings 6 and 7 were
validated as correct with no action requested.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01AvsJJC6NgtJuNz8fTYA163
@malibio

malibio commented Jul 31, 2026

Copy link
Copy Markdown
Collaborator Author

Review feedback addressed — commit 3e0838e2

Addressed 4 of 7 findings; skipped 3 (2 required no action, 1 declined with reasoning).

🟡 Finding 1 — property_count counted requests, not persistence ✅

You were right, and this was the one real correctness bug. The count came from the merged argument map before node_ops::create_node ran, so it answered "what did the model ask for" while the field name and its own comment claimed persistence. Since creation applies schema defaults and normalizes keys into the type namespace, the two disagree in both directions — and the inflating direction is the dangerous one: a default could push the count past minProperties: 1 and produce exactly the false pass the assertion exists to prevent.

Now reads output.node_data, which as you noted is already re-fetched at node_ops.rs:194-201. A detail that made this cleaner than expected: flatten_properties_for_api (convert.rs:69-95) already unwraps the type namespace and filters underscore-prefixed keys, so _schema_version is excluded for free and the count is exactly the user-meaningful values a later turn could resolve against.

Verified live rather than by inspection — a create carrying label + status:

result_preview={"id":"nodespace://55aaa806-...","property_count":2}
node get   →   properties: {"gadget":{"_schema_version":1,"label":"Widget A","status":"shipped"}}

Two persisted, two counted, internals excluded. The zero direction was already demonstrated by the eval run that produced result_field_count=0 on scenario 4.

Your framing was the useful part: the existing comment at agent_loop.rs:1232-1234 already drew this exact distinction, and the new field had landed on the wrong side of it.

🟡 Finding 2 — fixtures encoding a shape the daemon never emits ✅

Fixed, and it was broader than tool_names: tool="create_node", args_preview="{}" and result_preview="{}" were quoted too. Confirmed all of them bare off a running daemon rather than reasoning about it:

Tool executed tool=create_schema is_error=true duration_ms=0 args_preview={} result_preview={...}
tool_names=search_nodes, resolve_query, search_semantic, get_node, create_node, ...

Replaced the hand-written forms with captured ones and added a file-level note in aichat.test.ts to copy marker lines from a real log rather than write them by hand. Your "fixed the instance, left the class" characterization was accurate.

(Incidentally, confirming your experiment from the other direction: routing_decision="clarify" is quoted, because it's a single word. That's what makes this failure mode so quiet — the quoted form looks right next to a real quoted field.)

🟢 Finding 4 — no Rust coverage for the new producers ✅

Extracted the rendering as routing::routed_skill_names — a function specifically so the emitted text is assertable — and added three tests, including one that asserts the logged set matches what render_candidates_for_prompt actually writes into the prompt, so the two can't silently diverge. Agent crate: 371 → 374 tests.

🟢 Finding 3 — per-turn arrays are inert ✅

Comment now marks them anticipatory, noting the collapse would be silently wrong the moment a scenario scores more than one turn.

⏭️ Skipped

  • Finding 5 (rename result_field_count) — you confirmed the conflation is sound (disjoint shapes, per-tool interpretation), so this is a naming change rippling into an unrelated log field and its scraper for no behavioral gain. Worth revisiting if a third tool ever feeds it.
  • Findings 6 and 7 — validated as correct in review; no action requested.

Verification

bun run test:all exits 0 — frontend 4112 passed (171 files, = baseline), scripts 74 passed, skill 20 passed, Rust green (agent 374). cargo clippy -p nodespace-agent --all-targets -- -D warnings clean. quality:fix touched only files in this change. Full pre-push gate passed.

Re-review

Not needed, in my view — finding 1 is a genuine behavior change but narrow (one expression, verified live in both directions), and the rest are tests, fixtures, and comments. Happy to re-run if you'd prefer the persisted-count change get a second look, since it's the one thing here that alters what the eval measures.

@malibio
malibio merged commit 756243a into main Jul 31, 2026
2 checks passed
@malibio
malibio deleted the worktree-issue-1839-matrix-chain-trace branch July 31, 2026 04:57
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.

Fixture: agent-matrix scenarios 3->4->6 key on a value the chain never persists; trace doesn't record offered tools/routed skill

1 participant