Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 4 additions & 0 deletions docs/zh/design/atomic_memory_one_pass_design.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,10 @@ Core 在应用时记录本次回复已写过的记忆,再次以 revise / merge
(create 表示保留,revise / merge 与目标合并,noop 表示目标已包含该事实)。这一步与逐候选流程的一次比对等价,
直接用 `workset.apply(候选, 未展示记忆, 操作)` 应用。第 3 步的请求会重发第 2 步展示过的已有记忆,
因此发送前对这些记忆和新召回的记忆一起重新检查读写权限。
第 3 步的 `evidence_ids` 与第 2 步一样,可以引用本窗口的任意证据,
例如合并时同时引用窗口里另一个 Source;Core 先把引用的证据加入这条 create,再按上面的方式应用,
发布结果与第 2 步引用同样证据的写入相同。引用不属于本窗口的 ID 按不合规则处理(§3.1);
不给 `evidence_ids` 时沿用这条 create 已有的证据。

被多条 create 召回的同一条已有记忆只有一个标签,模型能看出它们指向同一条记忆。§3.3 的"最多写一次"在这一步
同样生效:两条 create 都要并入同一条已有记忆时,由一个操作合并,另一条以 noop 指向该记忆。
Expand Down
31 changes: 27 additions & 4 deletions src/powercontext/builtin/artifacts/atomic_memory/one_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

import json
from collections.abc import Mapping, Sequence
from dataclasses import replace
from typing import Literal, NoReturn, TypeVar

from pydantic import BaseModel, ConfigDict, Field, ValidationError
Expand All @@ -43,6 +44,7 @@
AtomicMemoryWindowWorkset,
AtomicMemoryWorkingItem,
RedundantAtomicMemoryRevisionError,
unique_evidence,
)
from powercontext.builtin.inference import InvalidInferenceOutputError
from powercontext.builtin.processing_diagnostics import (
Expand Down Expand Up @@ -293,10 +295,15 @@ def apply_one_pass_recheck(
reply: str,
created: Mapping[str, str],
unseen: Mapping[str, Mapping[str, str]],
extraction_input: AtomicMemoryExtractionInput,
) -> AtomicMemoryWindowWorkset:
"""Apply step 3 to a copy of the workset: each created item against the memories recalled for it."""
"""Apply step 3 to a copy of the workset: each created item against the memories recalled for it.

A write may cite any evidence of the window, as in step 2.
"""

result = workset.copy()
evidence = {item.evidence_id: item for item in extraction_input.evidence}
operations = {operation.id: operation for operation in _parse(reply, OnePassOperations).operations}
if operations.keys() != created.keys():
_invalid("return exactly one operation for every listed memory id")
Expand All @@ -313,6 +320,24 @@ def apply_one_pass_recheck(
resolved = tuple(dict.fromkeys(result.resolve(target) for target in targets))
if writes and written.intersection(resolved):
_invalid(_SHARED_TARGET)
cited = tuple(dict.fromkeys(operation.evidence_ids)) if writes else ()
if not set(cited) <= evidence.keys():
_invalid("evidence_ids may contain only the evidence_id values supplied in the first message")
if cited:
# The decision checks evidence against the proposal's own, so the cited window evidence joins it first.
supporting = unique_evidence((*proposal.evidence, *(evidence[identifier] for identifier in cited)))
proposal = replace(
proposal,
evidence=supporting,
sources=tuple(
{
item.source_ref.model_dump_json(): item.source_ref
for item in supporting
if isinstance(item, AtomicMemoryEvidence)
}.values()
),
)
result.items[key] = proposal

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.

[P2] Preserve original evidence during redundant-revision recovery

When a recheck cites another window Source and returns a revise identical to the recalled target while the proposal text differs, _apply() recovers by retaining the proposal, but this assignment leaves the newly cited evidence and Source lineage attached. The retained memory can consequently be published without that Source's required date; restore the original proposal's evidence and lineage before recovery or keep the expansion temporary until the write succeeds.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

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

Fixed in a1cd33b. When the recheck revision is redundant, the created memory is restored to what step 2 made before the recovery runs, so it keeps only the evidence and Source it was created from. test_recheck_accepts_every_evidence_id_of_the_window has a new case for this: the recheck revises the recalled memory to its own text and cites both Sources; the created memory is kept and links only its own Source. Without the restore the case fails with both Sources linked.

_apply(
result,
key,
Expand All @@ -322,9 +347,7 @@ def apply_one_pass_recheck(
compared_ids=tuple(item.key for item in related),
target_ids=resolved,
content=_content(operation, default=proposal.content) if writes else None,
evidence_ids=(
(operation.evidence_ids or tuple(item.evidence_id for item in proposal.evidence)) if writes else ()
),
evidence_ids=(cited or tuple(item.evidence_id for item in proposal.evidence)) if writes else (),
reason=operation.reason,
),
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,7 @@ async def _recheck_one_pass(
workset,
created=batch,
unseen={label: unseen[label] for label in batch},
extraction_input=extraction_input,
),
operations,
)
Expand Down
51 changes: 51 additions & 0 deletions tests/e2e/test_atomic_memory_one_pass.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,57 @@ async def scenario(contexts, memory) -> None:
_run(tmp_path, conversation, scenario)


def test_recheck_accepts_every_evidence_id_of_the_window(tmp_path: Path) -> None:
evidence: dict[str, str] = {}

def entries(window: dict[str, Any]) -> dict[str, Any]:
evidence.update({item["source_ref"]["source_id"]: item["evidence_id"] for item in window["evidence"]})
return _facts("unrelated words")

def create(_: dict[str, Any]) -> dict[str, Any]:
return {"operations": [_write("create", BUDGET_200, evidence_ids=[evidence["budget"]])]}

def run(path: Path, *cited: str) -> tuple[Any, tuple[Any, ...], InvalidInferenceOutputError | None]:
"""Revise the recalled budget in step 3 with the owner, citing ``cited`` or every Source of the window."""

def recheck(listed: dict[str, Any]) -> dict[str, Any]:
(entry,) = listed["recheck"]
label = entry["existing_memories"][0]["id"]
evidence_ids = list(cited or evidence.values())
operation = _write("revise", f"{BUDGET_200} {OWNER}", label, evidence_ids=evidence_ids)
return {"operations": [{**operation, "id": entry["id"]}]}

outcome: list[Any] = []

async def scenario(contexts, memory) -> None:
await contexts.records.create_atomic_memories(SCOPE, ({"kind": "fact", "text": BUDGET_100},))
outcome.extend((await memory.list()).items)
await contexts.process_memory(SCOPE, 1)
await contexts.records.capture_source(SCOPE, "content", "budget", BUDGET_200, {})
await contexts.records.capture_source(SCOPE, "content", "owner", OWNER, {})
try:
await contexts.process_memory(SCOPE, 2)
except InvalidInferenceOutputError as error:
outcome.append(error)
outcome.append((await memory.list()).items)

path.mkdir()
_run(path, _Conversation(entries, create, recheck), scenario)
return outcome[0], outcome[-1], outcome[1] if len(outcome) == 3 else None

# Step 3 may cite every Source of the window, as step 2 may: the revision states the owner from the other one.
original, (revised,), rejected = run(tmp_path / "window")
assert rejected is None
assert revised.artifact.content.text == f"{BUDGET_200} {OWNER}"
assert revised.ref.artifact_id == original.ref.artifact_id
assert {ref.source_id for ref in revised.artifact.lineage.sources} == {"budget", "owner"}

# An evidence id that is not in the window is still rejected.
original, items, rejected = run(tmp_path / "unknown", "unknown")
assert rejected is not None and rejected.operation == "atomic-memory-one-pass"
assert [(item.ref, item.artifact.content.text) for item in items] == [(original.ref, BUDGET_100)]


NOTES = "Rollout notes for the payments service: owner and budget are tracked here."


Expand Down
Loading