Repository navigation
KB-03: bounded authorized retrieval and repair - #3
Conversation
|
OpenRouter review posted ( |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: issues
Scope: full-pr (full-pr)
Mode: initial
Commit: 970419ebf7e47e40bd07c425ff5e5670c838b742
Judge: openai/gpt-5.6-luna
Cost: $0.8428 (lanes $0.8387 + judge $0.0040)
Lanes
meta/muse-spark-1.2: ok (3 finding(s), 94.6s, 889639+8420 tokens (472855 cached), 8 tool round(s), via Meta, $0.63)z-ai/glm-5.3-flash: ok (8 finding(s), 418.9s, 4196336+68818 tokens (3670848 cached), 33 tool round(s), via Makora, $0.21)
Findings
🟠 Issue 1 — Clock misconfiguration escapes content-free no_result contract
packages/application/src/publication.ts:34 · risk · identified by meta/muse-spark-1.2
Failure scenario: when options.clock.now() returns a non-canonical ISO string, publication.ts:clockTime() throws TypeError. For portal/bot request paths retrieval.ts:searchPublishedArticles/retrieveAnswerSources catches all errors and returns a content-free no_result, but publication.ts:check() re-throws TypeError (it only maps RepositoryCapacityError for index purpose to capacity and isUnavailable errors to NotFound). retrieval-maintenance.ts:desired() and currentStatus() only translate RepositoryCapacityError/RepositoryConflictError/NotFound into blocked/pending; a TypeError from the clock therefore propagates as an unhandled exception to the staff caller of repairArticleIndex/getArticleIndexStatus instead of the documented visible blocked/pending status.
Evidence: publication.ts:134-145 validates at strictly with toISOString() check and throws TypeError; publication.ts:304-322 catches and re-throws non-isUnavailable errors; retrieval-maintenance.ts:247-257 swallows only capacity/conflict/not-found.
Checked: packages/application/src/publication.ts, packages/application/src/retrieval-maintenance.ts, packages/application/src/retrieval.ts:464-483 outer try/catch for request paths vs maintenance paths. Gap: no test asserts clock TypeError becomes blocked status; proof gap remains that host clock is assumed correct.
🔵 Issue 2 — SourceGeneration minimum mismatch between hint validation and admission
packages/application/src/retrieval-records.ts:109 · nit · identified by meta/muse-spark-1.2
Failure scenario: retrieval-records.ts:requireRetrievalHint() allows sourceGeneration === 0 via requireGeneration(hint.sourceGeneration) with default minimum 0, but retrieval-repository.ts:beginArticleProjection() requires requireGeneration(request.sourceGeneration,1) and requireRetrievalHint inside requireTarget will still accept 0, creating a hint that can never be admitted — the subsequent beginArticleProjection throws TypeError instead of the expected RepositoryCapacityError/conflict path, leaving repairArticleIndex to surface an unexpected TypeError rather than a visible blocked:capacity.
Evidence: retrieval-records.ts:109 vs retrieval-repository.ts:894 and retrieval-maintenance.ts:143-154 where checked.binding.sourceGeneration originates from SourceSnapshot.generation which can be 0 for an article without private sources.
Checked: packages/application/src/retrieval-records.ts:103-122, packages/application/src/retrieval-repository.ts:881-914, test/retrieval-fixtures.ts uses default sources (generation 1) so the 0 case is exercised only on source-free articles. No counterevidence found that sourceGeneration is always >=1.
🔵 Issue 3 — Budget proxy conflates illegal API use with work exhaustion
packages/application/src/retrieval-budget.ts:78 · nit · identified by meta/muse-spark-1.2
Failure scenario: retrieval-budget.ts:createRetrievalReadBudget() proxies Store.collection() and throws RetrievalBudgetError for any property other than get/getVersioned with message "exhausted its bounded work allowance". A developer accidentally calling scan, list, or transact through the request-scoped budget store (e.g., future feature adding a corpus scan) receives a budget-exhaustion error that retrieval.ts maps to a content-free no_result, hiding the programming error and making debugging difficult — the error is indistinguishable from legitimate budget exhaustion in logs.
Evidence: retrieval-budget.ts:78-94 proxy get trap throws RetrievalBudgetError for all other properties; retrieval.ts:512-528 and 708 catch all and return no_result.
Checked: packages/application/src/retrieval-budget.ts, packages/application/src/retrieval.ts:388-410. No caller currently misuses the proxy; gap is observability when it happens.
🟠 Issue 4 — Adapter-path preselection discards the adapter's ranking and truncates by article ID
packages/application/src/retrieval.ts:371 · risk · identified by z-ai/glm-5.3-flash
A host KnowledgeCandidateAdapter returning more than maxConfirmations hints can have its best-ranked candidates silently dropped. Every adapter hint is added under the literal term "adapter" (retrieval.ts:371), so every adapter candidate ends up with terms.size === 1; the subsequent sort (right.terms.size - left.terms.size || ordinal(articleId)) therefore degenerates to plain article-ID ordering, and candidates.slice(0, limits.maxConfirmations) (retrieval.ts:422) confirms only the eight lexicographically-smallest article IDs. An adapter that streams a relevance-ranked result set of 20 hints loses its top matches to arbitrary low-ID articles, which then consume the confirmation budget.
🟠 Issue 5 — Adapter-supplied candidates are unconditionally dropped when the confirmed article has no lexical metadata overlap
packages/application/src/retrieval.ts:448 · risk · identified by z-ai/glm-5.3-flash
search() requires score > 0 after confirming a candidate (retrieval.ts:448), where the score comes from scoreConfirmedArticle over title/summary/tags only. An adapter that does anything beyond mirroring the default lexical projection — e.g. matching on body text, synonyms, or host-side semantics — can return its top-ranked article, the publication check succeeds, and the result is then discarded because none of the query terms appear in the approved title/summary/tags. searchPublishedArticles and retrieveAnswerSources both return no_result in that case, so an adapter integration can permanently fail to surface valid, authorized articles with no diagnostic.
🔵 Issue 6 — Adapter budget exposes the entire remaining physical-read allowance with no reserve for candidate probes and confirmations
packages/application/src/retrieval-budget.ts:103 · nit · identified by z-ai/glm-5.3-flash
remainingCandidateWork() (retrieval-budget.ts:103) hands the adapter the full remaining maxRequestPhysicalGets/maxIndexKeyReads allowance. After the adapter loop, the same request still needs head probes (one store read per candidate, up to maxHeadProbes) plus authoritative confirmations (~15-30 keyed reads each through the budget proxy). A truthful adapter that reports ~700 reads of real work against the default 768 ceiling leaves too little for the confirmation phase, so retrieveAnswerSources throws RetrievalBudgetError mid-confirmation and returns no_result even though matching, authorized articles exist.
🔵 Issue 7 — Index collection name is hardcoded as a string literal, duplicating retrievalRecords.name
packages/application/src/retrieval.ts:238 · nit · identified by z-ai/glm-5.3-flash
retrieval.ts:238 passes indexCollectionName: "knowledge-base.retrieval.v1" while the collection name is defined once in retrievalRecords (retrieval-records.ts). If the collection definition's name is ever changed or parameterized, the budget's reserve() silently stops recognizing index reads: the dedicated maxIndexKeyReads ceiling (128) becomes dead — index reads are then charged only against the 768 physical-read budget — and remainingCandidateWork()/adapter dispatch checks quietly change meaning, with no error pointing at the mismatch.
🔵 Issue 8 — Racing maintenance workers can mark a healthy in-flight projection plan blocked("conflict")
packages/application/src/retrieval-maintenance.ts:399 · nit · identified by z-ai/glm-5.3-flash
In repair()'s catch, a RepositoryConflictError triggers markBlocked(articleId, state, "conflict") (retrieval-maintenance.ts:399-407). Plan generation does not change while a worker advances terms, so when two workers (or two overlapping repair-page cycles) work the same plan and one loses a scope-head or manifest CAS race, the loser writes status: "blocked", reason: "conflict" onto the plan that is still current and healthy; the winner's next advanceArticleProjection sees status === "blocked" and aborts mid-cleanup. The aborted batch's scope writes persist, and the next repair call re-begins and converges, so this is recoverable — but it reports a failure that did not happen and stalls the other worker's progress by at least one cycle.
🔵 Issue 9 — getArticleIndexStatus reports a stale blocked reason once the desired plan has changed to a withdrawal
packages/application/src/retrieval-maintenance.ts:276 · nit · identified by z-ai/glm-5.3-flash
currentStatus() checks state.status === "blocked" before comparing the stored targets with the recomputed plan (retrieval-maintenance.ts:276). Concretely: an article is blocked with reason capacity (e.g. overlong metadata), then the collection policy is withdrawn so desired() now returns empty targets; the stored sourceGeneration still matches, so status keeps reporting blocked/capacity even though the correct next step is withdrawal cleanup, which repairArticleIndex would perform. The staff-visible reason describes the old blocker until someone runs repair.
🔵 Issue 10 — Retrieval's anonymous-audience publicApproval gate has no test and depends on an unverified hash equivalence
packages/application/src/retrieval.ts:262 · nit · identified by z-ai/glm-5.3-flash
authorizeCollection() requires, for any anonymous portal/bot use, an exact publicApproval whose policyHash equals fingerprint(collection.policy) (retrieval.ts:262-268). Every retrieval test (tests/retrieval.test.ts, tests/retrieval-bounds.test.ts, tests/retrieval-maintenance.test.ts) uses permission audiences; the only anonymous-audience test in the repo (tests/application.test.ts:652) covers getPublishedArticle, which never checks publicApproval. If the application's fingerprint/canonicalJson ever diverged from core's canonical/digest (key ordering, number formatting), every anonymous-collection list/search would silently return no_result, and no test would fail.
🔵 Issue 11 — Budget doc comment overclaims the reservation mechanism for adapter dispatch
packages/application/src/retrieval-budget.ts:41 · nit · identified by z-ai/glm-5.3-flash
The comment on createRetrievalReadBudget says "Reserve a physical read before awaiting the adapter, so overlapping keyed reads cannot overspend" (retrieval-budget.ts:41). The code does not hold any reservation across the adapter await: it only pre-checks that the allowance is at least 1 before dispatch and adds the reported work via accountExternal after the promise resolves. Since the adapter loop is strictly sequential per request, no overspend can occur, but the comment describes a mechanism that does not exist, which can mislead future work that relies on a held reservation.
| RepositoryConflictError, | ||
| RepositoryIntegrityError, | ||
| requireIdentifier, | ||
| snapshotData, |
There was a problem hiding this comment.
🟠 Clock misconfiguration escapes content-free no_result contract (risk)
Failure scenario: when options.clock.now() returns a non-canonical ISO string, publication.ts:clockTime() throws TypeError. For portal/bot request paths retrieval.ts:searchPublishedArticles/retrieveAnswerSources catches all errors and returns a content-free no_result, but publication.ts:check() re-throws TypeError (it only maps RepositoryCapacityError for index purpose to capacity and isUnavailable errors to NotFound). retrieval-maintenance.ts:desired() and currentStatus() only translate RepositoryCapacityError/RepositoryConflictError/NotFound into blocked/pending; a TypeError from the clock therefore propagates as an unhandled exception to the staff caller of repairArticleIndex/getArticleIndexStatus instead of the documented visible blocked/pending status.
Evidence: publication.ts:134-145 validates at strictly with toISOString() check and throws TypeError; publication.ts:304-322 catches and re-throws non-isUnavailable errors; retrieval-maintenance.ts:247-257 swallows only capacity/conflict/not-found.
Checked: packages/application/src/publication.ts, packages/application/src/retrieval-maintenance.ts, packages/application/src/retrieval.ts:464-483 outer try/catch for request paths vs maintenance paths. Gap: no test asserts clock TypeError becomes blocked status; proof gap remains that host clock is assumed correct.
There was a problem hiding this comment.
The content-free no_result contract applies to customer search/bot retrieval. Staff maintenance reports known capacity/conflict/source eligibility states and deliberately surfaces unexpected host configuration failures. The host supplies a trusted canonical clock; a noncanonical value produces an explicit content-free TypeError before maintenance writes, consistent with KB-02 command behavior. Treating an invalid clock as an ordinary withdrawal/repair status would hide a configuration defect. We are clarifying that staff diagnostic boundary in the composition docs.
| }); | ||
| requireIdentifier(hint.articleId, "articleId"); | ||
| requireGeneration(hint.articleRevision, 1); | ||
| requireGeneration(hint.generation, 1); |
There was a problem hiding this comment.
🔵 SourceGeneration minimum mismatch between hint validation and admission (nit)
Failure scenario: retrieval-records.ts:requireRetrievalHint() allows sourceGeneration === 0 via requireGeneration(hint.sourceGeneration) with default minimum 0, but retrieval-repository.ts:beginArticleProjection() requires requireGeneration(request.sourceGeneration,1) and requireRetrievalHint inside requireTarget will still accept 0, creating a hint that can never be admitted — the subsequent beginArticleProjection throws TypeError instead of the expected RepositoryCapacityError/conflict path, leaving repairArticleIndex to surface an unexpected TypeError rather than a visible blocked:capacity.
Evidence: retrieval-records.ts:109 vs retrieval-repository.ts:894 and retrieval-maintenance.ts:143-154 where checked.binding.sourceGeneration originates from SourceSnapshot.generation which can be 0 for an article without private sources.
Checked: packages/application/src/retrieval-records.ts:103-122, packages/application/src/retrieval-repository.ts:881-914, test/retrieval-fixtures.ts uses default sources (generation 1) so the 0 case is exercised only on source-free articles. No counterevidence found that sourceGeneration is always >=1.
There was a problem hiding this comment.
These are separate generation domains. beginArticleProjection.sourceGeneration is the authoritative ARTICLE head generation (maintenance passes plan.articleGeneration, and repository validates it against hint.generation), so it must be >=1. hint.sourceGeneration describes the retained private provenance snapshot. It is not passed to that admission field. Current source-free articles use sourceSnapshot(1, []), and normal source-free indexing is covered by the real-store suites. The claimed zero-provenance-to-article-generation TypeError path does not exist.
There was a problem hiding this comment.
OpenRouter pull-request review
Verdict: clean
Scope: latest-commit (commit-range)
Mode: verify
Commit: 83478eb6157c359707b348c56d90cfe29aac85fa
Judge: openai/gpt-5.6-luna
Cost: $0.1499 (lanes $0.1498 + judge $0.0001)
Lanes
meta/muse-spark-1.2: ok (0 finding(s), 18.6s, 71819+2414 tokens (10451 cached), 2 tool round(s), via Meta, $0.0885)z-ai/glm-5.3-flash: ok (0 finding(s), 219.7s, 1110801+36202 tokens (1021312 cached), 19 tool round(s), via Together, $0.0612)
Round 2 resolution
- 🤝
r1-1disputed — Clock misconfiguration escapes content-free no_result contract: Customer paths remain content-free:retrieval.ts:searchPublishedArticles/retrieveAnswerSourcescatch all errors frompublication.ts:clockTime()(which still throwsTypeErrorfor non-canonical clock) and returnno_result. Staff maintenance intentionally surfaces unexpected host configuration errors visibly instead of mapping them to a withdrawal status, consistent with KB-02 command behav… - ✅
r1-4fixed correctly — Adapter-path preselection discards the adapter's ranking and truncates by article ID: Adapter preselection now preserves host ranking:retrieval.tsaddsCandidate.firstSeenon first encounter, sortsqueryHintsbyfirstSeenwhencandidateAdapteris present (vsterms.size+ordinal for the Store path), and slicescandidates.slice(0, limits.maxConfirmations)after that ordering. Confirmed sorting also usesfirstSeenas tie-breaker for adapter path. Regression test `retri… - ✅
r1-5fixed correctly — Adapter-supplied candidates are unconditionally dropped when the confirmed article has no lexical metadata overlap: Zero-overlap adapter candidates are no longer discarded:retrieval.ts:search()now keeps a confirmed candidate whenscore>0 || candidateAdapter!==undefined, allowing body/synonym matches with zero title/summary/tag overlap after authoritativechecker.check. Sorting still ranks by metadata score with adapter-order tie-break, andHOST_COMPOSITION.md/RETRIEVAL.md/retrieval-types.tsdocume… - 8 nit finding(s) from earlier rounds retired (severity floor for follow-up rounds is
risk). - Open findings after this round: 0 (0 bug-severity).
No structured findings from the successful lane(s).
Summary
Implement KB-03 bounded lexical retrieval, audience-aware citations, and resumable index repair in the existing application package. Portal search and bot answer sources use separate collection audiences; all returned text comes from one shared authoritative publication checker.
The Store-backed projection contains source-free keyed hints, bounded posting pages, catalogs, and generation-fenced repair manifests. Request paths enforce physical read/page/entry/candidate/body/token ceilings and never scan. Staff repair uses bounded cursor-aware authority scans, visible pending/blocked progress, and safe cleanup with retained generation floors.
Compatibility and authority
Existing keyed portal reads keep their input contract and retained-publication behavior. An unapproved draft does not suppress an unchanged approved guide. Current policy, proof, applicability, and source eligibility defeat stale hints. Bot-only citations grant no portal browse capability; exact source references are reconfirmed under current effective-customer authority.
Bot retrieval returns a ranked prefix of whole approved sources within byte and locally counted token bounds. Citation reconfirmation stays all-or-nothing. Optional host adapters supply hints and truthful prefilter work accounting, never content or permission decisions; exhausted budgets stop dispatch before the external call.
All three source packages remain unpublished at 0.1.0. API/MCP authentication, D1 release conformance, publication, and live host activation remain later tasks.
Validation
pnpm run format:checkpnpm run checkpnpm test: 238 tests, including 98 new public-entry cases on real memory and Azuritepnpm run release:check: clean-consumer imports for all three packed packagesIndependent authority/storage/budget reviews drove regressions for capacity errors, stale draft-head hints, whole-source fitting, and adapter exhaustion across both pages and collection scopes. Final scoped re-reviews are clean.