Skip to content

perf(atomic-memory): compact repeated bodies in additional projections - #2163

Merged
hidb4ai merged 3 commits into
oceanbase:masterfrom
jasondeng1997:perf/atomic-memory-evidence-dedup
Oct 22, 2026
Merged

hidb4ai merged 3 commits into
oceanbase:masterfrom
jasondeng1997:perf/atomic-memory-evidence-dedup

Conversation

@jasondeng1997

@jasondeng1997 jasondeng1997 commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Which issue or RFC does this PR relate to?

Related to #2137; extends the Source evidence compaction introduced by #2139.

Rationale for this change

Additional named Source projections can repeat the body already supplied to Atomic Memory extraction. Compact these copies while preserving independent facts, provenance, and the existing handling of native and observed Sources.

What changes are included in this PR?

  • Remove an additional projection's content only when its canonical text matches the actual extraction body; retain its other fields and any different content.
  • Remove the consumed text-evidence projection only when its value equals the selected evidence object.
  • Share canonical comparison across content and wire carriers, retaining values that cannot be canonicalized.
  • Recognize native adapter reads that return a plain string, and retain stored content when the adapter supplies a different body.
  • Preserve the existing compaction of observed wire content and unprojected payloads.
  • Cover body deduplication, independent projection facts, differing adapter reads, and provenance through the extraction input.

Are there any user-facing changes?

Extraction inputs contain fewer repeated body copies. No public API, database schema, migration, or persisted Source format changes.

How was this change tested?

  • Focused Atomic Memory, extraction diagnostics, generation merge, wire evidence, flush concurrency, recall sufficiency, and statistics tests: 157 passed, 3 skipped.
  • SQLite submission and flush probes confirm that independent payload/projection facts and differing native adapter content survive, while a structured wire body appears once.
  • Ruff lint and formatting checks pass.
  • Full type checking and the Pydantic AI integration type check pass with --extra-search-path tests/e2e/cross_host_work_continuity/fixtures.
  • make check passes its release, lock, integration, lint, and formatting checks. Its type-check hook encounters the existing unresolved task import in tests/e2e/cross_host_work_continuity/fixtures/verify.py:23; the same error reproduces on upstream master without the additional fixture search path.

Validation commands:

.venv/bin/python -m pytest -q -o addopts='' \
  tests/builtin/artifacts/atomic_memory/ \
  tests/test_extraction_capabilities.py \
  tests/e2e/test_extraction_diagnostics.py \
  tests/e2e/test_atomic_memory_generation_merge.py \
  tests/e2e/test_atomic_memory_wire_evidence.py \
  tests/e2e/test_atomic_memory_flush_concurrency.py \
  tests/e2e/test_recall_sufficiency_gate.py \
  tests/builtin/runtime/test_statistics.py
make check
.venv/bin/ty check --extra-search-path tests/e2e/cross_host_work_continuity/fixtures
.venv/bin/ty check --extra-search-path tests/e2e/cross_host_work_continuity/fixtures integrations/pydantic-ai/src

AI usage statement

Codex assisted with conflict resolution, regression validation, and the PR description.

`project_atomic_memory_evidence` gave the model two independent body carriers: `content`, and a
full dump of the stored Source in `source_metadata`. Every Source body therefore arrived twice, and
three times for an observation, where `payload.content` and the text-evidence projection repeat it
again. Those copies spend the input token budget on text the model has already read, so a batch
crosses `atomic_memory_input_tokens_limit` and `_reduce_window()` bisects it instead of extracting.

Compact the metadata at the projection site. Only values that repeat the body are removed:
`ContentSource.content`, `payload.content`, the `content` key inside a projection value, and
`wire_content` when it is the same value as the body. Every other provenance key stays, including
`metadata`, `payload.metadata`, `definition_version` and `working_note`.

One 3,982-character Source, measured on the complete extraction input with the character estimator:
2,142 -> 1,143 tokens for a native Source (46.6% less) and 3,243 -> 1,195 for an observation (63.2%
less). At 24,000 tokens that is 11 -> 20 Sources per window for the HTTP capture path.

Source storage, the journal and Artifact lineage are untouched; this changes what the prompt sees.
Copilot AI balanced review requested due to automatic review settings October 21, 2026 08:37

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

if not isinstance(value, SourceObservation):
body = dumped.get("content")
dumped.pop("content", None)
if body is not None and dumped.get("wire_content") == body:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] 结构化 wire_content 仍把同一份正文送两遍,标题的「每份 Source 只送一次」只对字符串 wire 成立

:146 的判据是 dumped.get("wire_content") == body,即 dict 与 str 比较。真实写入路径是
records.create_source 的 content = _canonical_source_text(content)(RFC 8785 规范化 JSON)+
wire_content = <原始 JsonValue>;集成侧传的是结构化 JSON,因此这里恒为 False,整个 wire_content
连同其中的正文一起留在 source_metadata 里,而 content 已经是同一段文本的规范化 JSON。

探针 probes/probe_structured_wire.py(同一 Head 树,走 project_atomic_memory_evidence 公开入口后
AtomicMemoryExtractionInput.model_dump_json() 计数):

  • wire_content = {"text": <body>, "kind": "note"} ⇒ 正文出现 2 次,input 738 bytes(wire_content 保留);
  • wire_content = <body>(字符串)⇒ 1 次,553 bytes;
  • wire_content = {"messages": [...]}(不含正文)⇒ 0 次,580 bytes。

test_wire_bytes_that_carry_something_else_survive 用的正是第三种,所以用例自洽,但覆盖不到真实采集形态。

建议:按「wire 的规范化文本是否等于 content」判定(复用 _canonical_source_text / rfc8785.dumps),
而不是比较对象与字符串;并补一条 {"text": <body>, ...} 结构性 wire 的用例。

另需协调:#2139 修改的是同一个 project_atomic_memory_evidence 与同一插入点,去重边界与本 PR 不一致
(本 PR 无条件删 payload.content,并对任意 projection 的 value.content 一律剥离;#2139 仅在等于投影正文时删、
其余 projection 完整保留;结构化 wire_content 反而是 #2139 删、本 PR 保留:同场景实测 #2139 为 1 次 / 586 bytes)。
两者只能合入其一,后合的一方会在同段落必然冲突,建议在 PR 正文写明与 #2139、Issue #2137 的协调结论。

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8083f5f — thank you, this was a real hole and the reproduction is exact.

You were right that the comparison was dict-vs-string, so it was False for every structured capture and the carrier survived in exactly the shape real integrations produce. wire_content is now compared by canonical text rather than by object identity:

if _repeats(dumped.get("wire_content"), body_text):   # _text_of == _canonical_source_text
    dumped.pop("wire_content", None)
    dumped.pop("wire_content_present", None)

_text_of returns a string as itself and canonicalises anything else through records._canonical_source_text — the same encoding the write path used to derive the stored content from the wire — so a string wire and {"text": <body>, "kind": "note"} now answer alike, while {"messages": [...]} still does not match and stays.

Added test_a_structured_wire_body_that_encodes_the_body_is_also_redundant, which mirrors the writer path (content=_canonical_source_text(wire)) instead of hand-writing the stored text, so it cannot drift from what capture actually stores. Re-measured with your probe shape: wire_content = {"text": <body>, "kind": "note"} now serialises the body once, 3,147 → 1,125 tokens on the same 3,982-character Source.

On the #2139 coordination: agreed, and I have written the conclusion into the PR body rather than leaving it between threads. The short version is that both PRs now apply the same rule and they agreed on content, payload.content, the structured wire_content, and dropping the consumed text-evidence projection while keeping unrelated projections. The only remaining difference is narrow — this PR also removes a content key inside another projection's value when that value is the body text, where #2139 keeps other projections whole. That is a strict subset of the same safe rule, not a different boundary. They are still alternatives for one slot, so one of the two has to be chosen; I am fine with either and will rebase whichever survives.

The change that made them converge is in the other review thread on this same file: a carrier is now removed only when it is provably the same text, so the "unconditional deletion" of payload.content and of every projection's value.content is gone.

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please preserve distinct Source evidence during compaction. The current implementation can omit facts from extraction while still advancing the Source cursor.

continue
projected = projection.get("value")
if isinstance(projected, dict):
projection = {**projection, "value": {key: item for key, item in projected.items() if key != "content"}}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Preserve content that differs from the extraction body

This drops content from every projection by name, and line 153 does the same to payload.content, even when those values differ from the selected text evidence. With a valid registered Source whose text projection is Use canary deployment., raw content is The deployment region must be eu-west-1., and another projection's content is The deployment budget is 37 units., submitting to SQLite and then flushing removes both independent facts from the extractor input while advancing the cursor to 1. Both facts survive at base 88899876.

Only remove values proven redundant with the actual extraction body. The native branch at line 145 needs the same safeguard when adapter.read() returns a different value.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8083f5f, and your example is now a test.

The by-name deletion is gone. payload.content and a projection's value.content are removed only when the value's canonical text equals the body the extraction input actually carries, so your case keeps all three:

content          = "Use canary deployment."                    (text projection)
payload.content  = "The deployment region must be eu-west-1."   kept
projection value = "The deployment budget is 37 units."         kept

test_a_projection_content_that_differs_from_the_body_is_not_a_copy builds exactly that Source and asserts each of the three texts appears once in the serialized AtomicMemoryExtractionInput — dropping any of them would have been silent data loss, since the cursor advances either way.

The native branch got the same guard: the body it compares against is now the resolved content, not the stored field, so test_a_read_that_disagrees_with_the_stored_body_keeps_both keeps source_metadata.content whenever adapter.read() returns something different. _compact_source_metadata takes the body as a parameter for that reason (body: JsonValue) instead of reading it back out of the dump.

Nothing changed on the saving side: a carrier that is the body is still dropped, including a structured wire_content whose canonical text is the body, which the previous value-vs-string comparison silently missed.

@AlexStocks AlexStocks added the 1.4.1 v1.4.1 release tracking label Oct 21, 2026
…e text

Two ways the compaction could remove evidence instead of a duplicate:

A projection's `content` was stripped by name. A Source may project a *different* fact under
that key — one text projection says "Use canary deployment.", the payload says "The deployment
region must be eu-west-1.", another projection says "The deployment budget is 37 units." — and
removing them by name took both of those out of the extractor's input while the cursor still
advanced past the Source. The native branch had the same hole when the adapter read disagrees
with the stored content.

`wire_content` was compared to the body as `dumped.get("wire_content") == body`, a dict against
a string, which is False for every structured capture. Real integrations submit JSON, so the
whole wire body — the body included — stayed in the prompt and the duplicate this PR exists to
remove was still there.

Both now go through one test: the value is removed only when its canonical text equals the text
the extraction input actually carries. That is the same encoding `records.create_source` uses
to derive `content` from `wire_content`, so a string wire and the structured body that encodes
it answer alike, while a value that says something else is kept.

Measured on the complete extraction input for one 3,982-character Source: 2,130 -> 1,130 tokens
for a native source with a string wire (-46.9%), 3,147 -> 1,125 for a structured wire that was
never deduplicated before (-64.3%), and 4,248 -> 1,204 for an observation with a text
projection and a second projection (-71.7%). At 24,000 tokens that is 11 -> 21 Sources per
window, and 5 -> 19 for the observation.
Copilot AI balanced review requested due to automatic review settings October 22, 2026 06:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

Copilot AI balanced review requested due to automatic review settings October 22, 2026 09:02

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

An organization owner can choose the repository organization as the billing source for reviews requested by members with a paid Copilot license. Learn about Copilot code review billing.

@hidb4ai hidb4ai changed the title perf(atomic-memory): send each Source body once to extraction perf(atomic-memory): compact repeated bodies in additional projections Oct 22, 2026

@hidb4ai hidb4ai left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@hidb4ai
hidb4ai merged commit 8b54bc7 into oceanbase:master Oct 22, 2026
10 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

1.4.1 v1.4.1 release tracking

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants