Skip to content

perf(review): one candidate proposal issues 19 SQL statements per artifact evidence reference #2088

Closed

Description

@Inference1

Summary

Measured on master at e4efb39b: one candidate proposal issues 19 SQL statements per artifact
evidence reference
, and the loaded rows are discarded — the loop exists only to confirm each
reference resolves. The public bound is MAX_CANDIDATE_EVIDENCE = 32
(builtin/review/models.py:30, enforced on the request field at :71), so a proposal that attaches
the allowed maximum spends 608 of its 612 statements on this.

The same function already batches one of its two inputs and does not batch the other:

# builtin/review/service.py:1033-1035   (inside _validate_evidence)
source_rows = await self._sources.require_for_generation(connection, self._scope_id, sources)
for artifact in artifacts:
    await self._artifacts.get(connection, self._scope_id, artifact)   # result not bound; existence check only

This is the same read-amplification family as #2075, on a different path. #2079 consolidates the recall
path and does not touch builtin/review/ (verified against its changed-file list).

Measurements

Setup: Python 3.12, in-memory SQLite (SQLiteConfig()), no embedding model, no reranker, one Scope,
32 Atomic Memories created up front, then one public experience.propose(...) call whose
artifacts= field carries K of those refs. Statements issued while creating the memories are excluded;
the counter is event.listen(Engine, "before_cursor_execute", ...), the same harness as
tests/e2e/test_sqlite_vec.py:59 and tests/builtin/runtime/test_statistics.py:556.

artifact evidence refs (K) statements
1 23
2 42
4 80
8 156
16 308
32 612

Every interval is exactly 19 × ΔK, with a constant base of 4. The per-reference cost was attributed by
differencing the K=2 and K=1 statement multisets rather than by reading alone:

per additional artifact ref statement
5x SELECT pc_artifacts.scope_id, … pc_artifacts.content, … (whole payload)
5x SELECT artifact_relations.…
4x SELECT pc_sources.…
2x SELECT pc_artifact_heads.revision WHERE … artifact_id = ?
2x SELECT pc_artifact_heads.<whole row>
1x UPDATE pc_artifact_heads SET revision = pc_artifact_heads.revision …

So one evidence reference is read from the database roughly fourteen times to establish one fact about
it: that it resolves.

Not in scope: that sixth line is the deliberate SQLite stand-in for SELECT … FOR UPDATE, documented
at builtin/persistence/processing_intents.py:71-74 ("Even an unmatched UPDATE opens the real write
transaction before the read, protecting first inserts"). It stays. Same for the per-reference
security.authorize(...) call at builtin/artifacts/merge.py:764 — that is an authorization boundary,
not a read.

Cause

  • _validate_evidence (builtin/review/service.py:1008) receives sources and artifacts and treats
    them differently: sources go through one batched require_for_generation, artifacts go through a
    per-item artifacts.get.
  • artifacts.get is the full loader, not an existence probe: it resolves the head, loads the exact
    revision, and loads lineage and publication provenance (persistence/artifacts.py:461 latest →
    _find_head, _load_lineage, _load_publication_provenance). That is where the 5x/5x/4x/2x/2x comes
    from, and every one of those rows is discarded by the caller.
  • A batched loader already exists in the same repository class and is used elsewhere:
    persistence/artifacts.py:429 get_many(connection, scope_id, refs), whose docstring reads "Load exact
    Revisions and ordered lineage with bounded batch queries".
  • The same discard-the-result pattern appears once more at builtin/artifacts/merge.py:763
    (await self.artifacts.get(connection, scope_id, ref) inside for ref in draft.artifacts:), and
    builtin/artifacts/merge.py:226 loops self.sources.get over one artifact's lineage sources while
    sources.get_many exists.

Proposal

  1. Batch the artifact existence check in _validate_evidence, mirroring what the sources line
    beside it already does. An id-only batched select (… WHERE artifact_id IN (…) AND family = …
    against the heads table, or get_many if the payload is genuinely needed downstream) turns 19
    statements per reference into a constant.
    On failure semantics: the current code already reports a single reference-agnostic message —
    raise InvalidCandidateError("evidence", "reference is not available in this scope") — and names no
    offending ref, so a batched version preserves it exactly. I checked for a test that pins per-reference
    behavior: the InvalidCandidateError assertions in the suite match other messages
    ("operation contract changed", "preserve the target objective", "protected package metadata"), not
    this one. If a reviewer would rather the batched error name the missing reference, that is a behavior
    change and should be decided deliberately, not slipped in.
  2. Apply the same to artifacts/merge.py:763, keeping the per-reference security.authorize call
    untouched.
  3. Add a statement-count ceiling for propose, in the style of test_statistics.py:553
    ("A selection must not cost one query per Scope; see issue bug(server): POST /v1/stats latency degrades sharply under low concurrency on file-backed SQLite #1599") and of test(recall): pin the prepare_context statement ceiling #2087, which pins the
    recall path. Nothing currently bounds this number, so it grows with the evidence limit.

No schema change, no migration, no new HTTP/MCP operation, no public contract change.

What I did not measure

  • No MySQL/OceanBase or seekdb run; SQLite only.
  • Whether the five pc_artifacts reads within a single get are themselves reducible — that would be
    a separate question about the artifact repository, and I have not looked into it.
  • The approve / reject / revise paths, inspect_evidence, multi-Scope proposals, and the
    sources= half of the same function (already batched).
  • Wall time. The claim is statement count, not latency.
  • The write path (capture → flush). I measured it and left it alone: its repeated intent selects and
    LIMIT 1 snapshot pins are each explained by an inline comment as deliberate concurrency primitives.

Related

#2075 (same amplification family, recall path; this issue is the review path) · #2079 (consolidates
recall, does not touch builtin/review/) · #2087 (statement-count ceiling for recall; same test shape
proposed here) · #1599 (the doctrine this follows) · #1321 → #1709 (precedent that an accepted fix here
looks like: projection write amplification on the Memory append path, reported as superlinear growth and
resolved incrementally) · #59 (where MAX_CANDIDATE_EVIDENCE and this loop were introduced, commit
4f68d2a6).

Activity

  1. AlexStocks commented on Oct 19, 2026

    @AlexStocks
    Contributor

    按 master e4efb39b 静态核对,报告的位置与不对称都成立,算术也自洽(612 = 4 + 19×32);我补三处报告未覆盖的事实,会影响批量化方案的选择,其余结论不需要改。

    已复核

    • builtin/review/models.py:MAX_CANDIDATE_EVIDENCE = 32,sources/artifacts 各受 max_length 约束,另有 len(sources)+len(artifacts) <= 32 的校验,因此上限确实是二者合计 32。
    • builtin/review/service.py::_validate_evidence:require_for_generation(sources) 批量,for artifact in artifacts: await self._artifacts.get(...) 逐条且不绑定结果。
    • persistence/artifacts.py:get() 非 for_update 时就是 get_many((ref,));get_many 已按 100 分批做行选择 + _load_lineage_many + _load_publication_provenance_many + decode_many。
    • artifacts/merge.py:for ref in draft.artifacts: 内 security.authorize + artifacts.get(ref) 的模式成立。
    • 全仓 tests/ 检索 reference is not available in this scope 命中 0,因此批量化不会打破任何钉住该文案的用例。
    • 相关 PR 面:perf(context): consolidate recall queries #2079(OPEN,head 91293e51)文件清单不含 builtin/review/;test(recall): pin the prepare_context statement ceiling #2087(OPEN)只改 tests/builtin/runtime/test_statistics.py,与你提议的第 3 项同形,可直接复用其形态。

    1. 19 条/引用不只来自被丢弃的那一处

    同一次 propose 里,只要 EvidenceResolver 存在(生产装配中 evidence 是构造参数),_validate_evidence 之后的 self._evidence.validate(...) → _validate_lineage → _read_review_artifact 也会逐引用调用 artifacts.get;而且当证据中出现 atomic-memory 时,validate() 会先跑一遍未加锁遍历,lock_heads 之后再跑一遍 locked=True。lock_heads 本身也是逐引用一次 UPDATE pc_artifact_heads——与你明细里的 1x UPDATE、2x heads 正好对应。

    所以「结果被丢弃」只对 _validate_evidence 的循环成立;resolver 那几遍的读取是被用的(lineage 遍历 + 摘要)。只把 _validate_evidence 改成批量,剩余成本仍随 K 线性增长。若目标是常数级,需要一并处理 _validate_lineage 的逐节点读取与 lock_heads 的逐引用加锁(后者可用一次 IN (...) + ORDER BY family, artifact_id 的范围加锁,代价是锁粒度变化,属于单独决策)。

    2. 用 get_many,不要用「只查 heads/ids 存在性」

    当前逐条 get 的可观察错误契约不只是「存在」:decode_many 在 row["content"] is None 时抛 RepositoryNotFoundError,被 _validate_evidence 转成 InvalidCandidateError("evidence", "reference is not available in this scope");_decode_artifact 还会经 _artifact_type(family) 拒未知 family、经 decode_content 校验存储体是否符合该 family 的 schema,并用 IdentityMismatchError 拦身份不一致。

    只查 heads 或 ids 会把「content 缺失 / 存储体不符合 schema / 身份不一致」的引用从 propose 期拒绝 变成 接受后到 approve 或读取阶段才失败。这不是性能问题而是契约变化,需要显式声明并补用例;get_many 保留上述全部语义,且本身就是批量实现,是这一处更安全的落点。

    3. 定级

    上限固定为 32 ⇒ 绝对成本有界(≤612 条/次 propose),不随数据量增长,也没有正确性问题,建议按 P2 处理,与 #2075 同族一并推进;第 3 项语句数上限的用例正是防止 MAX_CANDIDATE_EVIDENCE 被调大时静默劣化的那条锁。

    我没有覆盖的

    未复跑你的语句计数器(接受 19×K+4 的算术自洽与明细分类);未在 MySQL/OceanBase/seekdb 上验证;未覆盖 approve/reject/revise/inspect_evidence 与多 Scope 路径;_evidence is None 与已装配 resolver 两种配置下每引用的常数可能不同,需要按实际装配分别测一次才能给单一上界。

  2. Inference1 commented on Oct 20, 2026

    @Inference1
    ContributorAuthor

    Correction: the attribution here was incomplete

    This issue foregrounds the _validate_evidence loop and states that one evidence reference is read
    roughly fourteen times. The count is right; the attribution is not, so I am correcting it rather than
    editing the description.

    Wrapping ArtifactRepository.get and reading the calling frame, a proposal with 4 artifact refs issues
    20 loads:

    calls site
    8 (2 per ref) builtin/evidence/resolver.py:173 _read_review_artifact
    8 (2 per ref) builtin/evidence/resolver.py:417 _read_atomic
    4 (1 per ref) builtin/review/service.py:1035 _validate_evidence

    So the loop quoted in the Summary is one of five loads per reference, not the driver. The per-ref
    total is 19 statements, of which this loop accounts for 2.

    The two resolver visits are deliberate: the traversal key is (reference_key(ref), history_owner)
    (resolver.py:141), and _read_atomic uses history_owner to decide whether a merged or inactive entry
    is still acceptable as history. I tested memoizing the repeated load per (family, artifact_id, revision)
    inside _validate_lineage; the measured statement count changed by zero, because the two visits
    resolve different revisions, so that idea is dead rather than pending.

    What is actually left is a set of per-reference decisions — authorize, current head, lifecycle state —
    each batchable in principle, but batching them means restructuring the traversal rather than swapping a
    call. That is the design question worth a maintainer view, and it is the reason this issue should not be
    read as "replace one loop".

    #2091 takes the one change that is unambiguous on its own: that loop is ArtifactRepository.get, whose
    non-locking branch is literally get_many(..., (ref,))[0], so it was the batch API being invoked N times.
    It measures 612 → 550 statements at 32 refs and changes no error type or ordering.

  3. Inference1 commented on Oct 20, 2026

    @Inference1
    ContributorAuthor

    What is left after #2091 and #2136, and the design question behind it

    Two slices of this are now in flight or merged: #2091 batched the existence check in _validate_evidence,
    and #2136 stops latest from re-reading a revision the caller already holds when the head still selects it.
    Measured on 0da4436d, one experience.propose carrying K Atomic Memory evidence refs:

    K 1 4 16 32
    master today 23 74 278 550
    with #2136 21 66 246 486

    Per reference that is 17 → 15 statements. The rest does not look like a misplaced loop, so I want to
    describe it rather than cut it.

    Where the remaining per-reference work goes (K=4, wrapping ArtifactRepository methods and reading the
    calling frame; each latest is a head read plus a full revision load):

    calls per ref call why it is per-reference
    2 get from resolver.py:173 _read_review_artifact the traversal visits one ref twice, once as a root and once as another entry's history, and the two visits resolve different revisions
    2 latest from resolver.py:417 _read_atomic asks "is this the current head?" and "is this acceptable as history for owner X?" — half of these are the FOR UPDATE read that approval uses to serialize, which cannot be skipped
    2 AtomicMemoryStateRepository.get lifecycle state per ref, per visit
    4 _authorize_reference authorization per ref, per visit — measured, not inferred (K=1 issues 4 calls, K=4 issues 16)

    The authorization line is the largest single per-reference item in the count, and it is also the one where a
    batched form has to be a deliberate decision rather than a refactor: it is the boundary that decides whether
    each reference may be read at all.

    The two visits are deliberate: the traversal key is (reference_key(ref), history_owner) (resolver.py:141),
    and _read_atomic uses history_owner to decide whether a merged or inactive entry still counts as
    history. That is why memoizing the artifact load by (family, artifact_id, revision) measured zero
    change earlier — the visits genuinely need different rows.

    The design question. Batching these means making the walk level-synchronous: authorize a whole frontier,
    read its heads in one statement, read its states in one statement, then expand to the next frontier. The
    traversal is recursive today, so children are only known after their parents are read — you cannot know the
    full ref set up front.

    Three reasons I did not do that unilaterally:

    1. EvidenceResolver is shared by review, Dream, and handoff, so the blast radius is not this issue's path.
    2. Restructuring the walk changes error precedence when several references are invalid: today the first
      failure in visit order wins, and a frontier batch would have to pick an order deliberately.
    3. lock_memory paths interleave locking with reading (lock_heads, then locked reads). A batched frontier
      has to preserve that ordering or approval loses its serialization guarantee.

    If a maintainer thinks that direction is worth it, I am happy to prototype it behind a test that pins the
    current behavior first — the statement counts above make it easy to prove any change is real. If instead the
    answer is "this is the cost of per-reference decisions", that is a fine answer too, and I would close the
    loop by pinning the current numbers with a ceiling the way #2087 does for recall.

  4. PsiACE commented on Nov 23, 2026

    @PsiACE
    Member

    mostly down, if still have pref problem, pls track in another issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions