Repository navigation
perf(atomic-memory): stop duplicating source text in extraction input to reduce token consumption #2139
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
perf(atomic-memory): stop duplicating source text in extraction input to reduce token consumption #2139
Changes from 4 commits
908d25d
0aad06e
257b506
7d44342
09579eb
b5ac929
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -26,9 +26,10 @@ | |
| from powercontext.builtin.artifacts.memory.prompts import MemoryExtractionProfile | ||
| from powercontext.builtin.inference import InvalidInferenceOutputError, StructuredGenerator, TokenEstimator | ||
| from powercontext.builtin.persistence.sources import SourceRepository, StoredSource | ||
| from powercontext.sources import TEXT_EVIDENCE_PROJECTION_KEY, SourceObservation, SourceRef, TextEvidence | ||
| from powercontext.sources import TEXT_EVIDENCE_PROJECTION_KEY, Source, SourceObservation, SourceRef, TextEvidence | ||
|
|
||
| _JSON = TypeAdapter(JsonValue) | ||
| _TEXT_EVIDENCE_KEY = TEXT_EVIDENCE_PROJECTION_KEY.model_dump(mode="json") | ||
|
|
||
| if TYPE_CHECKING: | ||
| from powercontext.builtin.artifacts.atomic_memory.reconciliation import ( | ||
|
|
@@ -129,6 +130,54 @@ async def extract(self, value: AtomicMemoryExtractionInput) -> tuple[AtomicMemor | |
| return output.candidates | ||
|
|
||
|
|
||
| def _duplicates_body(value: JsonValue, body: JsonValue) -> bool: | ||
| """Whether a metadata value is exactly the evidential body text.""" | ||
|
|
||
| return isinstance(body, str) and value == body | ||
|
|
||
|
|
||
| def _is_text_evidence_projection(projection: JsonValue) -> bool: | ||
| return isinstance(projection, dict) and projection.get("key") == _TEXT_EVIDENCE_KEY | ||
|
|
||
|
|
||
| def _compact_source_metadata(value: Source, *, body: JsonValue, body_from_text_projection: bool) -> JsonValue: | ||
| """Keep provenance without re-sending a body that ``content`` already carries. | ||
|
|
||
| The dropped carriers are ``content`` and the structured ``wire_content`` of a | ||
| ContentSource, the ``payload`` content of an observation, and the consumed | ||
| text-evidence projection. Every other field, including ``payload.metadata`` and | ||
| unrelated projections, is kept. | ||
| """ | ||
|
|
||
| dumped = value.model_dump(mode="json", by_alias=True) | ||
| body_text = body.get("content") if isinstance(body, dict) else None | ||
|
|
||
| if _duplicates_body(dumped.get("content"), body_text): | ||
| # ``content`` carries the body, so the structured payload repeats it. | ||
| dumped.pop("content", None) | ||
| dumped.pop("wire_content", None) | ||
| dumped.pop("wire_content_present", None) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Preserve independent wire evidence for custom Sources
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks review! Here are the change details: Reproduction
Fix
Verification
|
||
| elif _duplicates_body(dumped.get("wire_content"), body_text): | ||
| dumped.pop("wire_content", None) | ||
| dumped.pop("wire_content_present", None) | ||
|
|
||
| if isinstance(value, SourceObservation): | ||
| payload = dumped.get("payload") | ||
| if body_from_text_projection: | ||
| if isinstance(payload, dict) and _duplicates_body(payload.get("content"), body_text): | ||
| dumped["payload"] = {key: item for key, item in payload.items() if key != "content"} | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. [P2] Remove duplicate wire content inside observation payloads This branch removes only
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks review! Here are the change details: Reproduction
Fix
Verification
|
||
| projections = dumped.get("projections") | ||
| if isinstance(projections, list): | ||
| remaining = [item for item in projections if not _is_text_evidence_projection(item)] | ||
| if remaining: | ||
| dumped["projections"] = remaining | ||
| else: | ||
| dumped.pop("projections", None) | ||
| elif payload == body: | ||
| dumped.pop("payload", None) | ||
| return _JSON.validate_python(dumped) | ||
|
|
||
|
|
||
| async def project_atomic_memory_evidence( | ||
| stored: StoredSource, | ||
| sources: SourceRepository, | ||
|
|
@@ -139,23 +188,26 @@ async def project_atomic_memory_evidence( | |
| """Expose source-provided dates in content/metadata without synthesizing time.""" | ||
|
|
||
| value = stored.value | ||
| body_from_text_projection = False | ||
| if isinstance(value, SourceObservation): | ||
| content = value.payload | ||
| for projection in value.projections: | ||
| if projection.key == TEXT_EVIDENCE_PROJECTION_KEY: | ||
| content = TextEvidence.model_validate(projection.value).model_dump(mode="json") | ||
| body_from_text_projection = True | ||
| break | ||
| else: | ||
| materialized = await sources.read_value(value) | ||
| content = ( | ||
| materialized.model_dump(mode="json", by_alias=True) if isinstance(materialized, BaseModel) else materialized | ||
| ) | ||
| body = _JSON.validate_python(content) | ||
| return AtomicMemoryEvidence( | ||
| evidence_id=evidence_id, | ||
| source_ref=stored.ref, | ||
| journal_position=stored.journal_position, | ||
| content=_JSON.validate_python(content), | ||
| source_metadata=_JSON.validate_python(value.model_dump(mode="json", by_alias=True)), | ||
| content=body, | ||
| source_metadata=_compact_source_metadata(value, body=body, body_from_text_projection=body_from_text_projection), | ||
| via_artifact=via_artifact, | ||
| ) | ||
|
|
||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,232 @@ | ||
| # Copyright (c) 2026 OceanBase. | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
| from typing import cast | ||
|
|
||
| from pydantic import JsonValue | ||
|
|
||
| from powercontext import SourceMaterialization | ||
| from powercontext.builtin.artifacts.atomic_memory.extraction import ( | ||
| AtomicMemoryEvidence, | ||
| AtomicMemoryExtractionInput, | ||
| project_atomic_memory_evidence, | ||
| ) | ||
| from powercontext.builtin.persistence.records import _canonical_source_text | ||
| from powercontext.builtin.persistence.sources import SourceRepository, StoredSource | ||
| from powercontext.builtin.sources import BUILTIN_SOURCE_REGISTRY, CONTENT_SOURCE_ADAPTER, ContentCapture, ContentSource | ||
| from powercontext.sources import ( | ||
| Source, | ||
| SourceProjectionKey, | ||
| SourceProjectionValue, | ||
| SourceRef, | ||
| project_source_for_transport, | ||
| ) | ||
|
|
||
| MARKER = "UNIQUE_EVIDENCE_MARKER" | ||
| BODY = f"{MARKER} Refactor the recall builder so the host skips retrieval when no history is relevant." | ||
|
|
||
|
|
||
| def _source(*, wire_content: JsonValue | None = None) -> ContentSource: | ||
| """Mirror the writer path: ``content`` is the canonical text of ``wire_content``.""" | ||
|
|
||
| return ContentSource( | ||
| name="turn-1", | ||
| materialization=SourceMaterialization.CAPTURED, | ||
| content=BODY if wire_content is None else _canonical_source_text(wire_content), | ||
| metadata={"origin": "pi", "event": "user_prompt_submit", "session_id": "session-1"}, | ||
| wire_content=wire_content, | ||
| wire_content_present=wire_content is not None, | ||
| ) | ||
|
|
||
|
|
||
| class _InMemorySources: | ||
| """Stand-in for ``SourceRepository.read_value`` on the native path.""" | ||
|
|
||
| def __init__(self, source: ContentSource) -> None: | ||
| self._source = source | ||
|
|
||
| async def read_value(self, *_args: object, **_kwargs: object) -> ContentCapture: | ||
| return await CONTENT_SOURCE_ADAPTER.read(self._source) | ||
|
|
||
|
|
||
| async def _evidence(stored_value: Source, native_source: ContentSource) -> AtomicMemoryEvidence: | ||
| stored = StoredSource( | ||
| ref=SourceRef(source_type="content", source_id=native_source.name), | ||
| value=stored_value, | ||
| journal_position=1, | ||
| ) | ||
| return await project_atomic_memory_evidence( | ||
| stored, | ||
| cast("SourceRepository", _InMemorySources(native_source)), | ||
| evidence_id="source:1", | ||
| ) | ||
|
|
||
|
|
||
| def _serialized(evidence: AtomicMemoryEvidence) -> str: | ||
| return AtomicMemoryExtractionInput(evidence=(evidence,)).model_dump_json() | ||
|
|
||
|
|
||
| def test_native_source_body_is_serialized_once() -> None: | ||
| """The native path sends the body once and keeps its provenance fields.""" | ||
|
|
||
| async def scenario() -> None: | ||
| source = _source() | ||
| evidence = await _evidence(source, source) | ||
|
|
||
| payload = _serialized(evidence) | ||
| metadata = evidence.source_metadata | ||
| assert isinstance(metadata, dict) | ||
|
|
||
| assert payload.count(MARKER) == 1 | ||
| assert "content" not in metadata | ||
| assert metadata["metadata"] == source.metadata | ||
| assert metadata["name"] == source.name | ||
|
|
||
| assert evidence.evidence_id == "source:1" | ||
| assert evidence.journal_position == 1 | ||
| assert evidence.source_ref == SourceRef(source_type="content", source_id="turn-1") | ||
| assert isinstance(evidence.content, dict) | ||
| assert evidence.content["content"] == BODY | ||
|
|
||
| asyncio.run(scenario()) | ||
|
|
||
|
|
||
| def test_projected_observation_body_is_serialized_once() -> None: | ||
| """The projected observation sends the body once and keeps payload metadata.""" | ||
|
|
||
| async def scenario() -> None: | ||
| source = _source() | ||
| observation = project_source_for_transport(BUILTIN_SOURCE_REGISTRY, source) | ||
| evidence = await _evidence(observation, source) | ||
|
|
||
| payload = _serialized(evidence) | ||
| metadata = evidence.source_metadata | ||
| assert isinstance(metadata, dict) | ||
|
|
||
| assert payload.count(MARKER) == 1 | ||
| assert "projections" not in metadata | ||
| assert metadata["source_type"] == "content" | ||
| payload_metadata = metadata["payload"] | ||
| assert isinstance(payload_metadata, dict) | ||
| assert "content" not in payload_metadata | ||
| assert payload_metadata["metadata"] == source.metadata | ||
| assert payload_metadata["name"] == source.name | ||
|
|
||
| assert evidence.evidence_id == "source:1" | ||
| assert evidence.journal_position == 1 | ||
| assert evidence.source_ref == SourceRef(source_type="content", source_id="turn-1") | ||
| assert isinstance(evidence.content, dict) | ||
| assert evidence.content["content"] == BODY | ||
|
|
||
| asyncio.run(scenario()) | ||
|
|
||
|
|
||
| def test_native_wire_content_duplicate_is_serialized_once() -> None: | ||
| """A wire payload equal to the body is not serialized twice.""" | ||
|
|
||
| async def scenario() -> None: | ||
| source = _source(wire_content=BODY) | ||
| evidence = await _evidence(source, source) | ||
|
|
||
| assert _serialized(evidence).count(MARKER) == 1 | ||
| metadata = evidence.source_metadata | ||
| assert isinstance(metadata, dict) | ||
| assert "wire_content" not in metadata | ||
| assert "wire_content_present" not in metadata | ||
| assert metadata["metadata"] == source.metadata | ||
|
|
||
| asyncio.run(scenario()) | ||
|
|
||
|
|
||
| def test_native_structured_wire_content_is_serialized_once() -> None: | ||
| """A structured wire payload is not serialized beside its canonical text.""" | ||
|
|
||
| async def scenario() -> None: | ||
| wire = {"text": BODY, "kind": "note"} | ||
| source = _source(wire_content=wire) | ||
| evidence = await _evidence(source, source) | ||
|
|
||
| assert _serialized(evidence).count(MARKER) == 1 | ||
| metadata = evidence.source_metadata | ||
| assert isinstance(metadata, dict) | ||
| assert "wire_content" not in metadata | ||
| assert "wire_content_present" not in metadata | ||
| assert metadata["metadata"] == source.metadata | ||
| assert metadata["name"] == source.name | ||
|
|
||
| asyncio.run(scenario()) | ||
|
|
||
|
|
||
| def test_observation_without_text_projection_is_serialized_once() -> None: | ||
| """Without a projection, the payload is the body and is removed from metadata.""" | ||
|
|
||
| async def scenario() -> None: | ||
| source = _source() | ||
| observation = project_source_for_transport(BUILTIN_SOURCE_REGISTRY, source) | ||
| observation = observation.model_copy(update={"projections": ()}) | ||
| evidence = await _evidence(observation, source) | ||
|
|
||
| assert _serialized(evidence).count(MARKER) == 1 | ||
| metadata = evidence.source_metadata | ||
| assert isinstance(metadata, dict) | ||
| assert "payload" not in metadata | ||
| assert metadata["source_type"] == "content" | ||
| assert evidence.content == observation.payload | ||
|
|
||
| asyncio.run(scenario()) | ||
|
|
||
|
|
||
| def test_observation_keeps_projections_other_than_text_evidence() -> None: | ||
| """Only the consumed text-evidence projection is dropped.""" | ||
|
|
||
| async def scenario() -> None: | ||
| source = _source() | ||
| observation = project_source_for_transport(BUILTIN_SOURCE_REGISTRY, source) | ||
| summary = SourceProjectionValue( | ||
| key=SourceProjectionKey(name="custom.summary", version="1"), | ||
| value={"note": "keep"}, | ||
| ) | ||
| observation = observation.model_copy(update={"projections": (*observation.projections, summary)}) | ||
| evidence = await _evidence(observation, source) | ||
|
|
||
| metadata = evidence.source_metadata | ||
| assert isinstance(metadata, dict) | ||
| projections = metadata["projections"] | ||
| assert [projection["key"]["name"] for projection in projections] == ["custom.summary"] | ||
| assert _serialized(evidence).count(MARKER) == 1 | ||
|
|
||
| asyncio.run(scenario()) | ||
|
|
||
|
|
||
| def test_observation_keeps_payload_content_that_differs_from_projection() -> None: | ||
| """Payload content is only removed when it equals the projected evidence.""" | ||
|
|
||
| async def scenario() -> None: | ||
| source = _source() | ||
| observation = project_source_for_transport(BUILTIN_SOURCE_REGISTRY, source) | ||
| payload = dict(observation.payload) | ||
| payload["content"] = "DIFFERENT_BODY" | ||
| observation = observation.model_copy(update={"payload": payload}) | ||
| evidence = await _evidence(observation, source) | ||
|
|
||
| metadata = evidence.source_metadata | ||
| assert isinstance(metadata, dict) | ||
| payload_metadata = metadata["payload"] | ||
| assert payload_metadata["content"] == "DIFFERENT_BODY" | ||
| assert _serialized(evidence).count(MARKER) == 1 | ||
|
|
||
| asyncio.run(scenario()) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Design note (non-blocking): this overlaps the input gate in #1989 / draft #1991, which deduplicates the same Atomic
content/source_metadatafields generically behind a default-off switch. Its_would_noop()also requiressource_metadata["content"] == content["content"], so after this change that shadow check would always return false. Linking #1989 and noting which layer should own this deduplication would help keep the two from diverging. cc @hidb4aiThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
补充实证(head
7d44342e)。上一轮
4333088534的 P1 已闭合:_duplicates_body走_canonical_source_text语义比较,结构化 wire 时content已承载同一份规范化 JSON,因此wire_content被正确丢弃。同一探针(
oceanbase-powercontext-pr-2163/probes/probe_structured_wire.py,Windows / Python 3.14.3,PYTHONPATH指向镜像 src)对同一场景并排跑三个树:
88899876:2 次(content+wire_content同一份 JSON);7d44342e:1 次 / 586 bytes;1c57cf4a:2 次 / 738 bytes。tests/builtin/artifacts/atomic_memory/test_extraction_evidence_projection.py本地 7 passed。这条 design note 现在有具体对象:#2163(今日 08:37 开)对同一个
project_atomic_memory_evidence做了同一件事,边界不同——结构化
wire_content本 PR 删、#2163 保留(重复仍在);payload.content本 PR 仅在等于投影正文时删、#2163 无条件删;其他 projection 的
value.content本 PR 完整保留、#2163 一律剥离。两个 PR 改的是同一插入点,后合入者必然冲突。建议只推进其中一个,并在被放弃的一方写明原因;若保留本 PR,请把与 #1989 / #1991 / #2137 / #2163
的关系写进 PR 正文,避免三份实现各自声称同一收益。
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Conclusion: Recommend proceeding with this PR#2139 only
This proposal already had an implementation before #2163 was opened
Current state of #2139:
wire_contentcase is fixed and pinned by a test. On the same probe: master88899876sends the body 2 times, perf(atomic-memory): stop duplicating source text in extraction input to reduce token consumption #2139 once / 586 bytes, perf(atomic-memory): compact repeated bodies in additional projections #2163 (1c57cf4a) still twice / 738 bytes.I deliberately did not widen that boundary, because may the two wider removals carry evidence-loss risk:
1. Unconditional
payload.contentremoval : when a payload'scontentdiffers from the projected body (a summary rather than the full text, or another serialization), that distinct text never reaches the model. No test covers the differing case.2. Removing
value.contentfrom every projection : projections are an extension point, andcontentis a common key there (for example aticket-summaryprojection). Removing it deletes evidence that is not a duplicate and leaves only the sibling keys.3. Value-comparing
wire_content: a structured payload is never equal to its canonical text, so the duplicate survives; this is the inverse failure. #2139 replaces that comparison with a semantic one and pins the result with a test.If the maintainers are willing to accept that risk, I can widen #2139's boundary to match #2163 (unconditional
payload.content, strippingvalue.contentfrom other projections) and add tests for the differing-content cases.The relationship with #1989 / #1991 / #2137 / #2163 has been documented in the PR description.