Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
58 changes: 55 additions & 3 deletions src/powercontext/builtin/artifacts/atomic_memory/extraction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown
Collaborator

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_metadata fields generically behind a default-off switch. Its _would_noop() also requires source_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 @hidb4ai

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.

补充实证(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)
对同一场景并排跑三个树:

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 正文,避免三份实现各自声称同一收益。

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.

Conclusion: Recommend proceeding with this PR#2139 only

This proposal already had an implementation before #2163 was opened

Current state of #2139:

I deliberately did not widen that boundary, because may the two wider removals carry evidence-loss risk:

1. Unconditional payload.content removal : when a payload's content differs 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.content from every projection : projections are an extension point, and content is a common key there (for example a ticket-summary projection). 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, stripping value.content from other projections) and add tests for the differing-content cases. 

The relationship with #1989 / #1991 / #2137 / #2163 has been documented in the PR description.

"""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)

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 independent wire evidence for custom Sources

value can be any registered Source, so content == body["content"] does not establish that wire_content repeats it. A valid custom Source with content="The deploy uses canary." and wire_content={"constraint": "Pause when errors rise."}, whose adapter returns TextEvidence(content=source.content, ...), is accepted, persists and reads back correctly. Through a real SQLite Sources.add -> process_memory run, the independent wire evidence appears in the base extraction input but disappears at this head, while flush succeeds. Please only remove the wire fields when their equivalence to the retained body is established; the built-in writer's convention cannot be assumed for every Source Definition.

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.

Thanks review! Here are the change details:

Reproduction
A custom Source with content="The deploy uses canary." and wire_content={"constraint": "Pause when errors rise."}, whose adapter returns TextEvidence(content=source.content, ...):

  • before: wire_content and wire_content_present disappeared from the extraction input
  • after: both are preserved

Fix

  • Added _wire_repeats_body(value, body_text): a wire carrier is dropped only when its canonical text equals the retained body text. The presence of content no longer implies that the wire repeats it.
  • The same predicate drives the Source dump and the observation payload through _drop_body_carriers, so the two paths cannot diverge.
  • content and the wire carriers are decided independently; carriers that do reproduce the body still collapse to one copy.

Verification

  • test_sqlite_native_wire_evidence_survives_process_memory: real SQLite Sources.add -> process_memory for the custom Source above, asserting the independent wire survives.
  • test_native_keeps_wire_evidence_that_differs_from_body: unit-level counterpart.
  • Against the pre-fix code, the SQLite test fails with KeyError: 'wire_content'.

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"}

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] Remove duplicate wire content inside observation payloads

This branch removes only payload.content; payload.wire_content remains even when it contains exactly the same body. A remote Source Definition with a standard text-evidence projection and identical content/wire_content values reproduces this after successful manifest registration and observation submission. With a roughly 50,000-character ASCII body, the runtime character estimator reports 25,747 input tokens, and process_memory(..., 1) raises atomic-memory-input-budget before calling the extractor. Removing the residual duplicate reduces the estimate to 13,238, below the default 24,000 limit. Please apply equivalent compaction to the nested wire carriers while preserving distinct wire evidence, and cover observation inputs with both text and structured wire values.

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.

Thanks review! Here are the change details:

Reproduction
An observation with a standard text-evidence projection and content == wire_content, with a 50,000-character ASCII body:

  • before: process_memory(..., 1) raised atomic-memory-input-budget before the extractor was called
  • after: the observation is processed, and the serialized extraction input contains the body once, with the estimate below the 24,000 limit

Fix

  • Observation payloads now apply the same compaction to wire_content and wire_content_present that already applied to payload.content.
  • Each carrier is dropped independently, only when its canonical text equals the projected body. Distinct structured wire evidence is retained.
  • Both paths share _drop_body_carriers, so a future change to the rule applies to the Source dump and the observation payload together.

Verification

  • test_sqlite_observation_duplicate_wire_stays_within_input_budget: real SQLite observation submission followed by process_memory(..., 1), asserting one body occurrence and an input estimate under 24,000.
  • test_observation_payload_drops_wire_content_equal_to_body and test_observation_payload_keeps_wire_evidence_that_differs_from_body: text and structured wire values, as requested.
  • Against the pre-fix code, the SQLite observation test fails with atomic-memory-input-budget.

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,
Expand All @@ -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,
)

Expand Down
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())
Loading