Skip to content

Route skill retrieval by pure KNN instead of hybrid BM25 tiering - #2549

Merged
malibio merged 1 commit into
mainfrom
issue-2265-skill-retrieval-stability
Sep 9, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-2265-skill-retrieval-stability

Conversation

@malibio

@malibio malibio commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator

Summary

  • Fixes skill retrieval instability: find_skills called the hybrid BM25+KNN semantic_search_nodes, whose result order is a hard tier partition (BM25∩KNN, then KNN-only, then BM25-only) rather than a blended score — so a skill whose guidance markdown happened to share a keyword with the query could rank ahead of a much stronger semantic match purely from tier membership. Verified directly this is what made Schema Creation retrieval intermittent (not an embedding near-tie, as originally hypothesized). find_skills now calls semantic_search_nodes_of_type (pure KNN over skill-typed roots) — a pre-existing primitive built for exactly this small closed-corpus classification shape, with no BM25 involvement at all.
  • Adds a live-embedding-model regression test (packages/agent/tests/live_skill_retrieval_stability.rs) closing a real test-coverage gap: every prior skill-routing test either mocked retrieval out entirely or drove the full Stage-1 LLM, so nothing exercised live Stage-2 retrieval against the real seeded registry.
  • Fixes an unrelated 2-day-old regression in the eval harness's scripts/aichat.ts: it read node.properties["ai-chat"], but node get --json's output was flattened by a recent commit (Emit flat node properties from the CLI (closes #2381) #2423), so the turn-completion poll loop could never observe it and every eval turn silently burned its full timeout before detecting completion.

Verification

  • Live embedding-model test (live_skill_retrieval_stability.rs, run explicitly against the real nomic-embed-text-v1.5 model): scenario 8a now routes Schema Creation 1st (previously 3rd), 5/5 reps, with a clear score margin over the runner-up. A BM25-collision regression test confirms two unrelated skills still keyword-match via bm25_search_roots but no longer affect find_skills's output.
  • Full bun run eval:agent matrix (gemma-4-e4b-q4km, --runs 3, fresh isolated DB): create_schema was offered and called in every rep for every Schema-Creation-relevant scenario; the daemon log's all_scores diagnostic confirms Schema Creation won retrieval by a clear margin on every turn. Filed Relationship Management never routes for natural 'point at'/'link'/'connect' phrasing #2548 for an unrelated, pre-existing routing gap in Relationship Management found along the way.
  • cargo test -p nodespace-core -p nodespace-agent --lib: 1286 + 627 passed, no regressions.
  • bun run quality:fix: clean (ESLint, TypeScript, svelte-check, clippy).
  • bun run test:all: clean, no new failures vs. baseline (4909 frontend tests).
  • Pre-push gate (test:all + cargo build --bin nodespaced + test:e2e): passed.

Test plan

  • Live-embedding regression test added and passing (packages/agent/tests/live_skill_retrieval_stability.rs, run with --ignored)
  • Full dev-workflow matrix re-run against the fix, confirming Schema Creation routing stability
  • Existing Rust unit test suites pass unchanged
  • quality:fix and test:all clean

Closes #2265

🤖 Generated with Claude Code

 #2265)

find_skills used the hybrid BM25+KNN semantic_search_nodes, whose result
order is a hard tier partition (BM25∩KNN, then KNN-only, then BM25-only)
rather than a blended score. A skill whose guidance markdown happened to
share a keyword with the query could rank ahead of a much stronger
semantic match purely from tier membership — this is what made Schema
Creation retrieval intermittent rather than an embedding near-tie as
originally hypothesized. find_skills now calls
semantic_search_nodes_of_type (pure KNN over skill-typed roots), a
pre-existing primitive built for exactly this small-corpus classification
shape, with no BM25 involvement.

Also fixes an unrelated 2-day-old regression in the eval harness's
scripts/aichat.ts: it read node.properties["ai-chat"], but node get
--json's output was flattened by a recent commit, so the turn-completion
poll loop could never observe it and every eval turn silently burned its
full timeout.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@malibio

malibio commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

Clean, well-scoped fix. find_skills swaps the hybrid BM25+KNN semantic_search_nodes for the pre-existing pure-KNN semantic_search_nodes_of_type primitive, eliminating a real tier-partition bug (BM25 hits unconditionally outranking stronger KNN-only matches regardless of score magnitude). The swap is a clean replacement, not a dual-mode/fallback — no backward-compatibility shim, no feature flag, consistent with this repo's pre-release conventions. The new live regression test is properly gated (#[ignore], graceful skip when the embedding model isn't on disk) and asserts something meaningful (100% pass rate across 5 reps on a documented 1-in-3 intermittent defect, not an averaged or single-run check). The aichat.ts fix is a real, self-contained bug fix to eval-harness tooling; bundling it is defensible given it silently corrupted eval timing data, though it is scope creep relative to the PR's stated purpose. One stale test comment/doc-drift item, no blockers.

Requirements Check (issue #2265 acceptance criteria)

  • Scenario 8a's prompt routes Schema Creation in the top-N across repeated reps — scenario_8a_routes_schema_creation_every_rep asserts this directly (5/5 reps); PR description reports the live run went 5/5 with a clear score margin, up from the 2/3 baseline in the issue.
  • A repeated-prompt retrieval-stability check exists — live_skill_retrieval_stability.rs (REPS = 5, explicitly justified against the issue's own 1-in-3 observed rate) is exactly this check, and it's a permanent regression test, not a one-off harness run.
  • [~] Attribution/authorship phrasing does not pull Relationship Management ahead on type-definition prompts — addressed structurally (the BM25 tier-collision root cause is eliminated entirely, so the specific mechanism described in the issue can't recur), not via the issue's suggested lever (rewording Schema Creation's / Relationship Management's descriptions). The PR's own investigation found the root cause was tiering, not embedding-space closeness or description wording, which supersedes the issue's original hypothesis — reasonable, but worth noting this criterion is met by a different mechanism than literally written. scenario_8a_paraphrases_show_wording_sensitivity is a diagnostic-only test (no assertions) probing exactly this; it doesn't harden the criterion, it documents it.
  • Re-run Evaluate Ornith 1.5 and Qwen 3.6 on the dev-workflow matrix (prior rejections predate the current stack) #2239's arms and confirm no ⊗ exclusions from this cause — PR body reports a full eval:agent matrix rerun (gemma-4-e4b-q4km, --runs 3, fresh DB) with create_schema offered/called on every rep for every Schema-Creation-relevant scenario. Filed Relationship Management never routes for natural 'point at'/'link'/'connect' phrasing #2548 for an unrelated pre-existing gap found along the way rather than scope-creeping it into this PR — good hygiene.

Findings

Critical Issues

None.

Suggested Improvements

  • packages/core/src/ops/skill_ops.rs:975-990 (skill_filter_matches_only_skill_nodes test) — its comment says "Validates the post-filter predicate used in find_skills," but after this change find_skills no longer imports or calls SearchNodeFilters at all (confirmed: the import was removed at the top of the file). The predicate itself is still real code, exercised by semantic_search_nodes's other callers, so the test isn't asserting a false invariant — but the comment now misattributes which caller it's protecting, and a future reader will use it to reason about find_skills's filtering behavior incorrectly. Worth a one-line comment update (or moving/renaming the test) in a follow-up; not a blocker for this PR.

Nitpicks

  • Nit: packages/core/src/ops/skill_ops.rs:321 — the removed manual search_limit = (limit * 5).max(limit + 15) pre-inflation is correctly redundant: search_embeddings_by_node_type already over-fetches by EMBEDDING_KNN_OVERFETCH * 5 with the type filter folded into the SQL WHERE clause (DB-level, not a Rust post-filter), so nothing here needed backfilling. Confirmed by reading packages/core/src/db/sqlite_store/embeddings.rs:539-580. Good simplification — flagging only so the reviewer trail shows this was checked, not assumed.
  • Nit: packages/agent/tests/live_skill_retrieval_stability.rs — find_skills_ranking_is_unaffected_by_bm25_keyword_collisions and scenario_8a_paraphrases_show_wording_sensitivity are diagnostic/investigative tests dressed as #[tokio::test]s (the paraphrase one has zero assertions, just eprintln!). They're fine to keep since they're #[ignore]d and won't run in CI/test:all, but if this repo wants to keep tests/ scoped to enforced regressions vs. exploratory probes, these two are candidates for a bin/example or deletion once their diagnostic purpose is served — consistent with the CLAUDE.md guidance to delete one-off scripts once their purpose is served (that guidance is scoped to scripts/, so this is explicitly optional, not a rule violation).

Verification Performed

  • git diff origin/main...HEAD read in full across all three changed files.
  • Confirmed semantic_search_nodes_of_type is pre-existing (present since commit 233c47da, "Implement Topic Node Embeddings with Adaptive Chunking (Implement Topic Node Embeddings with Adaptive Chunking #198)"), already used by context_ops.rs — the PR's "pre-existing primitive" claim is accurate, not a new/undertested code path.
  • Confirmed SKILL_SEARCH_THRESHOLD = 0.0 is unchanged and both search functions share the same composite_score > threshold / cosine-similarity semantics — no silent threshold-semantics change for downstream confidence scoring.
  • Confirmed node_type = 'skill' scoping is correct: it matches the same skill-only intent the old SearchNodeFilters { node_types: Some(vec!["skill"]) } filter expressed, just enforced in SQL instead of as a Rust post-filter.
  • cargo build -p nodespace-core -p nodespace-agent --tests — clean, no warnings surfaced.
  • cargo test -p nodespace-core --lib skill_ops — 26/26 passed.
  • Grepped for #[allow(...)] / #[deprecated] across all three changed files — none present.
  • Confirmed live_skill_retrieval_stability.rs follows this repo's established live_*.rs naming/gating convention (14 prior files in packages/agent/tests/, several using the identical #[ignore = "requires the locked ... GGUF on disk"] + graceful seed_and_embed() -> Option<...> skip pattern seen in live_stage1_golden_prompts.rs).
  • Read the aichat.ts diff in full: Partial<AiChat> + { ...defaultAiChat(), ...node.properties } merge is the correct fix for a genuinely flattened CLI JSON shape, and the inline comment on NodeJson.properties accurately explains why writes stay nested while reads are flat.

Recommendation

APPROVE. The core fix is correct, minimal, and directly traceable to the issue's root-cause finding; it removes rather than layers on complexity (deletes the now-unneeded pre-inflation logic and an unused import). Test coverage is real and meaningfully asserts the fix (not tautological — it reproduces the documented intermittent-failure rate and shows a fix). The bundled aichat.ts fix is legitimate scope creep (arguably should have been its own PR per strict atomicity) but is small, self-contained, well-justified, and low-risk enough not to block on. Address the one stale test comment in skill_ops.rs in a follow-up rather than this PR.

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Sep 9, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2549 (closes #2265)

Verdict: APPROVE

Summary of what changed

  1. packages/core/src/ops/skill_ops.rs: find_skills now calls NodeEmbeddingService::semantic_search_nodes_of_type (pure KNN over node_type = 'skill' roots) instead of semantic_search_nodes (hybrid BM25+KNN with tier-partitioned ordering). Also drops the manual limit * 5 over-fetch/truncate dance, since the typed-KNN primitive already takes limit directly and doesn't need post-hoc Rust-side type filtering.
  2. packages/agent/tests/live_skill_retrieval_stability.rs (new, 316 lines): four #[ignore]d live-embedding-model tests — a 5-rep stability check for the reported scenario (Schema Creation), a diagnostic proving the BM25-collision mechanism is real and no longer affects ranking, a wording-sensitivity diagnostic, and a control-prompt regression guard.
  3. scripts/aichat.ts: fixes a node.properties["ai-chat"] read that no longer matched the CLI's flattened --json output shape, unrelated to the main fix but caught along the way (eval harness was silently timing out every turn).

Verification performed

  • Confirmed semantic_search_nodes_of_type (packages/core/src/services/embedding_service.rs:974) calls search_embeddings_by_node_type, which is a straight vec0 KNN query joined on node_type in SQL — no BM25 path at all. This matches the PR's core claim.
  • Confirmed semantic_search_nodes (embedding_service.rs:905) delegates to semantic_search, whose hybrid tiering (BM25∩KNN, then KNN-only, then BM25-only) is a hard partition, not a blended score — the described bug mechanism is real, not a mischaracterization.
  • Confirmed the aichat.ts premise against AiChatNode::from_node (packages/core/src/models/ai_chat_node.rs:216-250), which is explicitly documented as accepting nested-or-flat properties, falling back to flat when the "ai-chat" namespace is absent "e.g. after flatten_properties_for_api has promoted them" — exactly the situation the script hits.
  • Checked other semantic_search_nodes call sites (search_ops.rs, agent_catalog/context_assembly.rs) — both are open-ended document search / neighbor-expansion use cases, genuinely different retrieval shapes from the closed ~8-20-item skill classification problem, so correctly left untouched. No missed sibling instance of the bug.
  • Verified the removed SearchNodeFilters import is dead in this file outside the test module (which has its own local use) — no leftover dead code.
  • cargo build -p nodespace-core -p nodespace-agent --lib: clean.
  • cargo test -p nodespace-core --lib skill_ops: 26/26 passed.
  • bun run test:scripts: 387/387 passed (covers aichat.ts marker-parsing logic via aichat.test.ts).
  • bun run quality:fix: clean, no changes needed (ESLint, tsc, svelte-check, cargo fmt/clippy all already pass).
  • git diff main...HEAD --stat: exactly the 3 files described in the PR body — no scope creep.

Findings

None blocking. This is a well-scoped, well-verified fix:

  • The root-cause diagnosis (tier-partitioned hybrid ranking, not an embedding near-tie) is demonstrated directly by the new find_skills_ranking_is_unaffected_by_bm25_keyword_collisions test, which independently confirms via bm25_search_roots that the collision is real on the reproduction query before asserting the fix's outcome — good discipline, not just an assertion on faith.
  • Code change itself is a net simplification (deletes the manual over-fetch/truncate/filter-construction logic that the typed-KNN primitive makes unnecessary), not just a swap.
  • New test suite is appropriately gated behind #[ignore] + a graceful skip when the model isn't on disk, so it won't break CI or contributors without the model cached, while still being runnable on demand exactly where this class of regression would need to be caught (a live-embedding property, not something a mock can meaningfully test).
  • The unrelated aichat.ts fix is small, narrowly scoped, in a dev-tooling script (exempt from createLogger), and independently justified/tested.

Minor, non-blocking observations (not requesting changes):

  • find_skills itself has no non-live unit test directly exercising the new semantic_search_nodes_of_type call path with a fake/mocked embedding service — all coverage of the actual behavioral change is behind --ignored live tests. Given the bug is inherently about real embedding-space ranking behavior, a mock would only test wiring, not the property that matters, so this is a reasonable tradeoff rather than a gap worth blocking on.
  • The PR description's "Filed Relationship Management never routes for natural 'point at'/'link'/'connect' phrasing #2548" side-note (unrelated Relationship Management routing gap found during matrix verification) is correctly kept out of this PR's diff — good scope discipline.

No correctness, security, or architectural concerns. Recommend merge.

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

Automated pragmatic-code-review: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio
malibio merged commit e661561 into main Sep 9, 2026
@malibio
malibio deleted the issue-2265-skill-retrieval-stability branch September 9, 2026 22:36
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.

Skill retrieval is unstable across runs: same prompt drops create_schema from the tool surface

1 participant