Repository navigation
feat(atomic-memory): add an opt-in one-pass processing mode - #2729
Conversation
frf12
left a comment
There was a problem hiding this comment.
@jasper-yl I reviewed 13ba05509 and compared the reproductions with master b64ee80b6. The two inline findings are worth fixing before merge: accepting unknown-field replies as empty operations, and accounting for the conversation input budget across steps and recheck branches.
The reproductions exercised Core and SQLite with scripted model replies, including the actual Pydantic AI generator paths. They establish the framework behavior for these inputs, not how often a live model produces them. No real-provider acceptance is claimed.
One separate, non-blocking note for custom dynamic authorization providers: if a memory was readable and writable when shown in step 2, but the provider denies its read access before step 3, the recheck authorizes only the newly recalled memories while resending the old memory in conversation history. I reproduced that resend; final publication was correctly denied. Ordinary read-only shares are excluded by the comparison admission's write check, so this is not a report of shared read-only memories being modified, or a reproduction under the default sharing model. The ordinary per-candidate control stopped before its next logical comparison in the same revocation scenario. This note is limited to checking the historical input reused by a later step; the existing authorization behavior of correction retries within a single generation call is outside this PR finding.
|
@frf12 thanks for the review. Both inline findings are fixed in 458cec0; details are in the two threads. On the non-blocking note about dynamic authorization providers: before each recheck request, the comparison authorization now covers the memories shown in step 2 together with the newly recalled ones, so a memory whose access was revoked after step 2 stops the window before it is resent. I have not added a test with a revoking provider for this. Two other things changed since
🤖 Generated with Claude Code |
|
Thanks for the updates. I rechecked
I also reviewed the step-1 change and did not find a new runtime issue. The checks covered a planned memory with details from two Sources, and separate entries sharing the same recall query; the complete plan reaches step 2 and the resulting Source references are preserved. These checks used Core/SQLite with scripted model responses; I have not independently rerun the model-quality benchmarks. Could you also address the two test typing errors in the current CI preflight? I reproduced both locally:
These two diagnostics come from the new test changes and are separate from the existing dashboard diagnostic on master. The earlier functional findings are resolved; these test typing errors are the remaining issue from this recheck. |
|
Full suite on 458cec0 ( The 31 failures are in 🤖 Generated with Claude Code |
|
@frf12 thanks for rechecking. Both test typing errors are fixed in 9f49eb1: the scripted conversation in I had only run 🤖 Generated with Claude Code |
| else pipeline.input_renderer(extraction_input) | ||
| ) | ||
| if not conversation.fits(evidence): | ||
| return None |
There was a problem hiding this comment.
[P2] 一次成型的回落分支没有任何诊断或日志
POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE=one_pass 时,_prepare_one_pass 在渲染后的 evidence 超出 input_tokens_limit 时直接 return None(第 684-685 行),调用方 _prepare 收到 None 后静默转入 per_candidate 路径(第 510-515 行),不留下任何记录。
影响:这是文档化的用户可见开关(docs/{en,zh}/docs/operate/configuration.md 都已登记),但开启后运维无法区分三种状态——one_pass 真的跑了、one_pass 因为窗口超限被跳过、开关根本没生效。同文件其余分支都通过 ProcessingDiagnostics / log_safely 记录(例如第 1192 行),唯独这条降级路径没有。窗口大小随内容变化,因此在默认日志级别下降级是按批次发生的、完全不可观测的。
建议:在该分支发出一次诊断(或 log_safely warning),携带估算 token 数与 input_tokens_limit;并在已有的 tests/e2e/test_atomic_memory_one_pass.py::test_window_over_the_step_two_budget_is_prepared_per_candidate(第 335 行)里断言这条记录存在,避免以后改动让它再次静默。
There was a problem hiding this comment.
Fixed in 422ad54. Each Source window processed in one_pass mode now emits one INFO atomic_memory.one_pass event through log_safely:
outcome: successwhen the window's operations came from the conversation.outcome: fallbackwhen the window was processed per candidate instead, withfallback_reason(entries_input_over_budgetfor step 1,operations_input_over_budgetfor step 2),estimated_input_tokens,effective_budgetandtoken_estimator_id.
So the three states can be told apart: a success event, a fallback event, or no event when the mode is not in effect (a window whose processing fails also emits none; the existing failure diagnostics report it). Both fallback points log, not only the one at this line. I used INFO rather than WARNING because the fallback is the documented behavior for a large window, not a fault, and it matches the existing atomic_memory.prefixed_extraction event. If you prefer WARNING for the fallback, I can change it. All fields are already in the allowlist, and the event carries no Source, memory, prompt or reply text.
Tests: test_window_over_the_step_two_budget_is_prepared_per_candidate now asserts the event and its budget fields, and there are two new ones for the step 1 fallback and for the success event. The event is documented in docs/{en,zh}/docs/operate/observability.md.
中文:已在 422ad54 修复。one_pass 模式下每个窗口输出一条 INFO 级别的 atomic_memory.one_pass 事件:success 表示由这一次对话得出;fallback 表示改用了逐候选流程,并带上超出的是哪一步、估算输入和生效上限。第 1 步和第 2 步两处回落都会记录。级别用 INFO 是因为回落是文档写明的正常行为,与现有的 atomic_memory.prefixed_extraction 一致。
🤖 Generated with Claude Code
frf12
left a comment
There was a problem hiding this comment.
Rechecked 422ad5436. The earlier output-validation, budget-accounting and custom-Provider authorization findings are resolved, as are the two test typing errors. I found no additional blocking issue in the step-1 adjustment or the new preparation/fallback logging. Approving, with one small non-blocking documentation note below.
The latest CI is still blocked by the existing dashboard type diagnostic on master.
| input exceeded `atomic_memory_input_tokens_limit` and the window was processed per candidate instead; | ||
| `fallback_reason` is then `entries_input_over_budget` (step 1) or `operations_input_over_budget` (step 2), | ||
| `estimated_input_tokens` is the estimated input of that request, `effective_budget` the limit in effect, and | ||
| `token_estimator_id` the estimator used. A window whose processing fails emits no such event; processing failure |
There was a problem hiding this comment.
Small documentation note (non-blocking): this event describes preparation or the choice to fall back, so a window that ultimately fails can still have emitted it. For example, fallback is logged before per-candidate processing runs, and success is logged after preparation but before publication; a later failure does not remove that earlier event. It would help to clarify this in both language versions rather than saying that a failed window emits no event. The current event placement and INFO level look reasonable; this is only a wording clarification.
There was a problem hiding this comment.
Thanks, you are right. Reworded in 5bb429b in both locales: the event reports how the window was prepared, not that it was published. fallback is logged before per-candidate processing runs and success before publication, so a window that fails afterwards has still emitted it; only a window that fails during the conversation emits none.
🤖 Generated with Claude Code
| result = workset.copy() | ||
| evidence = {item.evidence_id: item for item in extraction_input.evidence} | ||
| created: list[str] = [] | ||
| for ordinal, operation in enumerate(_parse(reply, OnePassOperations).operations): |
There was a problem hiding this comment.
[P2] Require a decision for every step-one entry
A nonempty step-one list followed by {"operations":[]} or {} passes this validator, so publication advances the Source cursor without deciding any listed fact. Track entry identities and require one explicit decision per entry, returning incomplete replies for correction before consuming the window.
There was a problem hiding this comment.
@hireview001 Thanks for looking into this. We don't consider this first finding a blocker for the PR, and I would like to explain the baseline and scope behind that decision.
We exercised ordinary extraction on the master baseline used for this review (b64ee80b6). Both {"candidates":[]} and {} produce no memories, skip reconciliation, and advance the Source cursor without another model call to confirm the empty result. The risk that a model may omit something worth retaining, without the framework being able to distinguish omission from a deliberate decision, therefore already exists on the baseline.
In one-pass, step 1 is a candidate plan; step 2 decides what is ultimately retained. A nonempty plan alone does not establish that the final result must contain memories. From the checks so far, we have not found evidence that accepting a valid empty result materially lowers the baseline for this risk. The earlier issue where an incorrectly shaped reply was silently accepted as empty was a different case, and has been fixed.
Requiring an explicit decision for every planned entry could be an enhancement, but it has a cost: per-entry explanations add output, and treating an empty result as incomplete can trigger additional correction requests. It does not necessarily turn the flow into a separate model call per entry, but it is not a free check either. The agreed goal here is to reduce memory-processing cost while preserving the existing processing semantics; a stronger guarantee against model omissions is not an additional acceptance condition for this PR. Without evidence of a new regression and a demonstrated benefit from the extra check, we would prefer to discuss that stronger guarantee separately.
I also wanted to share a scope concern from a few PRs we have reviewed together:
- In feat(plugins): reload plugin directories, upgrade plugin data, and expose plugin routes as OpenAPI and MCP tools #2638, duplicate MCP tool names and the reserved
body/queryparameter names had explicitly been accepted as tutorial constraints, and that scope had been reviewed and approved. They were subsequently raised as P2 requests for framework validation or design changes. Those may be useful improvements, but revisiting the agreed acceptance scope needs an explanation of what new evidence warrants it. See the accepted scope and the later finding. - In feat(gateway): extract Atomic Memory over the agent's cached conversation prefix #2435, we had agreed to preserve the complete Source and use the prefix when it was cheaper. A subsequent suggestion still proposed an additional prefix fallback condition for content missing from capture. The evidence gap deserved a fix, but an added fallback gate could also reduce the benefit the feature was intended to provide, so it needed to be considered alongside the already chosen approach. See the agreed approach and the later finding.
Individually, these suggestions can look like stronger safeguards. Taken together, though, they can raise a feature PR's acceptance bar above the master baseline or the scope already agreed, with additional complexity and cost.
For future comments, could we take the PR's goal, existing discussion, and other reviewers' feedback into account before adding a new requirement, and make clear what regression it addresses or which accepted tradeoff it changes? New defects, materially amplified risks, and violations of an explicit contract should still be fixed. Stronger general guarantees can be identified as non-blocking improvements and discussed separately. That would help us keep reviews focused on the changes this PR needs to make.
There was a problem hiding this comment.
@hireview001 thanks for the finding. Before deciding, I checked how often this happens in the evaluation runs behind this PR, and what a fix would cost.
What the runs show. The runs kept token usage per model call, not reply text, so I measured the visible reply length (completion tokens minus reasoning tokens). {} or {"operations":[]} is a few tokens.
| Evaluation | One-pass model calls | Visible reply ≤ 20 tokens | Shortest visible reply |
|---|---|---|---|
| Coding sessions (5 repetitions) | 173 | 0 | 58 tokens |
| LoCoMo (10 conversations) | 786 | 0 | 95 tokens |
No call in either evaluation returned an empty reply, in step 1 or step 2. This method cannot see a reply that decides some entries and omits others; counting that needs the entry and operation counts recorded in a new run.
What a fix would be. When step 1 listed entries and step 2 returns no operation, return the reply to the model for correction; an entry that an existing memory already covers is a noop. It does not change the prompt or the reply format. On the data above the rule would never have fired, so it costs nothing in these runs and also has no measured benefit. Requiring one identified decision per entry is a larger change to the reply format and would need the evaluation rerun.
Given @frf12's point that master accepts an empty extraction the same way, and that this was not observed, do you still see the empty-reply check as needed in this PR? If so I can add the small check above; otherwise I would leave it as a possible follow-up.
Your second finding (two rechecked memories revising the same target) reproduces; I will answer it in its own thread.
中文:评测运行只保存了每次调用的 token 用量。按可见回复长度统计,编程会话 173 次、LoCoMo 786 次单次整理调用中没有一次空回复(最短分别为 58 和 95 token);只漏掉部分条目的情况这种方法统计不到。修复可以很小:第 1 步有条目而第 2 步没有任何操作时退回纠正,不改提示词和回复格式,在上述数据里不会触发。考虑到 master 同样接受空抽取、且评测中未出现,想请你判断这个检查是否仍有必要放进本 PR。第二条已复现,在对应位置另行回复。
🤖 Generated with Claude Code
| AtomicMemoryReconciliationOutput( | ||
| action=operation.action, | ||
| compared_ids=tuple(item.key for item in related), | ||
| target_ids=tuple(dict.fromkeys(result.resolve(target) for target in targets)), |
There was a problem hiding this comment.
[P2] Preserve earlier updates to shared targets
When two creates recall the same unseen memory, both recheck revisions use its original body, but the second target resolves to the first revision's result and overwrites it, losing the first update. Coordinate shared targets or reject conflicting replacements for correction before publishing; step two permits the same target reuse.
There was a problem hiding this comment.
@hireview001 @hidb4ai thanks, this reproduces here as well, in step 3 and by the same mechanism in step 2. A fix is ready locally and is being evaluated before I push it, because it changes the flow instructions:
- Step 2 and step 3 reject a reply in which a second operation revises or merges a memory that an earlier operation of the same reply already wrote; the reply goes back to the model for correction and nothing is published.
- The instructions state the rule: one reply writes an existing memory at most once; when several entries change it, one operation states all their facts and the others return noop with that target.
- In step 3 a memory recalled by several created memories carries one label instead of one per created memory.
Regression tests cover both steps (separate revisions are rejected and the store is unchanged; the combined form publishes both facts). I am rerunning the coding and LoCoMo evaluations with the changed instructions to confirm that memory granularity and coverage stay where they were, and will push the fix together with the rebase onto current master once the run finishes.
🤖 Generated with Claude Code
There was a problem hiding this comment.
@hireview001 @hidb4ai fixed in 9bfd6e4, which is also rebased onto current master (this resolves the conflict).
What changed
- Step 2 and the re-check each track the existing memories a reply has already written. A second
reviseormergethat targets one of them is rejected like any other rule violation: the workset copy is discarded and the model is asked to state all the facts in one operation and returnnoopwith that target for the others. If correction attempts run out, the window is not consumed and nothing partial is published.noopdoes not write, so it is not limited. - In the re-check, a memory recalled by several created memories now has one label, so the model can see they point at the same memory.
- Regression tests for both steps:
test_two_operations_revising_one_shown_memory_are_rejectedandtest_two_rechecked_memories_revising_one_memory_are_rejected. Both fail without the check.
What the evaluation showed
I first also wrote the rule into the flow instructions, and evaluated both variants on the coding and LoCoMo runs behind this PR:
| Before | Rule in instructions + check | Check only (this commit) | |
|---|---|---|---|
| LoCoMo J | 0.826 | 0.822 | 0.823 |
| LoCoMo memories / mean chars | 1031 / 335 | 877 / 409 | 1026 / 343 |
| Coding substantive facts missing | 6.0% | 3.7% | 4.2% |
| Cost (coding / LoCoMo) | 2.26M / 8.27M | 2.13M / 7.97M | 2.24M / 8.30M |
- With the rule in the instructions, LoCoMo stores had 15% fewer and 22% longer memories: the sentence nudged the model toward merging in every window. So the instructions are unchanged and the rule reaches the model only as a correction.
- In the check-only run (about 1050 model calls) the check fired 0 times. The overwrite is real but did not occur in these runs, and the check adds no calls in normal operation.
- Limit: because it never fired, the model's behaviour after a rejection is covered only by the tests with scripted replies.
The design document (§3.3, §3.4, §6.2, §6.3) and the PR description are updated.
已在 9bfd6e4 修复,并已变基到当前 master。第 2 步和复核都会拒绝同一次回复里对同一条已有记忆的第二次 revise / merge,并要求模型用一个操作写全事实、其余以 noop 指向该记忆;复核中同一条已有记忆只有一个标签。把规则写进流程指令会让 LoCoMo 的记忆少 15%、长 22%,因此指令不变,规则只在违反时告知模型。只加检查的评测中(约 1050 次调用)检查触发 0 次,得分和成本不变。
🤖 Generated with Claude Code
|
I have approved this PR. However, there are some file conflictions. |
hidb4ai
left a comment
There was a problem hiding this comment.
Reviewed 5bb429b3ce7f51fdd77d31d3b03416c740fb3f92. Requesting changes for the existing shared-target overwrite finding, without opening a duplicate thread.
I reproduced it through Core's Source processing and SQLite readback in both step 2 and step 3: the stored memory initially says budget 100 and owner platform; new evidence changes the budget to 200 and owner to reliability. Two revisions of the same target, each based on the shown original, are accepted. The final persisted memory says budget 100 and owner reliability, and the Source cursor advances to 2. The second replacement silently discards the first accepted update. Shared-target operations must preserve the combined changes or be rejected for correction before publication. This uses scripted model replies; it does not establish the frequency with a live provider.
The opt-in conversation approach and reuse of the publication path are reasonable. I am not treating the separately discussed empty-result policy as an additional blocker without evidence of a regression against the accepted baseline. The branch also currently conflicts with master in src/powercontext/builtin/inference/pydantic_ai.py.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…he budget Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…esidual risk of splitting Co-Authored-By: Claude <noreply@anthropic.com>
… the budget Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
Co-Authored-By: Claude <noreply@anthropic.com>
…pass processing Listing one entry per fact made step 2 write one memory per fact: three times as many memories as per-candidate processing, each half as long. Step 1 now lists the memories to write and names the facts each must state. Co-Authored-By: Claude <noreply@anthropic.com>
…et each request by what it sends A reply with unrecognized top-level fields was read as an empty result and consumed the window. The input estimate of a later step missed the model replies it resends, and split rechecks counted each other's messages. Rechecks also resent step 2's memories without checking their authority again. Co-Authored-By: Claude <noreply@anthropic.com>
…as text Co-Authored-By: Claude <noreply@anthropic.com>
…ll back Co-Authored-By: Claude <noreply@anthropic.com>
… publication Co-Authored-By: Claude <noreply@anthropic.com>
…s reply Co-Authored-By: Claude <noreply@anthropic.com>
5bb429b to
9bfd6e4
Compare
hidb4ai
left a comment
There was a problem hiding this comment.
Rechecked 9bfd6e4afc5a5630ccb12a3dad3dd89c8cabf224. The shared-target overwrite is fixed: both previous Core/SQLite reproductions now reject the reply and leave the original store unchanged. The new regression tests also verify that one combined revision plus noop retains both facts. I found no additional blocking correctness issue in the fix or the rebase. This validation uses scripted model replies; I have not independently rerun the provider-quality evaluations.
CI remains a merge gate. The website failure is the pre-existing langchain.md#配置连接与-scope link in the Chinese Deep Agents guide, while the target heading uses 和; both files are identical to base 1840db817. The usage-recorder test also failed locally in the combined run (125 passed, 1 skipped, 1 failed), then passed alone on both head and base. Its test and recorder implementation are unchanged by this PR, so I am not attributing that intermittent failure to this change. Please obtain a green required CI run before merging.
I am withdrawing my earlier change request because its correctness finding is resolved. This is not an approval: the PR adds a runtime configuration contract and Python conversation/pipeline interfaces, which require explicit review under the requested approval criteria.
The shared-target overwrite is fixed and verified on 9bfd6e4. Withdrawing the earlier correctness block; required CI and explicit interface review remain separate merge gates.
Which issue or RFC does this PR close?
No issue or RFC yet. The design is in this PR:
docs/zh/design/atomic_memory_one_pass_design.md. I am opening it to get your opinion on the direction before going further; an RFC can follow if you want one.Rationale for this change
Goal: cut the model cost of writing Atomic Memory without losing facts.
Today a Source window is processed per candidate: one extraction call, then for every candidate one or more reconciliation calls, each resending the candidate's evidence and its related memories. Almost none of that input is served from the provider's prefix cache (1% in the measurements below), and each candidate's text is generated twice.
This PR adds an opt-in mode,
one_pass, that handles a window in one model conversation:Each step continues the previous request, so the instructions and evidence are a shared prefix that the provider can cache.
Measured effect. Both modes ran on the same Core build with only the mode setting changed. Cost units: uncached input token 1, cached input 0.1, output 8, counted over the Atomic Memory write path.
Coding sessions (15 consecutive turns over three repositories, 5 repetitions, blind review of the final store against 43 substantive reference facts per repetition):
per_candidateone_passPaired by repetition and fact: 5 missed only by
per_candidate, 5 missed only byone_pass.LoCoMo (10 conversations, 1540 questions, answers from the top 10 memories that Core retrieves):
per_candidateone_passPaired by question: 80 correct only with
per_candidate, 119 only withone_pass(sign test p=0.007).In short: cost is 31% (coding) and 20% (LoCoMo) of the current flow, the store has about the same number and size of memories, coding fact coverage is the same, and LoCoMo accuracy is not lower.
Limits.
one_passleaves more duplicates in the coding store (19 vs 6).What step 1 lists matters. An earlier form of this flow listed one entry per fact. The model then wrote one memory per fact: 270 memories of 282 characters in coding and 2192 of 166 in LoCoMo, so the top 10 results carried about half the text. Coverage and J were level with
per_candidate, but the store was fragmented. Asking step 2 to group by topic, or widening revise, over-merged instead (coding signal 52%). Listing memories with their facts in step 1 gave the granularity of the current flow. The design document has the numbers for each alternative.What changes are included in this PR?
builtin/artifacts/atomic_memory/one_pass.py: the flow instructions, the reply formats, and applying a reply to anAtomicMemoryWindowWorkset. Every operation goes through the existingworkset.apply()andvalidate_extraction_outputrules.AtomicMemorySourceWindowProcessor._preparebranches to the one-pass conversation when the mode isone_pass. Publishing, the write gate, provenance (sources), read dependencies and conflict retries are the existing code.atomic_memory_input_tokens_limit, the window is processed by the per-candidate flow. Step 2 is never split. A re-check that exceeds the budget is split by created memory.PydanticAIConversationGenerator(ConversationTurn/ConversationReply): a plain-text conversation generator. The existing structured generator writes the output schema into the instructions, so two calls with different schemas cannot share a prefix. It reuses the existing timeout, request limit, error mapping and usage reporting.atomic_memory.extractinstructions and append a Scope's customatomic_memory.reconcileinstructions. No new prompt key.Are there any user-facing changes?
One new Server setting, documented in
docs/{en,zh}/docs/operate/configuration.md:POWERCONTEXT_SERVER_RUNTIME_ATOMIC_MEMORY_PROCESSING_MODE=per_candidate(default) |one_passThe default is unchanged and the default path does not enter the new code. No HTTP API, OpenAPI, persisted format or prompt key changes. A deployment that injects its own
AtomicMemoryGenerationPipelinemust provideconversationto useone_pass; otherwise processing a window raisesInferenceUnavailableError.How was this change tested?
tests/e2e/test_atomic_memory_one_pass.py(create then revise, noop, merge, re-check, rejected reply publishes nothing, two operations writing one existing memory are rejected in step 2 and in the re-check, over-budget window falls back to per-candidate, default mode never starts a conversation) and a conversation-generator test intests/builtin/inference/test_pydantic_ai.py(shared prefix and in-step correction).uv run pytest -q -n 3on this branch: 10755 passed, 1104 skipped, 31 failed. The 31 failures are intests/test_cli_kimi_code.py,tests/test_cli_zcode.pyandtests/test_installation.py; the test machine has no Node or Kimi CLI, and the same 31 fail there on unmodifiedmaster.uv run ruff check,uv run ruff format --check,uv run ty check: clean.master, with the flow instructions that are in this PR; at that pointatomic_memory_input_tokens_limitdefaulted to 24000. It has not been rerun after the rebase.tests/e2e/test_atomic_memory_one_pass.pyandtests/builtin/inference/test_pydantic_ai.py(84 passed), ruff and ty; CI runs the full suite.AI usage statement
Implemented and evaluated with Claude Code (Claude), with the design directed by the author.
🤖 Generated with Claude Code