Repository navigation
Description
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 onlyThis 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) receivessourcesandartifactsand treats
them differently: sources go through one batchedrequire_for_generation, artifacts go through a
per-itemartifacts.get.artifacts.getis 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)insidefor ref in draft.artifacts:), and
builtin/artifacts/merge.py:226loopsself.sources.getover one artifact's lineage sources while
sources.get_manyexists.
Proposal
- Batch the artifact existence check in
_validate_evidence, mirroring what thesourcesline
beside it already does. An id-only batched select (… WHERE artifact_id IN (…) AND family = …
against the heads table, orget_manyif 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: theInvalidCandidateErrorassertions 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. - Apply the same to
artifacts/merge.py:763, keeping the per-referencesecurity.authorizecall
untouched. - Add a statement-count ceiling for
propose, in the style oftest_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_artifactsreads within a singlegetare themselves reducible — that would be
a separate question about the artifact repository, and I have not looked into it. - The
approve/reject/revisepaths,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 1snapshot 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).
Metadata
Metadata
Assignees
Labels
Type
Projects
- StatusShow more project fieldsDone
Activity
AlexStocks commentedon Oct 19, 2026
按 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,因此批量化不会打破任何钉住该文案的用例。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 两种配置下每引用的常数可能不同,需要按实际装配分别测一次才能给单一上界。Inference1 commentedon Oct 20, 2026
Correction: the attribution here was incomplete
This issue foregrounds the
_validate_evidenceloop and states that one evidence reference is readroughly fourteen times. The count is right; the attribution is not, so I am correcting it rather than
editing the description.
Wrapping
ArtifactRepository.getand reading the calling frame, a proposal with 4 artifact refs issues20 loads:
builtin/evidence/resolver.py:173_read_review_artifactbuiltin/evidence/resolver.py:417_read_atomicbuiltin/review/service.py:1035_validate_evidenceSo 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_atomicuseshistory_ownerto decide whether a merged or inactive entryis 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 visitsresolve 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, whosenon-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.
perf(review): batch the candidate evidence artifact existence check (#…
Inference1 commentedon Oct 20, 2026
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
latestfrom re-reading a revision the caller already holds when the head still selects it.Measured on
0da4436d, oneexperience.proposecarrying K Atomic Memory evidence refs:mastertodayPer 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
ArtifactRepositorymethods and reading thecalling frame; each
latestis a head read plus a full revision load):getfromresolver.py:173_read_review_artifactlatestfromresolver.py:417_read_atomicFOR UPDATEread that approval uses to serialize, which cannot be skippedAtomicMemoryStateRepository.get_authorize_referenceThe 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_atomicuseshistory_ownerto decide whether a merged or inactive entry still counts ashistory. That is why memoizing the artifact load by
(family, artifact_id, revision)measured zerochange 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:
EvidenceResolveris shared by review, Dream, and handoff, so the blast radius is not this issue's path.failure in visit order wins, and a frontier batch would have to pick an order deliberately.
lock_memorypaths interleave locking with reading (lock_heads, then locked reads). A batched frontierhas 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.
perf(evidence): reuse the loaded revision when the head still selects…
PsiACE commentedon Nov 23, 2026
mostly down, if still have pref problem, pls track in another issue