From c9aef13835422c9985f7d5d5b5f978d1a4987aac Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 12:47:32 +0200 Subject: [PATCH 01/14] wip(processing): checkpoint document references and context nomination --- .github/ci/integration-paths.txt | 1 + .github/ci/unit-paths.txt | 3 + benchmarks/locomo/protocol.py | 4 +- .../contextual_fact_nomination_design.md | 17 +- plan/handoffs/2026-09-14-d122-d123-grok.md | 7 +- src/rememberstack/core/__init__.py | 8 + src/rememberstack/core/context_references.py | 32 ++ .../core/selection_references.py | 368 +++++++++++++++++ src/rememberstack/model/__init__.py | 2 + src/rememberstack/model/claims.py | 19 +- src/rememberstack/model/relations.py | 3 + src/rememberstack/spine/catalog_contract.py | 9 +- src/rememberstack/spine/fact_adjudication.py | 17 +- .../spine/fact_application_inputs.py | 206 +++++++++- src/rememberstack/spine/fact_applications.py | 59 ++- src/rememberstack/spine/forget.py | 9 + .../p9_32_0053_source_reference_context.py | 82 ++++ src/rememberstack/spine/resolver.py | 4 +- src/rememberstack/workers/e3.py | 46 +++ src/tests/core/test_context_references.py | 50 +++ src/tests/core/test_selection_references.py | 387 ++++++++++++++++++ src/tests/database_reset.py | 8 +- src/tests/fact_application_support.py | 62 ++- .../spine/test_d123_context_nomination.py | 258 ++++++++++++ src/tests/spine/test_migrations.py | 51 ++- src/tests/workers/e3_test_doubles.py | 13 +- .../workers/test_e3_context_references.py | 119 ++++++ .../src/app/docs/ingestion/pipeline/page.mdx | 7 + 28 files changed, 1814 insertions(+), 37 deletions(-) create mode 100644 src/rememberstack/core/context_references.py create mode 100644 src/rememberstack/core/selection_references.py create mode 100644 src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py create mode 100644 src/tests/core/test_context_references.py create mode 100644 src/tests/core/test_selection_references.py create mode 100644 src/tests/spine/test_d123_context_nomination.py create mode 100644 src/tests/workers/test_e3_context_references.py diff --git a/.github/ci/integration-paths.txt b/.github/ci/integration-paths.txt index 4a035ed33..86284e7d8 100644 --- a/.github/ci/integration-paths.txt +++ b/.github/ci/integration-paths.txt @@ -8,6 +8,7 @@ src/tests/spine/test_backfill.py src/tests/spine/test_canonical_bounds_sql.py src/tests/spine/test_clustering.py src/tests/spine/test_component_versions.py +src/tests/spine/test_d123_context_nomination.py src/tests/spine/test_deployment_bootstrap.py src/tests/spine/test_document_inventory.py src/tests/spine/test_fact_application_writer.py diff --git a/.github/ci/unit-paths.txt b/.github/ci/unit-paths.txt index ec616d868..380debfa9 100644 --- a/.github/ci/unit-paths.txt +++ b/.github/ci/unit-paths.txt @@ -28,6 +28,7 @@ src/tests/benchmarks/test_locomo_sharding.py src/tests/benchmarks/test_locomo_store_backup.py src/tests/core/test_blockizer_corpus.py src/tests/core/test_chunker.py +src/tests/core/test_context_references.py src/tests/core/test_consumption_skill.py src/tests/core/test_conversion.py src/tests/core/test_core_manifest.py @@ -44,6 +45,7 @@ src/tests/core/test_knowledge_hashing.py src/tests/core/test_knowledge_planner.py src/tests/core/test_knowledge_writer.py src/tests/core/test_section_snap.py +src/tests/core/test_selection_references.py src/tests/core/test_source_passages.py src/tests/core/test_structure_skeleton.py src/tests/core/test_temporal.py @@ -96,6 +98,7 @@ src/tests/workers/test_d79_summaries.py src/tests/workers/test_d79_summary_consumption.py src/tests/workers/test_e3_bare_head_noun.py src/tests/workers/test_e3_claim_normalize_fanout.py +src/tests/workers/test_e3_context_references.py src/tests/workers/test_e3_entity_obs_flush_fanout.py src/tests/workers/test_extraction_temperature.py src/tests/workers/test_hard_forget_handler.py diff --git a/benchmarks/locomo/protocol.py b/benchmarks/locomo/protocol.py index 6c0e84f43..433234a33 100644 --- a/benchmarks/locomo/protocol.py +++ b/benchmarks/locomo/protocol.py @@ -79,10 +79,10 @@ "normalize_relations": ( "e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:" "no-types-1:binary-t4-1:document-t0-1:mutable-window-1:" - "assertion-clarity-3" + "assertion-clarity-3:d123-context-refs-1" ), "adjudicate_observations": ( - "e3-obs-flush:entity-fanout-1:e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:no-types-1:binary-t4-1:document-t0-1:mutable-window-1:assertion-clarity-3:relation-adjudicator-2026.09d:concise-handles-5:obs-adjudicator-2026.09d:concise-handles-5" + "e3-obs-flush:entity-fanout-1:e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:no-types-1:binary-t4-1:document-t0-1:mutable-window-1:assertion-clarity-3:d123-context-refs-1:relation-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1:obs-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1" ), "adjudicate_supersession": "fact-followup-2026.09:mutable-window-1", "embed_claim": "p1-embed-claims-2026.07", diff --git a/plan/designs/contextual_fact_nomination_design.md b/plan/designs/contextual_fact_nomination_design.md index c4807acfa..86d1f85fd 100644 --- a/plan/designs/contextual_fact_nomination_design.md +++ b/plan/designs/contextual_fact_nomination_design.md @@ -16,12 +16,17 @@ or creative work when it is a source-grounded referent of an assertion. Extend the existing normalization response for each assertion with a bounded list of ordinary `EntityRef` context references. They must be explicit referents in the grounded claim, not entities guessed from unrelated profiles. The existing -normalizer call emits them; no additional inference stage. Four additional -references is the initial generation-pinned bound. Deduplicate in emitted order, -retain the first four and record truncation; auxiliary overflow must not cause -schema rejection of the whole normalization response, discard an otherwise valid -assertion or prove novelty. Preserve original reference ordinals and document the -cap clearly in the provider schema. +normalizer call emits them. There is no additional dedicated event extractor, +profile summarizer, or semantic-checker stage. Ordinary entity resolution remains +authoritative and may invoke its existing model tier for a newly supplied context +reference; that resolver cost is measured, not bypassed. Four additional +references is the initial generation-pinned bound. Bound the first four original +array slots, resolve them normally, then deduplicate and exclude the canonical +subject or object while keeping those original ordinals. Equal names are not +identity; aliases of one entity keep the first resolved id. Record truncation +from the frozen list; auxiliary overflow must not cause schema rejection of the +whole normalization response, discard an otherwise valid assertion or prove +novelty. Document the cap clearly in the provider schema. The subject remains the correct subject. “Joanna said Nate won Tournament A” remains attributed to Joanna; Nate and Tournament A can be context. Relations' diff --git a/plan/handoffs/2026-09-14-d122-d123-grok.md b/plan/handoffs/2026-09-14-d122-d123-grok.md index d4e528f1f..83d99a1f7 100644 --- a/plan/handoffs/2026-09-14-d122-d123-grok.md +++ b/plan/handoffs/2026-09-14-d122-d123-grok.md @@ -22,8 +22,11 @@ junction bindings with atomic staging, positive current-testimony membership, canonical-subject exclusion and baseline-preserving additional nomination. Do not add an event type/table, per-fact event column, new date window, local alias -registry, extra model call, grouped adjudication, event scheduler or profile -neighborhood fetch. Dates remain on supported facts; profile descriptions are +registry, grouped adjudication, event scheduler or profile neighborhood fetch. +D122 adds no third extraction call. D123 adds no dedicated event extractor, +profile summarizer, or semantic-checker stage; ordinary entity resolution may +still invoke its existing model tier for a newly supplied context reference, and +that cost is measured. Dates remain on supported facts; profile descriptions are derived. Existing inference-outside-locks and source deletion contracts apply. Do not drop assertions for auxiliary context overflow. Same event never means same proposition; D120 remains the semantic rule. Context-empty is not novelty. diff --git a/src/rememberstack/core/__init__.py b/src/rememberstack/core/__init__.py index 4806122c6..2525c3d90 100644 --- a/src/rememberstack/core/__init__.py +++ b/src/rememberstack/core/__init__.py @@ -18,6 +18,8 @@ from rememberstack.core.chunker import pack_blocks from rememberstack.core.consumption_skill import CONSUMPTION_SKILL_VERSION from rememberstack.core.consumption_skill import render_consumption_skill +from rememberstack.core.context_references import attempted_context_refs +from rememberstack.core.context_references import MAX_CONTEXT_REFS from rememberstack.core.conversion import ConversionRouter from rememberstack.core.conversion import Converter from rememberstack.core.conversion import entire_document_labeling @@ -67,6 +69,8 @@ from rememberstack.core.ranking import rerank_by_weighted_signals from rememberstack.core.section_snap import SECTION_ROLES from rememberstack.core.section_snap import snap_sections +from rememberstack.core.selection_references import claimify_input_hash +from rememberstack.core.selection_references import REFERENCE_POLICY_VERSION from rememberstack.core.source_passages import build_passage_catalog from rememberstack.core.source_passages import canonicalize_spans from rememberstack.core.source_passages import EvidenceSpan @@ -99,6 +103,10 @@ "extraction_input_hash", "is_anchor", "pack_blocks", + "attempted_context_refs", + "MAX_CONTEXT_REFS", + "claimify_input_hash", + "REFERENCE_POLICY_VERSION", "EMBEDDING_INPUT_POLICY_VERSION", "render_embedding_input", "CORE_MANIFEST", diff --git a/src/rememberstack/core/context_references.py b/src/rememberstack/core/context_references.py new file mode 100644 index 000000000..b7b6ab359 --- /dev/null +++ b/src/rememberstack/core/context_references.py @@ -0,0 +1,32 @@ +"""Bounded generic context references on normalized assertions (D123). + +The normalizer may name ordinary entities the claim refers to besides the +subject (and besides a relation's object). The first four original array +slots are attempted. Extra items are truncation, recorded from the frozen +list; they must not reject the assertion or prove novelty. Name equality is +not entity identity: resolved canonical ids are deduplicated after ordinary +resolution, and original ordinals are preserved. +""" + +from __future__ import annotations + +from typing import Final + +from rememberstack.model.relations import EntityRef + +MAX_CONTEXT_REFS: Final = 4 + + +def attempted_context_refs( + *, refs: tuple[EntityRef, ...] +) -> tuple[tuple[tuple[int, EntityRef], ...], bool]: + """Keep original ordinals of the first four emitted references. + + Truncation is whether the frozen list is longer than the bound. Equal + names stay distinct until ordinary resolution assigns entity ids. + """ + truncated = len(refs) > MAX_CONTEXT_REFS + return ( + tuple((index, ref) for index, ref in enumerate(refs[:MAX_CONTEXT_REFS])), + truncated, + ) diff --git a/src/rememberstack/core/selection_references.py b/src/rememberstack/core/selection_references.py new file mode 100644 index 000000000..524dcb7f8 --- /dev/null +++ b/src/rememberstack/core/selection_references.py @@ -0,0 +1,368 @@ +"""Bounded source-reference cards shared from Selection to Claimify (D122). + +The engine supplies labeled source passages (the D119 catalog) before Selection +runs. Selection names people, companies, works, or particular events by citing +those labels. This module resolves citations through that catalog: it does not +search for quote strings. Two cards that share a descriptive name stay distinct. +A missing, forged, or incomplete citation rejects the whole card. Remapping +applies D119's already-translated ranges; it does not rescue unmatched text. +""" + +from __future__ import annotations + +from collections.abc import Mapping +from dataclasses import dataclass +import hashlib +import re +from typing import Final +from typing import Literal +from uuid import UUID + +from rememberstack.model.chunks import ChunkForEmbedding +from rememberstack.model.claims import SourceReferenceCard + +REFERENCE_POLICY_VERSION: Final = "d122-ref-policy-1:cards4-claimify8-chars4096-prev8" +MAX_CARDS_PER_SELECTION: Final = 4 +MAX_CARDS_PER_CLAIMIFY: Final = 8 +MAX_CARD_CHARS: Final = 4096 +PRECEDING_CHUNK_LIMIT: Final = 8 + +_TOKEN_RE: Final = re.compile(r"\w+") +PassageRegion = Literal["target", "previous", "next"] + + +@dataclass(frozen=True) +class PassageSupport: + """One engine-supplied source passage the model may cite (D119 descriptor).""" + + label: str + char_start: int + char_end: int + region: PassageRegion + + +@dataclass(frozen=True) +class GroundedPassage: + """One resolved exact source range that supports a published card.""" + + label: str + char_start: int + char_end: int + region: PassageRegion + text: str + + +@dataclass(frozen=True) +class GroundedCard: + """A Selection card after catalog resolution, with its original ordinal.""" + + name: str + aliases: tuple[str, ...] + passages: tuple[GroundedPassage, ...] + ordinal: int + owner_chunk_id: UUID + owner_ordinal: int + + +@dataclass(frozen=True) +class CardDiagnostic: + """Why a cited card was not published. Cap losses are separate.""" + + ordinal: int + gate: str + detail: str + + +def claimify_input_hash( + *, + target_selection_input_hash: str, + preceding_selection_input_hashes: tuple[str, ...], + policy_version: str = REFERENCE_POLICY_VERSION, +) -> str: + """Stable Claimify reuse key, including empty preceding producers. + + Hashing only admitted cards would miss a competing introduction in an + earlier chunk that published nothing last time. The ordered Selection + input hashes of the previous eight source chunks are the negative + dependency. Absolute offsets and temporary labels stay out. + """ + payload = "\x1e".join( + (target_selection_input_hash, *preceding_selection_input_hashes, policy_version) + ) + return hashlib.sha256(payload.encode("utf-8")).hexdigest() + + +def token_set(*, text: str) -> frozenset[str]: + """Lowercased word tokens used for overlap ranking.""" + return frozenset(token.casefold() for token in _TOKEN_RE.findall(text)) + + +def catalog_by_label( + *, passages: tuple[PassageSupport, ...] +) -> dict[str, PassageSupport]: + """Label map; labels are unique by construction in the engine catalog.""" + return {passage.label: passage for passage in passages} + + +def resolve_card( + *, + card: SourceReferenceCard, + catalog: Mapping[str, PassageSupport], + document_md: str, + owner_chunk: ChunkForEmbedding, + ordinal: int, +) -> tuple[GroundedCard | None, CardDiagnostic | None]: + """Resolve every cited label through the supplied catalog. + + Unknown, empty, or incomplete citations reject the whole card. A published + card keeps every cited support. At least one target-chunk body passage is + required; neighbour passages may only clarify. Kept-proposition origin + eligibility is not required for cards. + """ + if not card.source_refs: + return None, CardDiagnostic( + ordinal=ordinal, + gate="empty_source_refs", + detail="a reference card must cite at least one supplied passage", + ) + resolved: list[GroundedPassage] = [] + seen_labels: set[str] = set() + for label in card.source_refs: + if label in seen_labels: + continue + passage = catalog.get(label) + if passage is None: + return None, CardDiagnostic( + ordinal=ordinal, + gate="unknown_source_ref", + detail=f"source reference {label!r} was not provided", + ) + if ( + passage.char_end > len(document_md) + or passage.char_start >= passage.char_end + ): + return None, CardDiagnostic( + ordinal=ordinal, + gate="invalid_source_ref", + detail=f"source reference {label!r} is not a usable range", + ) + seen_labels.add(label) + resolved.append( + GroundedPassage( + label=label, + char_start=passage.char_start, + char_end=passage.char_end, + region=passage.region, + text=document_md[passage.char_start : passage.char_end], + ) + ) + if not any(item.region == "target" for item in resolved): + return None, CardDiagnostic( + ordinal=ordinal, + gate="no_target_passage", + detail="a published card needs at least one target-chunk body passage", + ) + aliases = tuple( + alias.strip() + for alias in card.aliases + if alias.strip() and alias.strip() != card.name + ) + return ( + GroundedCard( + name=card.name.strip(), + aliases=aliases, + passages=tuple(resolved), + ordinal=ordinal, + owner_chunk_id=owner_chunk.chunk_id, + owner_ordinal=owner_chunk.ordinal, + ), + None, + ) + + +def publish_selection_cards( + *, + cards: tuple[SourceReferenceCard, ...], + catalog: Mapping[str, PassageSupport], + document_md: str, + owner_chunk: ChunkForEmbedding, +) -> tuple[tuple[GroundedCard, ...], bool, tuple[CardDiagnostic, ...]]: + """Resolve cards in emission order and keep the first four whole cards. + + Original emitted ordinals are preserved. Equal names are not identity, and + the same supporting range may introduce two different referents. Distinct + emitted cards stay distinct. The cap drops a whole later card. + """ + published: list[GroundedCard] = [] + diagnostics: list[CardDiagnostic] = [] + truncated = False + for ordinal, card in enumerate(cards): + grounded, diagnostic = resolve_card( + card=card, + catalog=catalog, + document_md=document_md, + owner_chunk=owner_chunk, + ordinal=ordinal, + ) + if diagnostic is not None: + diagnostics.append(diagnostic) + continue + assert grounded is not None + if len(published) >= MAX_CARDS_PER_SELECTION: + truncated = True + break + published.append(grounded) + return tuple(published), truncated, tuple(diagnostics) + + +def remap_card( + *, + card: GroundedCard, + remapped_spans: tuple[tuple[int, int], ...] | None, + current_md: str, + current_windows: Mapping[PassageRegion, tuple[int, int]], +) -> GroundedCard | None: + """Apply D119-translated ranges. Incomplete mapping rejects the whole card. + + ``remapped_spans`` is the output of D119 ``remap_evidence_spans`` (or None + when that mapping refuses). This function does not search for text. + """ + if remapped_spans is None or len(remapped_spans) != len(card.passages): + return None + remapped: list[GroundedPassage] = [] + for (new_start, new_end), prior in zip(remapped_spans, card.passages, strict=True): + region = _unique_region( + char_start=new_start, char_end=new_end, windows=current_windows + ) + if region is None: + return None + if current_md[new_start:new_end] != prior.text: + return None + remapped.append( + GroundedPassage( + label=prior.label, + char_start=new_start, + char_end=new_end, + region=region, + text=current_md[new_start:new_end], + ) + ) + if not any(item.region == "target" for item in remapped): + return None + return GroundedCard( + name=card.name, + aliases=card.aliases, + passages=tuple(remapped), + ordinal=card.ordinal, + owner_chunk_id=card.owner_chunk_id, + owner_ordinal=card.owner_ordinal, + ) + + +def _unique_region( + *, char_start: int, char_end: int, windows: Mapping[PassageRegion, tuple[int, int]] +) -> PassageRegion | None: + """Region of the unique window that fully contains the range.""" + matches = [ + region + for region, (start, end) in windows.items() + if start <= char_start and char_end <= end + ] + if len(matches) != 1: + return None + return matches[0] + + +def _card_tokens(*, card: GroundedCard) -> frozenset[str]: + """Name, aliases, and supporting passage tokens.""" + parts = [card.name, *card.aliases, *(passage.text for passage in card.passages)] + return token_set(text=" ".join(parts)) + + +def rank_and_fit_cards( + *, + cards: tuple[GroundedCard, ...], + target_text: str, + target_ordinal: int, + max_cards: int = MAX_CARDS_PER_CLAIMIFY, + max_chars: int = MAX_CARD_CHARS, +) -> tuple[tuple[GroundedCard, ...], bool]: + """Order eligible cards and keep whole cards under the rendered request bounds.""" + target_tokens = token_set(text=target_text) + + def sort_key(card: GroundedCard) -> tuple[int, int, int]: + overlap = len(target_tokens & _card_tokens(card=card)) + distance = abs(target_ordinal - card.owner_ordinal) + return (-overlap, distance, card.ordinal) + + ranked = tuple(sorted(cards, key=sort_key)) + chosen: list[GroundedCard] = [] + truncated = False + for card in ranked: + candidate = (*chosen, card) + rendered = render_cards_for_claimify(cards=candidate) + if len(chosen) >= max_cards or len(rendered) > max_chars: + truncated = True + break + chosen.append(card) + return tuple(chosen), truncated or len(ranked) > len(chosen) + + +def render_cards_for_claimify(*, cards: tuple[GroundedCard, ...]) -> str: + """Human-readable card block. Names are orientation; passages are evidence. + + Card labels are request-unique across owning chunks. Passage labels are the + engine-supplied catalog ids Claimify can cite as D119 source support. + """ + if not cards: + return "(none)" + lines: list[str] = [] + for index, card in enumerate(cards, start=1): + alias = f" also called {', '.join(card.aliases)}" if card.aliases else "" + lines.append(f"R{index}: {card.name}{alias}") + for passage in card.passages: + lines.append(f' {passage.label}: "{passage.text}"') + return "\n".join(lines) + + +def card_payload(*, card: GroundedCard) -> dict[str, object]: + """JSON object stored with a frozen Selection result.""" + return { + "name": card.name, + "aliases": list(card.aliases), + "ordinal": card.ordinal, + "owner_chunk_id": str(card.owner_chunk_id), + "owner_ordinal": card.owner_ordinal, + "passages": [ + { + "label": passage.label, + "char_start": passage.char_start, + "char_end": passage.char_end, + "region": passage.region, + "text": passage.text, + } + for passage in card.passages + ], + } + + +def card_from_payload(*, payload: dict[str, object]) -> GroundedCard: + """Rehydrate one stored card.""" + passages = tuple( + GroundedPassage( + label=str(item["label"]), + char_start=int(item["char_start"]), + char_end=int(item["char_end"]), + region=item["region"], # type: ignore[arg-type] + text=str(item["text"]), + ) + for item in payload["passages"] # type: ignore[union-attr] + ) + return GroundedCard( + name=str(payload["name"]), + aliases=tuple(str(alias) for alias in payload.get("aliases", ())), + passages=passages, + ordinal=int(payload["ordinal"]), + owner_chunk_id=UUID(str(payload["owner_chunk_id"])), + owner_ordinal=int(payload["owner_ordinal"]), + ) diff --git a/src/rememberstack/model/__init__.py b/src/rememberstack/model/__init__.py index 890cf583b..173a32d91 100644 --- a/src/rememberstack/model/__init__.py +++ b/src/rememberstack/model/__init__.py @@ -53,6 +53,7 @@ from rememberstack.model.claims import SelectionOutcome from rememberstack.model.claims import SelectionResponse from rememberstack.model.claims import SelectionVerdict +from rememberstack.model.claims import SourceReferenceCard from rememberstack.model.client import CapabilityReadiness from rememberstack.model.client import ConnectorCreate from rememberstack.model.client import ConnectorDescriptor @@ -604,6 +605,7 @@ "SelectionOutcome", "SelectionDropReason", "SelectionResponse", + "SourceReferenceCard", "SelectionVerdict", "LifecycleReport", "CurrencyTransition", diff --git a/src/rememberstack/model/claims.py b/src/rememberstack/model/claims.py index 683fa7b63..6b4322837 100644 --- a/src/rememberstack/model/claims.py +++ b/src/rememberstack/model/claims.py @@ -130,12 +130,29 @@ def drop_reason(self) -> SelectionDropReason | None: return SelectionDropReason(self.outcome.value.removeprefix(_DROP_PREFIX)) +class SourceReferenceCard(BaseModel): + """One source-backed referent Selection introduced in the target chunk. + + The name is orientation, not evidence. ``source_refs`` cites engine-supplied + passage labels from the same catalog D119 uses for claim evidence. The model + never writes quote strings or character offsets. Local aliases are allowed + only when the shown source itself establishes them. + """ + + model_config = ConfigDict(frozen=True, extra="forbid") + + name: _NonEmpty + aliases: tuple[str, ...] = () + source_refs: tuple[_NonEmpty, ...] + + class SelectionResponse(BaseModel): - """The Selection call's structured output: every judged candidate.""" + """The Selection call's structured output: judged candidates and referents.""" model_config = ConfigDict(frozen=True, extra="forbid") candidates: tuple[SelectionCandidate, ...] + references: tuple[SourceReferenceCard, ...] = () class AddedContext(BaseModel): diff --git a/src/rememberstack/model/relations.py b/src/rememberstack/model/relations.py index c94841f05..2007b494e 100644 --- a/src/rememberstack/model/relations.py +++ b/src/rememberstack/model/relations.py @@ -40,6 +40,7 @@ class RelationCandidate(BaseModel): predicate: _NonEmpty object: EntityRef uses_claim_window: bool = False + context_refs: tuple[EntityRef, ...] = () class ObservationCandidate(BaseModel): @@ -50,6 +51,7 @@ class ObservationCandidate(BaseModel): subject: EntityRef statement: _NonEmpty uses_claim_window: bool = False + context_refs: tuple[EntityRef, ...] = () class ObservationAssertion(BaseModel): @@ -97,3 +99,4 @@ class ResolvedEntity(BaseModel): entity_id: UUID created: bool + decision_id: UUID | None = None diff --git a/src/rememberstack/spine/catalog_contract.py b/src/rememberstack/spine/catalog_contract.py index 9ce1ed072..dd09572e8 100644 --- a/src/rememberstack/spine/catalog_contract.py +++ b/src/rememberstack/spine/catalog_contract.py @@ -105,6 +105,7 @@ ) EXPECTED_TABLES: Final = ( "aliases", + "application_context_bindings", "canary_cases", "chunk_claims", "chunk_search", @@ -173,6 +174,7 @@ "saved_query_versions", "scope_interests", "scopes", + "selection_results", "surface_cost_ledger", "surface_cost_meter_state", "testimony_currency_events", @@ -184,6 +186,7 @@ "ix_aliases_lemma_dm", "ix_aliases_lemma_exact", "ix_aliases_lemma_trgm", + "ix_application_context_entity", "ix_chunkclaims_claim", "ix_chunk_search_bm25", "ix_chunk_search_embedding_hnsw", @@ -267,6 +270,8 @@ "ix_sections_doc", "ix_sections_parent", "ix_sections_role", + "ix_selection_results_representation", + "ix_selection_results_reuse", "ix_skeleton_checks_representation", "ix_structure_generations_representation", "ix_surface_cost_export", @@ -338,7 +343,7 @@ def lane_is_valid(*, stage: str, lane: str | None) -> bool: # PostgreSQL 19 represents NOT NULL declarations as first-class `n` rows in # pg_constraint. The catalog contract pins them with the other structural # constraint kinds instead of pretending the database still exposes PG16's shape. -EXPECTED_CONSTRAINT_COUNTS: Final = {"c": 90, "f": 130, "n": 562, "p": 72, "u": 38} +EXPECTED_CONSTRAINT_COUNTS: Final = {"c": 93, "f": 133, "n": 576, "p": 74, "u": 39} DECISION_OBJECTS: Final = { "D1": ("pipeline_component_versions",), "D2": ("claims", "relations", "relation_evidence"), @@ -377,6 +382,8 @@ def lane_is_valid(*, stage: str, lane: str | None) -> bool: "ix_claims_current_bm25", ), "D102": ("document_entity_bindings",), + "D122": ("selection_results",), + "D123": ("application_context_bindings",), } diff --git a/src/rememberstack/spine/fact_adjudication.py b/src/rememberstack/spine/fact_adjudication.py index 24cbc3057..906256eba 100644 --- a/src/rememberstack/spine/fact_adjudication.py +++ b/src/rememberstack/spine/fact_adjudication.py @@ -30,9 +30,17 @@ from rememberstack.spine.fact_applications import PreparedApplication from rememberstack.spine.fact_applications import snapshot_hash -RELATION_APPLICATION_VERSION = "relation-adjudicator-2026.09d:concise-handles-5" -OBSERVATION_APPLICATION_VERSION = "obs-adjudicator-2026.09d:concise-handles-5" -FACT_NORMALIZER_VERSION = "e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:no-types-1:binary-t4-1:document-t0-1:mutable-window-1:assertion-clarity-3" +RELATION_APPLICATION_VERSION = ( + "relation-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1" +) +OBSERVATION_APPLICATION_VERSION = ( + "obs-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1" +) +FACT_NORMALIZER_VERSION = ( + "e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:no-types-1:" + "binary-t4-1:document-t0-1:mutable-window-1:assertion-clarity-3:" + "d123-context-refs-1" +) FACT_FLUSH_VERSION = f"e3-obs-flush:entity-fanout-1:{FACT_NORMALIZER_VERSION}:{RELATION_APPLICATION_VERSION}:{OBSERVATION_APPLICATION_VERSION}" _FACT_PROMPT = """Decide how ONE incoming assertion belongs in the fact store and whether @@ -44,6 +52,9 @@ that claim. A fact is the stored interpretation of testimony about that proposition. An entity is a person, event, place, or other referent. Sharing an entity does not make two assertions the same proposition. +Context entities named on an assertion are other referents the source mentioned. +They help find related facts; they do not prove two assertions are the same fact. +Empty context does not mean the assertion is new. IDENTITY AND EVIDENCE Choose an existing supplied fact or declare a new fact whose content comes from diff --git a/src/rememberstack/spine/fact_application_inputs.py b/src/rememberstack/spine/fact_application_inputs.py index 043eb4f94..0814c2b33 100644 --- a/src/rememberstack/spine/fact_application_inputs.py +++ b/src/rememberstack/spine/fact_application_inputs.py @@ -15,6 +15,7 @@ # Bounds limit model input, never certify complete identity/evidence coverage. _FACT_LIMIT = 20 +_CONTEXT_FACT_LIMIT = 8 _CLAIM_LIMIT = 100 _ASSERTION_LIMIT = 100 @@ -129,9 +130,112 @@ def application_snapshot( FROM {table} f {joins} WHERE f.deployment_id=:deployment_id AND f.subject_entity_id=ANY(:members) AND f.invalidated_at IS NULL) - SELECT fact_id FROM block ORDER BY tier, rank DESC, fact_id LIMIT {_FACT_LIMIT}""" - nominated = _rows(connection=connection, sql=selection, params=params) - params["fact_ids"] = sorted(row["fact_id"] for row in nominated) + SELECT fact_id, tier, rank FROM block ORDER BY tier, rank DESC, fact_id LIMIT {_FACT_LIMIT}""" + context_members = _context_member_ids( + connection=connection, + deployment_id=deployment_id, + root=root, + application=incoming[0], + ) + params["context_members"] = context_members + extra_sql = f""" + SELECT f.{id_column} AS fact_id, + CASE WHEN {exact} THEN 0 ELSE 1 END AS tier, + ts_rank_cd(to_tsvector('simple',{content}),plainto_tsquery('simple',:query)) AS rank + FROM {table} f {joins} + WHERE f.deployment_id=:deployment_id AND f.subject_entity_id=ANY(:members) + AND f.invalidated_at IS NULL + AND NOT f.{id_column} = ANY(CAST(:baseline_ids AS uuid[])) + AND EXISTS ( + SELECT 1 FROM fact_applications a JOIN claims c + ON c.deployment_id=a.deployment_id AND c.claim_id=a.claim_id + WHERE a.deployment_id=:deployment_id + AND a.{pointer}=f.{id_column} + AND a.applied_at IS NOT NULL + AND a.support_stance='supports' + AND c.is_current_testimony + AND ( + EXISTS ( + SELECT 1 FROM application_context_bindings b + WHERE b.deployment_id=a.deployment_id + AND b.application_id=a.application_id + AND b.entity_id=ANY(CAST(:context_members AS uuid[])) + AND NOT b.entity_id=ANY(CAST(:members AS uuid[])) + ) + OR ( + a.object_entity_id IS NOT NULL + AND a.object_entity_id=ANY(CAST(:context_members AS uuid[])) + AND NOT a.object_entity_id=ANY(CAST(:members AS uuid[])) + ) + ) + ) + ORDER BY tier, rank DESC, fact_id LIMIT {_CONTEXT_FACT_LIMIT}""" + + def _nominate_fact_ids() -> list[Any]: + baseline = _rows(connection=connection, sql=selection, params=params) + extra: list[dict[str, Any]] = [] + if context_members and baseline: + extra = _rows( + connection=connection, + sql=extra_sql, + params={ + **params, + "baseline_ids": [row["fact_id"] for row in baseline], + }, + ) + by_id = {row["fact_id"]: row for row in baseline} + for row in extra: + by_id.setdefault(row["fact_id"], row) + shared_ids = {row["fact_id"] for row in extra} + if context_members and baseline: + shared_ids.update( + row["fact_id"] + for row in _rows( + connection=connection, + sql=f""" + SELECT f.{id_column} AS fact_id FROM {table} f + WHERE f.deployment_id=:deployment_id AND f.{id_column}=ANY(CAST(:shared_probe AS uuid[])) + AND EXISTS ( + SELECT 1 FROM fact_applications a JOIN claims c + ON c.deployment_id=a.deployment_id AND c.claim_id=a.claim_id + WHERE a.deployment_id=:deployment_id + AND a.{pointer}=f.{id_column} + AND a.applied_at IS NOT NULL + AND a.support_stance='supports' + AND c.is_current_testimony + AND ( + EXISTS ( + SELECT 1 FROM application_context_bindings b + WHERE b.deployment_id=a.deployment_id + AND b.application_id=a.application_id + AND b.entity_id=ANY(CAST(:context_members AS uuid[])) + AND NOT b.entity_id=ANY(CAST(:members AS uuid[])) + ) + OR ( + a.object_entity_id IS NOT NULL + AND a.object_entity_id=ANY(CAST(:context_members AS uuid[])) + AND NOT a.object_entity_id=ANY(CAST(:members AS uuid[])) + ) + ) + )""", + params={ + **params, + "shared_probe": [row["fact_id"] for row in baseline], + }, + ) + ) + ordered = sorted( + by_id.values(), + key=lambda row: ( + 0 if row["fact_id"] in shared_ids else 1, + int(row["tier"]), + -float(row["rank"] or 0), + str(row["fact_id"]), + ), + ) + return [row["fact_id"] for row in ordered] + + params["fact_ids"] = _nominate_fact_ids() # Keep complete support membership in the fingerprint, but cap model copies. claim_selection = f"""SELECT c.claim_id FROM claims c WHERE c.deployment_id=:deployment_id AND (c.claim_id=:claim_id OR EXISTS ( @@ -154,10 +258,7 @@ def application_snapshot( params, ).all() # A lifecycle/review writer may have completed while these row locks waited. - if { - row["fact_id"] - for row in _rows(connection=connection, sql=selection, params=params) - } != set(params["fact_ids"]) or { + if set(_nominate_fact_ids()) != set(params["fact_ids"]) or { row["claim_id"] for row in _rows(connection=connection, sql=claim_selection, params=params) } != set(params["claim_ids"]): @@ -176,6 +277,8 @@ def application_snapshot( """, params=params, ) + order_index = {fact_id: index for index, fact_id in enumerate(params["fact_ids"])} + facts.sort(key=lambda fact: order_index[fact["fact_id"]]) for fact in facts: fact["window_claim_ids"] = sorted(fact["window_claim_ids"]) claims = _rows( @@ -247,6 +350,48 @@ def application_snapshot( """, params=params, ) + binding_hash = _digest_rows( + connection=connection, + sql=f""" + SELECT a.application_id,a.support_stance,c.is_current_testimony,c.claim_id, + b.ordinal,b.entity_id,b.resolver_decision_id + FROM fact_applications a + JOIN claims c ON c.deployment_id=a.deployment_id AND c.claim_id=a.claim_id + LEFT JOIN application_context_bindings b + ON b.deployment_id=a.deployment_id AND b.application_id=a.application_id + WHERE a.deployment_id=:deployment_id + AND ( + a.application_id=:application_id + OR a.{pointer}=ANY(CAST(:fact_ids AS uuid[])) + OR ( + a.subject_entity_id=ANY(CAST(:members AS uuid[])) + AND a.applied_at IS NOT NULL + AND a.support_stance='supports' + AND c.is_current_testimony + AND ( + b.entity_id=ANY(CAST(:context_members AS uuid[])) + OR ( + a.object_entity_id IS NOT NULL + AND a.object_entity_id=ANY(CAST(:context_members AS uuid[])) + ) + ) + ) + ) + ORDER BY a.application_id, b.ordinal NULLS FIRST + """, + params=params, + ) + canonical_membership_hash = _digest_rows( + connection=connection, + sql=""" + SELECT member_id FROM unnest(CAST(:context_members AS uuid[])) AS members(member_id) + ORDER BY member_id + """, + params=params, + ) + context_hash = sha256( + f"{binding_hash}\n{canonical_membership_hash}".encode() + ).hexdigest() all_assertions = sorted( [*incoming, *assertions], key=lambda row: row["application_id"] ) @@ -279,12 +424,57 @@ def application_snapshot( "membership_hash": member_hash, "evidence_hash": evidence_hash, "support_hash": support_hash, + "context_hash": context_hash, + "context_member_ids": [str(entity_id) for entity_id in context_members], + "context_truncated": len(assertion.get("context_refs") or []) > 4, "limits": { "facts": _FACT_LIMIT, + "context_facts": _CONTEXT_FACT_LIMIT, "claims": _CLAIM_LIMIT, "assertions": _ASSERTION_LIMIT, }, - "potentially_truncated": len(facts) == _FACT_LIMIT + "potentially_truncated": len(facts) >= _FACT_LIMIT or len(claims) == _CLAIM_LIMIT or len(assertions) == _ASSERTION_LIMIT, } + + +def _context_member_ids( + *, + connection: Connection, + deployment_id: UUID, + root: UUID, + application: Mapping[str, Any], +) -> list[UUID]: + """Canonical reverse-closure of incoming context, excluding the subject.""" + rows = _rows( + connection=connection, + sql=""" + SELECT entity_id FROM application_context_bindings + WHERE deployment_id=:deployment_id AND application_id=:application_id + ORDER BY ordinal + """, + params={ + "deployment_id": deployment_id, + "application_id": application["application_id"], + }, + ) + entity_ids = [UUID(str(row["entity_id"])) for row in rows] + object_id = application.get("object_entity_id") + if object_id is not None: + entity_ids.append(UUID(str(object_id))) + members: list[UUID] = [] + seen: set[UUID] = set() + for entity_id in entity_ids: + canonical = canonical_entity( + connection=connection, deployment_id=deployment_id, entity_id=entity_id + ) + if canonical == root: + continue + for member in entity_members( + connection=connection, deployment_id=deployment_id, root=canonical + ): + if member not in seen: + seen.add(member) + members.append(member) + return members diff --git a/src/rememberstack/spine/fact_applications.py b/src/rememberstack/spine/fact_applications.py index 6580bb019..0a8f0f7e1 100644 --- a/src/rememberstack/spine/fact_applications.py +++ b/src/rememberstack/spine/fact_applications.py @@ -251,8 +251,16 @@ def stage( subject_entity_id: UUID, object_entity_id: UUID | None, version_ids: tuple[UUID, ...], + context_bindings: tuple[tuple[int, UUID, UUID], ...] = (), ) -> UUID: - """Register one accepted assertion and all known source-version memberships.""" + """Register one accepted assertion, complete context, and version memberships. + + ``context_bindings`` is the complete ordinal/entity/decision set. Empty + is valid. The application is not visible without that complete set. + """ + ordinals = [item[0] for item in context_bindings] + if len(set(ordinals)) != len(ordinals): + raise ValueError("context binding ordinals cannot repeat") params = { "deployment_id": deployment_id, "claim_id": claim_id, @@ -268,7 +276,7 @@ def stage( self._engine.begin() as connection, application_fence(connection=connection, deployment_id=deployment_id), ): - connection.execute( + inserted = connection.execute( text(""" INSERT INTO fact_applications(application_id,deployment_id,claim_id,normalizer_version, output_kind,output_ordinal,adjudicator_version,subject_entity_id,object_entity_id) @@ -279,9 +287,10 @@ def stage( AND EXISTS (SELECT 1 FROM jsonb_array_elements(n.accepted_outputs) x WHERE x->>'kind'=:kind AND (x->>'ordinal')::int=:ordinal) ON CONFLICT DO NOTHING + RETURNING application_id """), params, - ) + ).scalar_one_or_none() app = ( connection.execute( text(""" @@ -295,6 +304,50 @@ def stage( .one() ) params["application_id"] = app["application_id"] + if inserted is not None: + seen_entities: set[UUID] = set() + for bind_ordinal, entity_id, decision_id in context_bindings: + if entity_id in seen_entities: + continue + seen_entities.add(entity_id) + bind_params = { + **params, + "ordinal": bind_ordinal, + "entity_id": entity_id, + "decision_id": decision_id, + } + valid = connection.execute( + text(""" + SELECT 1 FROM resolution_decisions d + WHERE d.deployment_id=:deployment_id + AND d.decision_id=:decision_id + AND d.entity_id=:entity_id + AND d.superseded_by IS NULL + AND EXISTS ( + SELECT 1 FROM mentions m + WHERE m.mention_id=d.mention_id + AND m.deployment_id=:deployment_id + AND m.claim_id=:claim_id + ) + """), + bind_params, + ).scalar_one_or_none() + if valid is None: + raise ValueError( + "context binding must cite a live resolver decision " + "for this claim and entity" + ) + connection.execute( + text(""" + INSERT INTO application_context_bindings( + deployment_id, application_id, ordinal, entity_id, + resolver_decision_id) + VALUES (:deployment_id, :application_id, :ordinal, :entity_id, + :decision_id) + ON CONFLICT DO NOTHING + """), + bind_params, + ) # Already applied applications still get memberships. The barrier must see # their entity unit before receipt-based retirement; no support is relinked. for version_id in sorted(set(version_ids)): diff --git a/src/rememberstack/spine/forget.py b/src/rememberstack/spine/forget.py index c213e44c4..8e3f1843c 100644 --- a/src/rememberstack/spine/forget.py +++ b/src/rememberstack/spine/forget.py @@ -1185,6 +1185,9 @@ def _text_values( ) _POSTGRES_SCRUB = ( + text( + "DELETE FROM selection_results WHERE deployment_id=:deployment_id AND chunk_id=ANY(CAST(:chunk_ids AS uuid[]))" + ), text( "DELETE FROM fact_applications WHERE deployment_id=:deployment_id AND claim_id=ANY(:claim_ids)" ), @@ -1683,6 +1686,12 @@ def _text_values( FROM ( SELECT 1 FROM normalization_outputs WHERE deployment_id=:deployment_id AND claim_id=ANY(:claim_ids) UNION ALL + SELECT 1 FROM selection_results WHERE deployment_id=:deployment_id AND chunk_id=ANY(CAST(:chunk_ids AS uuid[])) + UNION ALL + SELECT 1 FROM application_context_bindings WHERE deployment_id=:deployment_id AND application_id IN ( + SELECT application_id FROM fact_applications WHERE deployment_id=:deployment_id AND claim_id=ANY(:claim_ids) + ) + UNION ALL SELECT 1 FROM fact_applications WHERE deployment_id=:deployment_id AND claim_id=ANY(:claim_ids) UNION ALL SELECT 1 FROM fact_applications WHERE deployment_id=:deployment_id AND input_claim_ids && CAST(:claim_ids AS uuid[]) diff --git a/src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py b/src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py new file mode 100644 index 000000000..de15ed7ef --- /dev/null +++ b/src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py @@ -0,0 +1,82 @@ +"""D122 frozen Selection results and D123 application context bindings. + +A populated store is not converted. Existing claims and frozen extraction +outputs cannot satisfy the new Selection-result and context-binding +generations; recreate the deployment and ingest sources again. +""" + +from collections.abc import Sequence + +from alembic import op +from sqlalchemy import text + +from rememberstack.spine.migrations._helpers import apply_ddl +from rememberstack.spine.migrations._helpers import drop_tables + +revision: str = "p9_32_0053" +down_revision: str | None = "p9_31_0052" +branch_labels: str | Sequence[str] | None = None +depends_on: str | Sequence[str] | None = None + +_DDL = r""" +CREATE TABLE selection_results ( + deployment_id uuid NOT NULL, + chunk_id uuid NOT NULL, + representation_id uuid NOT NULL, + extractor_version text NOT NULL, + selection_input_hash text NOT NULL, + output jsonb NOT NULL CHECK (jsonb_typeof(output) = 'object'), + cards jsonb NOT NULL CHECK (jsonb_typeof(cards) = 'array'), + truncated boolean NOT NULL DEFAULT false, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (deployment_id, chunk_id, extractor_version), + FOREIGN KEY (deployment_id) REFERENCES deployments (deployment_id) +); +COMMENT ON TABLE selection_results IS + 'D122 frozen Selection responses, including zero-proposition and zero-card results. Cards are source-owned and remapped per consuming chunk occurrence.'; + +CREATE INDEX ix_selection_results_reuse + ON selection_results (deployment_id, selection_input_hash); +CREATE INDEX ix_selection_results_representation + ON selection_results (deployment_id, representation_id, extractor_version); + +CREATE TABLE application_context_bindings ( + deployment_id uuid NOT NULL, + application_id uuid NOT NULL, + ordinal integer NOT NULL CHECK (ordinal >= 0), + entity_id uuid NOT NULL, + resolver_decision_id uuid NOT NULL, + PRIMARY KEY (deployment_id, application_id, ordinal), + UNIQUE (deployment_id, application_id, entity_id), + FOREIGN KEY (deployment_id, application_id) + REFERENCES fact_applications (deployment_id, application_id) ON DELETE CASCADE, + FOREIGN KEY (deployment_id, entity_id) + REFERENCES entities (deployment_id, entity_id) +); +COMMENT ON TABLE application_context_bindings IS + 'D123 immutable source-owned application-to-entity context bindings with stable original ordinals. An application row is the complete (possibly empty) set.'; + +CREATE INDEX ix_application_context_entity + ON application_context_bindings (deployment_id, entity_id, application_id); +""" + + +def upgrade() -> None: + """Refuse a populated store, then add the Selection store and context junction.""" + connection = op.get_bind() + if connection.execute(text("SELECT EXISTS(SELECT 1 FROM claims)")).scalar_one(): + raise RuntimeError( + "D122/D123 do not convert a store that already holds claims; " + "recreate the deployment and ingest its sources again" + ) + apply_ddl(sql=_DDL) + + +def downgrade() -> None: + """Drop additive tables.""" + drop_tables( + table_names=( + "application_context_bindings", + "selection_results", + ) + ) diff --git a/src/rememberstack/spine/resolver.py b/src/rememberstack/spine/resolver.py index 2862df171..16492b621 100644 --- a/src/rememberstack/spine/resolver.py +++ b/src/rememberstack/spine/resolver.py @@ -1027,7 +1027,9 @@ def _record( _BUMP_MENTION_COUNT, {"deployment_id": deployment_id, "entity_id": entity_id}, ) - return ResolvedEntity(entity_id=entity_id, created=created) + return ResolvedEntity( + entity_id=entity_id, created=created, decision_id=decision_id + ) def _upsert_alias( self, diff --git a/src/rememberstack/workers/e3.py b/src/rememberstack/workers/e3.py index 1a6b5bb6d..b75622ae7 100644 --- a/src/rememberstack/workers/e3.py +++ b/src/rememberstack/workers/e3.py @@ -18,6 +18,7 @@ from pydantic_settings import BaseSettings from pydantic_settings import SettingsConfigDict +from rememberstack.core.context_references import attempted_context_refs from rememberstack.model import ClaimedWork from rememberstack.model import ClaimForNormalization from rememberstack.model import EnqueueWork @@ -131,6 +132,16 @@ def _run_profile_refresh(*, action: Callable[[], object], call_key: str) -> None - "Nate said he won Tournament A" → attributed stance on Nate, not an unqualified win. +CONTEXT REFERENCES +For each assertion, list up to four other named entities the claim itself +refers to, besides the subject and besides a relation's object. These help +later matching; they do not change who the assertion is about. +"Joanna said Nate won Tournament A" stays an observation about Joanna; Nate +and Tournament A are context. Equal names can still be different people or +events; do not merge them here. Do not guess entities that are not explicit +in the claim. If more than four apply, keep the first four in emission order. +Overflow must not drop the assertion. An empty list is valid. + SOURCE TIMESTAMP: {asserted_at} CLAIM WORLD WINDOW (inclusive raw source dates): {claim_window} @@ -358,6 +369,40 @@ def _normalize_claim( meter=meter, call_key=f"resolve:{claim.claim_id}:relation:{ordinal}:object", ).entity_id + exclude = {subject.entity_id} + if object_id is not None: + exclude.add(object_id) + attempted, truncated = attempted_context_refs(refs=output.context_refs) + if truncated: + _logger.warning( + "context references truncated for claim %s: kept %s of %s", + claim.claim_id, + len(attempted), + len(output.context_refs), + ) + context_bindings: list[tuple[int, UUID, UUID]] = [] + seen_entities: set[UUID] = set() + for bind_ordinal, ref in attempted: + resolved = self._resolver.resolve( + deployment_id=deployment_id, + reference=ref, + claim=claim, + meter=meter, + call_key=f"resolve:{claim.claim_id}:{kind}:{ordinal}:context:{bind_ordinal}", + ) + if resolved.decision_id is None: + raise NonRetryableHandlerError( + "context resolution produced no validating decision" + ) + if ( + resolved.entity_id in exclude + or resolved.entity_id in seen_entities + ): + continue + seen_entities.add(resolved.entity_id) + context_bindings.append( + (bind_ordinal, resolved.entity_id, resolved.decision_id) + ) catalog.stage( deployment_id=deployment_id, claim_id=claim.claim_id, @@ -370,6 +415,7 @@ def _normalize_claim( subject_entity_id=subject.entity_id, object_entity_id=object_id, version_ids=version_ids, + context_bindings=tuple(context_bindings), ) def _generate_normalize_response( diff --git a/src/tests/core/test_context_references.py b/src/tests/core/test_context_references.py new file mode 100644 index 000000000..7279398c3 --- /dev/null +++ b/src/tests/core/test_context_references.py @@ -0,0 +1,50 @@ +"""Provider-free D123 context-reference cap and original-ordinal tests.""" + +from rememberstack.core.context_references import attempted_context_refs +from rememberstack.core.context_references import MAX_CONTEXT_REFS +from rememberstack.model.relations import EntityRef +from rememberstack.model.relations import NormalizationResponse +from rememberstack.model.relations import ObservationCandidate + + +def test_overflow_keeps_original_ordinals_and_does_not_reject_the_assertion() -> None: + """Auxiliary extras are truncated after the fourth original slot.""" + refs = tuple(EntityRef(name=f"Entity {index}") for index in range(6)) + attempted, truncated = attempted_context_refs(refs=refs) + assert truncated is True + assert [ordinal for ordinal, _ in attempted] == list(range(MAX_CONTEXT_REFS)) + assert [ref.name for _, ref in attempted] == [ + f"Entity {index}" for index in range(4) + ] + response = NormalizationResponse( + observations=( + ObservationCandidate( + subject=EntityRef(name="Joanna"), + statement="Joanna said Nate won Tournament A", + context_refs=refs, + ), + ) + ) + assert response.observations[0].subject.name == "Joanna" + assert len(response.observations[0].context_refs) == 6 + + +def test_equal_names_keep_distinct_original_ordinals() -> None: + """Equal names are not identity before resolution.""" + refs = ( + EntityRef(name="The Open"), + EntityRef(name="Nate"), + EntityRef(name="The Open"), + EntityRef(name="Tournament B"), + ) + attempted, truncated = attempted_context_refs(refs=refs) + assert truncated is False + assert [(ordinal, ref.name) for ordinal, ref in attempted] == [ + (0, "The Open"), + (1, "Nate"), + (2, "The Open"), + (3, "Tournament B"), + ] + empty, empty_truncated = attempted_context_refs(refs=()) + assert empty == () + assert empty_truncated is False diff --git a/src/tests/core/test_selection_references.py b/src/tests/core/test_selection_references.py new file mode 100644 index 000000000..8dba1397e --- /dev/null +++ b/src/tests/core/test_selection_references.py @@ -0,0 +1,387 @@ +"""Provider-free D122 catalog resolution, distinct cards, and complete support.""" + +from uuid import uuid4 + +from rememberstack.core.selection_references import catalog_by_label +from rememberstack.core.selection_references import claimify_input_hash +from rememberstack.core.selection_references import GroundedCard +from rememberstack.core.selection_references import GroundedPassage +from rememberstack.core.selection_references import PassageSupport +from rememberstack.core.selection_references import publish_selection_cards +from rememberstack.core.selection_references import rank_and_fit_cards +from rememberstack.core.selection_references import remap_card +from rememberstack.core.selection_references import render_cards_for_claimify +from rememberstack.model.chunks import ChunkForEmbedding +from rememberstack.model.claims import SourceReferenceCard + + +def _chunk(*, ordinal: int, start: int, end: int, chunk_id=None) -> ChunkForEmbedding: + """Minimal extract-window chunk.""" + return ChunkForEmbedding( + chunk_id=chunk_id or uuid4(), + doc_id=uuid4(), + version_id=uuid4(), + ordinal=ordinal, + char_start=start, + char_end=end, + chunk_content_hash=f"h{ordinal}", + extraction_input_hash=f"e{ordinal}", + section_role="body", + section_path="/root", + ) + + +def _catalog(*passages: PassageSupport) -> dict[str, PassageSupport]: + """Engine-supplied label map.""" + return catalog_by_label(passages=passages) + + +def test_unknown_label_rejects_the_whole_card() -> None: + """A forged citation is not dropped so the remaining supports can keep the name.""" + document = "Nate won the Riverside Cup today." + owner = _chunk(ordinal=0, start=0, end=len(document)) + catalog = _catalog( + PassageSupport(label="S1", char_start=13, char_end=26, region="target") + ) + published, truncated, diagnostics = publish_selection_cards( + cards=( + SourceReferenceCard(name="Riverside Cup", source_refs=("S1", "S-forged")), + ), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert published == () + assert truncated is False + assert diagnostics[0].gate == "unknown_source_ref" + + +def test_neighbour_only_support_is_not_published() -> None: + """Neighbour passages may clarify; they cannot publish the card alone.""" + document = "Earlier the cup was named. Nate won that tournament today." + owner = _chunk(ordinal=1, start=26, end=len(document)) + catalog = _catalog( + PassageSupport(label="S1", char_start=8, char_end=25, region="previous") + ) + published, _, diagnostics = publish_selection_cards( + cards=(SourceReferenceCard(name="the cup", source_refs=("S1",)),), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert published == () + assert diagnostics[0].gate == "no_target_passage" + + +def test_same_name_distinct_ranges_are_both_published() -> None: + """Equal names are not identity; two tournaments stay two cards.""" + document = "The Open on Monday. The Open on Friday." + owner = _chunk(ordinal=0, start=0, end=len(document)) + catalog = _catalog( + PassageSupport(label="S1", char_start=0, char_end=18, region="target"), + PassageSupport(label="S2", char_start=20, char_end=39, region="target"), + ) + published, truncated, diagnostics = publish_selection_cards( + cards=( + SourceReferenceCard(name="The Open", source_refs=("S1",)), + SourceReferenceCard(name="The Open", source_refs=("S2",)), + ), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert truncated is False + assert diagnostics == () + assert [card.ordinal for card in published] == [0, 1] + assert [card.passages[0].char_start for card in published] == [0, 20] + + +def test_two_referents_may_share_one_passage() -> None: + """One paragraph can introduce Nate and Tournament A; range is not identity.""" + document = "Nate won Tournament A today." + owner = _chunk(ordinal=0, start=0, end=len(document)) + catalog = _catalog( + PassageSupport(label="S1", char_start=0, char_end=len(document), region="target") + ) + published, truncated, diagnostics = publish_selection_cards( + cards=( + SourceReferenceCard(name="Nate", source_refs=("S1",)), + SourceReferenceCard(name="Tournament A", source_refs=("S1",)), + ), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert truncated is False + assert diagnostics == () + assert [card.name for card in published] == ["Nate", "Tournament A"] + assert [card.ordinal for card in published] == [0, 1] + assert {card.passages[0].label for card in published} == {"S1"} + + +def test_cap_keeps_first_four_distinct_cards() -> None: + """A fifth distinct card is a recorded cap loss, not a merge.""" + names = ("A Cup", "B Cup", "C Cup", "D Cup", "E Cup") + document = " ".join(names) + owner = _chunk(ordinal=0, start=0, end=len(document)) + cursor = 0 + passages: list[PassageSupport] = [] + for index, name in enumerate(names, start=1): + start = document.find(name, cursor) + passages.append( + PassageSupport( + label=f"S{index}", + char_start=start, + char_end=start + len(name), + region="target", + ) + ) + cursor = start + len(name) + catalog = _catalog(*passages) + published, truncated, diagnostics = publish_selection_cards( + cards=tuple( + SourceReferenceCard(name=name, source_refs=(f"S{index}",)) + for index, name in enumerate(names, start=1) + ), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert truncated is True + assert diagnostics == () + assert [card.name for card in published] == list(names[:4]) + assert [card.ordinal for card in published] == [0, 1, 2, 3] + + +def test_claimify_hash_includes_empty_preceding_producers() -> None: + """A silent earlier chunk is still a negative reuse dependency.""" + with_empty = claimify_input_hash( + target_selection_input_hash="target", + preceding_selection_input_hashes=("a", "empty-producer", "c"), + ) + without = claimify_input_hash( + target_selection_input_hash="target", + preceding_selection_input_hashes=("a", "c"), + ) + competing = claimify_input_hash( + target_selection_input_hash="target", + preceding_selection_input_hashes=("a", "new-introduction", "c"), + ) + assert with_empty != without + assert with_empty != competing + + +def test_rank_prefers_overlap_then_nearer_chunk_then_ordinal() -> None: + """Zero overlap can still admit a nearby pronoun-needed card.""" + owner_a = uuid4() + owner_b = uuid4() + near_no_overlap = GroundedCard( + name="Riverside Cup", + aliases=(), + passages=( + GroundedPassage( + label="S-near", + char_start=0, + char_end=7, + region="target", + text="the cup", + ), + ), + ordinal=1, + owner_chunk_id=owner_a, + owner_ordinal=6, + ) + far_overlap = GroundedCard( + name="City Open", + aliases=(), + passages=( + GroundedPassage( + label="S-far", + char_start=0, + char_end=9, + region="target", + text="City Open", + ), + ), + ordinal=0, + owner_chunk_id=owner_b, + owner_ordinal=1, + ) + same_nearer = GroundedCard( + name="City Open Final", + aliases=(), + passages=( + GroundedPassage( + label="S-nearer", + char_start=0, + char_end=9, + region="target", + text="City Open", + ), + ), + ordinal=0, + owner_chunk_id=owner_b, + owner_ordinal=5, + ) + chosen, truncated = rank_and_fit_cards( + cards=(near_no_overlap, far_overlap, same_nearer), + target_text="Nate won the City Open yesterday.", + target_ordinal=7, + ) + assert truncated is False + assert [card.name for card in chosen] == [ + "City Open Final", + "City Open", + "Riverside Cup", + ] + + +def test_fit_drops_a_whole_card_rather_than_trimming_passages() -> None: + """An over-budget card is omitted; its label is not kept without evidence.""" + huge = GroundedCard( + name="X" * 4000, + aliases=(), + passages=( + GroundedPassage( + label="S-huge", + char_start=0, + char_end=200, + region="target", + text="Y" * 200, + ), + ), + ordinal=0, + owner_chunk_id=uuid4(), + owner_ordinal=0, + ) + small = GroundedCard( + name="Nate", + aliases=(), + passages=( + GroundedPassage( + label="S-nate", char_start=0, char_end=4, region="target", text="Nate" + ), + ), + ordinal=1, + owner_chunk_id=uuid4(), + owner_ordinal=0, + ) + chosen, truncated = rank_and_fit_cards( + cards=(huge, small), target_text="Nate", target_ordinal=1, max_chars=100 + ) + assert truncated is True + assert [card.name for card in chosen] == ["Nate"] + + +def test_remap_rejects_incomplete_or_rescued_mapping() -> None: + """D119 refusal or a dropped support invalidates the card; text is not searched.""" + document = "pad pad Riverside Cup then Riverside Cup later" + second = document.rfind("Riverside Cup") + length = len("Riverside Cup") + card = GroundedCard( + name="Riverside Cup", + aliases=(), + passages=( + GroundedPassage( + label="S1", + char_start=20, + char_end=20 + length, + region="target", + text="Riverside Cup", + ), + ), + ordinal=0, + owner_chunk_id=uuid4(), + owner_ordinal=1, + ) + windows = {"target": (second, second + length)} + assert ( + remap_card( + card=card, remapped_spans=None, current_md=document, current_windows=windows + ) + is None + ) + complete = remap_card( + card=card, + remapped_spans=((second, second + length),), + current_md=document, + current_windows=windows, + ) + assert complete is not None + assert complete.passages[0].char_start == second + assert complete.passages[0].label == "S1" + + +def test_claimify_labels_are_request_unique_and_keep_source_ids() -> None: + """Two owners can both emit R-ordinal 0; the request still gets R1 and R2.""" + owner_a = uuid4() + owner_b = uuid4() + nate = GroundedCard( + name="Nate", + aliases=(), + passages=( + GroundedPassage( + label="S1", char_start=0, char_end=4, region="target", text="Nate" + ), + ), + ordinal=0, + owner_chunk_id=owner_a, + owner_ordinal=1, + ) + tournament = GroundedCard( + name="Tournament A", + aliases=("the cup",), + passages=( + GroundedPassage( + label="S2", + char_start=9, + char_end=21, + region="target", + text="Tournament A", + ), + ), + ordinal=0, + owner_chunk_id=owner_b, + owner_ordinal=2, + ) + rendered = render_cards_for_claimify(cards=(nate, tournament)) + assert rendered.startswith("R1: Nate") + assert "R2: Tournament A also called the cup" in rendered + assert ' S1: "Nate"' in rendered + assert ' S2: "Tournament A"' in rendered + assert rendered.count("R1:") == 1 + assert rendered.count("R2:") == 1 + + +def test_character_cap_counts_the_rendered_block() -> None: + """The 4096 bound includes labels and formatting, not only raw name text.""" + card = GroundedCard( + name="Nate", + aliases=(), + passages=( + GroundedPassage( + label="S1", char_start=0, char_end=4, region="target", text="Nate" + ), + ), + ordinal=0, + owner_chunk_id=uuid4(), + owner_ordinal=0, + ) + rendered = render_cards_for_claimify(cards=(card,)) + assert len(rendered) > len("NateNate") + chosen, truncated = rank_and_fit_cards( + cards=(card,), + target_text="Nate", + target_ordinal=1, + max_chars=len(rendered) - 1, + ) + assert truncated is True + assert chosen == () + kept, kept_truncated = rank_and_fit_cards( + cards=(card,), + target_text="Nate", + target_ordinal=1, + max_chars=len(rendered), + ) + assert kept_truncated is False + assert kept == (card,) diff --git a/src/tests/database_reset.py b/src/tests/database_reset.py index 2042994b6..1a24ff442 100644 --- a/src/tests/database_reset.py +++ b/src/tests/database_reset.py @@ -34,8 +34,12 @@ def reset_database(*, config: Config) -> None: text("SELECT version_num FROM alembic_version") ).scalar_one_or_none() if ( - revision == "p9_31_0052" - or revision == "p9_30_0051" + revision + in { + "p9_30_0051", + "p9_31_0052", + "p9_32_0053", + } or connection.execute( text("SELECT to_regclass('public.fact_applications') IS NOT NULL") ).scalar_one() diff --git a/src/tests/fact_application_support.py b/src/tests/fact_application_support.py index 2dfe4cfb9..f2b97f3eb 100644 --- a/src/tests/fact_application_support.py +++ b/src/tests/fact_application_support.py @@ -92,14 +92,22 @@ def stage( predicate: str = "related_to", uses_claim_window: bool = True, precision: Literal["day", "open"] = "day", + statement: str | None = None, + context_entities: tuple[UUID, ...] = (), + context_bindings: tuple[tuple[int, UUID, UUID], ...] = (), + context_ref_names: tuple[str, ...] = (), ) -> tuple[UUID, UUID]: """Freeze one dated source assertion and stage its original output ordinal. ``uses_claim_window=False`` models a normalizer that did not attribute the claim's dates to this assertion, so a new fact starts undated. ``precision="open"`` supplies an explicitly ongoing source window. + ``context_entities`` records real resolver decisions for those ids. + ``context_bindings`` passes already-built ordinal/entity/decision triples, + including invented ids used to prove staging rejection. """ claim = uuid4() + doc_id = uuid4() instant = datetime(2022, 5, day, tzinfo=timezone.utc) with self.engine.begin() as connection: connection.execute( @@ -111,7 +119,7 @@ def stage( { "claim": claim, "dep": self.dep, - "doc": uuid4(), + "doc": doc_id, "chunk": uuid4(), "at": instant, "end": None if precision == "open" else instant, @@ -128,7 +136,9 @@ def stage( if kind == "relation": item.update(predicate=predicate, object={"name": "Riverside Cup"}) else: - item["statement"] = "Nate won the Riverside final" + item["statement"] = statement or "Nate won the Riverside final" + if context_ref_names: + item["context_refs"] = [{"name": name} for name in context_ref_names] response = NormalizationResponse.model_validate({f"{kind}s": [item]}) self.catalog.publish_normalization( deployment_id=self.dep, @@ -137,6 +147,21 @@ def stage( output=response, accepted=((kind, 0),), ) # type: ignore[arg-type] + bindings = context_bindings + if context_entities: + bindings = tuple( + ( + ordinal, + entity_id, + self.record_resolution( + claim_id=claim, + doc_id=doc_id, + entity_id=entity_id, + name="Riverside Cup", + ), + ) + for ordinal, entity_id in enumerate(context_entities) + ) app = self.catalog.stage( deployment_id=self.dep, claim_id=claim, @@ -149,9 +174,42 @@ def stage( subject_entity_id=self.subject, object_entity_id=self.object if kind == "relation" else None, version_ids=(self.version,), + context_bindings=bindings, ) # type: ignore[arg-type] return claim, app + def record_resolution( + self, *, claim_id: UUID, doc_id: UUID, entity_id: UUID, name: str + ) -> UUID: + """Insert one live mention and resolver decision for this claim.""" + mention_id = uuid4() + decision_id = uuid4() + with self.engine.begin() as connection: + connection.execute( + text("""INSERT INTO mentions(mention_id,deployment_id,surface_form, + normalized_lemma,canonical_name_form,claim_id,doc_id) + VALUES(:mention,:dep,:name,lower(:name),:name,:claim,:doc)"""), + { + "mention": mention_id, + "dep": self.dep, + "name": name, + "claim": claim_id, + "doc": doc_id, + }, + ) + connection.execute( + text("""INSERT INTO resolution_decisions(decision_id,deployment_id, + mention_id,entity_id,method,confidence,resolver_version) + VALUES(:decision,:dep,:mention,:entity,'T0',1.0,'test')"""), + { + "decision": decision_id, + "dep": self.dep, + "mention": mention_id, + "entity": entity_id, + }, + ) + return decision_id + def decide(self, *, decision: dict[str, object]) -> UUID: """Publish a supplied answer for the actual locked prepared head.""" prepared = self.writer.prepare( diff --git a/src/tests/spine/test_d123_context_nomination.py b/src/tests/spine/test_d123_context_nomination.py new file mode 100644 index 000000000..a2177c17c --- /dev/null +++ b/src/tests/spine/test_d123_context_nomination.py @@ -0,0 +1,258 @@ +"""PostgreSQL acceptance for D123 application context bindings and extra nomination.""" + +from collections.abc import Iterator +from pathlib import Path +from uuid import UUID +from uuid import uuid4 + +from alembic import command +from alembic.config import Config +from pydantic import ValidationError +import pytest +from sqlalchemy import create_engine +from sqlalchemy import text +from sqlalchemy.engine import Engine + +from rememberstack.model.relations import EntityRef +from rememberstack.model.relations import NormalizationResponse +from rememberstack.model.relations import ObservationCandidate +from rememberstack.spine.fact_application_inputs import application_snapshot +from rememberstack.spine.fact_applications import application_block +from rememberstack.spine.settings import load_database_settings +from tests.database_reset import reset_database +from tests.fact_application_support import WriterCase + +_ROOT = Path(__file__).resolve().parents[3] + + +@pytest.fixture(scope="module") +def database_engine() -> Iterator[Engine]: + """Use the isolated D122 integration database at the real schema head.""" + try: + url = load_database_settings().sqlalchemy_url() + except ValidationError: + pytest.skip("REMEMBERSTACK_DATABASE_URL is required for writer acceptance") + config = Config(str(_ROOT / "alembic.ini")) + config.set_main_option("sqlalchemy.url", url) + reset_database(config=config) + command.upgrade(config=config, revision="head") + engine = create_engine(url) + try: + yield engine + finally: + engine.dispose() + + +def _tournament(*, engine: Engine, case: WriterCase) -> UUID: + """A third entity used only as source-backed context, never the subject.""" + entity_id = uuid4() + with engine.begin() as connection: + connection.execute( + text("""INSERT INTO entities(entity_id,deployment_id,canonical_name,normalized_name) + VALUES(:entity,:dep,'Riverside Cup','riverside cup')"""), + {"entity": entity_id, "dep": case.dep}, + ) + return entity_id + + +def _snapshot(*, engine: Engine, case: WriterCase, app: UUID) -> dict[str, object]: + """Re-read nomination inputs under the ordinary application lock.""" + with engine.begin() as connection: + with application_block( + connection=connection, + deployment_id=case.dep, + subject_entity_id=case.subject, + ) as (root, members): + application = ( + connection.execute( + text("SELECT * FROM fact_applications WHERE application_id=:id"), + {"id": app}, + ) + .mappings() + .one() + ) + return application_snapshot( + connection=connection, + deployment_id=case.dep, + root=root, + members=members, + application=dict(application), + ) + + +def test_overflow_context_refs_do_not_reject_the_assertion() -> None: + """Auxiliary extras stay on the frozen response; staging uses the first four.""" + refs = tuple(EntityRef(name=f"Entity {index}") for index in range(6)) + response = NormalizationResponse( + observations=( + ObservationCandidate( + subject=EntityRef(name="Joanna"), + statement="Joanna said Nate won Tournament A", + context_refs=refs, + ), + ) + ) + assert response.observations[0].subject.name == "Joanna" + assert len(response.observations[0].context_refs) == 6 + + +def test_complete_bindings_are_written_with_the_application( + database_engine: Engine, +) -> None: + """Publishing the application and its junction rows is the complete set.""" + case = WriterCase(engine=database_engine) + tournament = _tournament(engine=database_engine, case=case) + _, app = case.stage(day=10, context_entities=(tournament,)) + with database_engine.connect() as connection: + columns = { + row[0] + for row in connection.execute( + text( + """SELECT column_name FROM information_schema.columns + WHERE table_name='fact_applications'""" + ) + ) + } + assert "context_complete" not in columns + bindings = connection.execute( + text( + """SELECT ordinal, entity_id, resolver_decision_id + FROM application_context_bindings WHERE application_id=:id + ORDER BY ordinal""" + ), + {"id": app}, + ).all() + assert len(bindings) == 1 + assert bindings[0][0] == 0 + assert bindings[0][1] == tournament + assert bindings[0][2] is not None + exists = connection.execute( + text( + """SELECT 1 FROM resolution_decisions + WHERE decision_id=:decision AND entity_id=:entity + AND superseded_by IS NULL""" + ), + {"decision": bindings[0][2], "entity": tournament}, + ).scalar_one() + assert exists == 1 + + +def test_invented_resolver_decision_is_rejected(database_engine: Engine) -> None: + """Staging validates the live claim/entity decision, not an unverified UUID.""" + case = WriterCase(engine=database_engine) + tournament = _tournament(engine=database_engine, case=case) + with pytest.raises(ValueError, match="live resolver decision"): + case.stage(day=10, context_bindings=((0, tournament, uuid4()),)) + + +def test_duplicate_resolved_entity_keeps_the_first_ordinal( + database_engine: Engine, +) -> None: + """Two aliases of one entity do not abort the assertion.""" + case = WriterCase(engine=database_engine) + tournament = _tournament(engine=database_engine, case=case) + _, app = case.stage(day=10, context_entities=(tournament, tournament)) + with database_engine.connect() as connection: + bindings = connection.execute( + text( + """SELECT ordinal, entity_id FROM application_context_bindings + WHERE application_id=:id ORDER BY ordinal""" + ), + {"id": app}, + ).all() + assert bindings == [(0, tournament)] + + +def test_empty_context_still_nominates_the_baseline(database_engine: Engine) -> None: + """An empty context search is not a new-fact authorization.""" + case = WriterCase(engine=database_engine) + _, _, fact = case.first() + _, app = case.stage(day=12, statement="Nate enjoyed the Riverside final") + snapshot = _snapshot(engine=database_engine, case=case, app=app) + assert fact in {row["fact_id"] for row in snapshot["facts"]} + assert snapshot["context_hash"] + assert snapshot["context_member_ids"] == [] + assert snapshot["context_truncated"] is False + + +def test_frozen_overflow_is_visible_on_the_snapshot(database_engine: Engine) -> None: + """Auxiliary truncation is the frozen extra refs, not a separate completion flag.""" + case = WriterCase(engine=database_engine) + names = tuple(f"Entity {index}" for index in range(6)) + _, app = case.stage(day=10, context_ref_names=names) + snapshot = _snapshot(engine=database_engine, case=case, app=app) + assertion = snapshot["assertions"][0]["assertion"] + assert len(assertion["context_refs"]) == 6 + assert snapshot["context_truncated"] is True + + +def test_canonical_membership_changes_the_context_fingerprint( + database_engine: Engine, +) -> None: + """A merge that changes context reverse-closure must change validation.""" + case = WriterCase(engine=database_engine) + tournament = _tournament(engine=database_engine, case=case) + alias = uuid4() + with database_engine.begin() as connection: + connection.execute( + text("""INSERT INTO entities(entity_id,deployment_id,canonical_name,normalized_name) + VALUES(:entity,:dep,'Riverside Final','riverside final')"""), + {"entity": alias, "dep": case.dep}, + ) + _, app = case.stage(day=10, context_entities=(alias,)) + before = _snapshot(engine=database_engine, case=case, app=app) + with database_engine.begin() as connection: + connection.execute( + text( + "UPDATE entities SET merged_into=:survivor WHERE entity_id=:absorbed" + ), + {"survivor": tournament, "absorbed": alias}, + ) + after = _snapshot(engine=database_engine, case=case, app=app) + assert before["context_hash"] != after["context_hash"] + assert str(alias) in after["context_member_ids"] + assert str(tournament) in after["context_member_ids"] + + +def test_context_extra_does_not_displace_baseline_targets( + database_engine: Engine, +) -> None: + """The additional eight cannot push out a fact the baseline 20 would include.""" + case = WriterCase(engine=database_engine) + tournament = _tournament(engine=database_engine, case=case) + _, win_app = case.stage( + day=10, + statement="Nate took first place in May", + context_entities=(tournament,), + ) + case.decide( + decision={ + "target": {"new_handle": "win"}, + "new_facts": [{"handle": "win", "assertion_application_id": str(win_app)}], + } + ) + win = UUID(case.apply(app=win_app)["fact_id"]) + for index in range(20): + _claim, filler = case.stage( + day=11, statement=f"Nate enjoyed practice session {index}" + ) + case.decide( + decision={ + "target": {"new_handle": f"f{index}"}, + "new_facts": [ + {"handle": f"f{index}", "assertion_application_id": str(filler)} + ], + } + ) + case.apply(app=filler) + del _claim + _, enjoy = case.stage( + day=12, + statement="Nate enjoyed the Riverside final", + context_entities=(tournament,), + ) + snapshot = _snapshot(engine=database_engine, case=case, app=enjoy) + fact_ids = [row["fact_id"] for row in snapshot["facts"]] + assert win in fact_ids + assert len(fact_ids) <= 28 + assert len(fact_ids) >= 20 diff --git a/src/tests/spine/test_migrations.py b/src/tests/spine/test_migrations.py index 2e055dc49..0e27855dc 100644 --- a/src/tests/spine/test_migrations.py +++ b/src/tests/spine/test_migrations.py @@ -132,6 +132,7 @@ def test_revision_graph_is_one_linear_structural_chain() -> None: "p9_29_0050", "p9_30_0051", "p9_31_0052", + "p9_32_0053", ) assert len(script.get_heads()) == 1 @@ -648,7 +649,7 @@ def test_postgresql_fresh_downgrade_reupgrade_mutation_and_noop_lifecycle() -> N "observation_evidence": 64, "relation_evidence": 64, } - assert len(fresh_inventory.tables) == 72 + assert len(fresh_inventory.tables) == 74 assert fresh_inventory.empty_tables == ("deployments", "entity_types", "predicates") engine = create_engine(database_url) @@ -670,7 +671,7 @@ def test_postgresql_fresh_downgrade_reupgrade_mutation_and_noop_lifecycle() -> N head_before_noop = _head_revision(database_url=database_url) command.upgrade(config=config, revision="head") head_after_noop = _head_revision(database_url=database_url) - assert head_before_noop == head_after_noop == "p9_31_0052" + assert head_before_noop == head_after_noop == "p9_32_0053" assert _inventory(database_url=database_url) == restored_inventory @@ -1258,4 +1259,48 @@ def test_d118_refuses_lossy_downgrade() -> None: command.upgrade(config=config, revision="head") with pytest.raises(RuntimeError, match="explicitly reviewed restore/conversion"): command.downgrade(config=config, revision="p9_27_0048") - assert _head_revision(database_url=database_url) == "p9_31_0052" + assert _head_revision(database_url=database_url) == "p9_32_0053" + + +def test_d122_refuses_a_populated_store() -> None: + """The real migration refuses existing claims instead of converting them.""" + database_url = _database_url() + config = _alembic_config(database_url=database_url) + reset_database(config=config) + command.upgrade(config=config, revision="p9_31_0052") + engine = create_engine(database_url) + try: + with engine.begin() as connection: + deployment_id = uuid4() + connection.execute( + text( + "INSERT INTO deployments (deployment_id, slug, name, raw_bucket," + " artifacts_bucket, corpusfs_bucket) VALUES" + " (:deployment, 'd122-refuse', 'D122 refuse', 'mem://raw'," + " 'mem://artifacts', 'mem://corpusfs')" + ), + {"deployment": deployment_id}, + ) + connection.execute( + text( + """INSERT INTO claims(claim_id,deployment_id,doc_id,chunk_id,claim_text, + source_span,char_start,char_end,anchor_ok,window_membership_ok, + extractor_version) + VALUES(:claim,:deployment,:doc,:chunk,'populated store','populated store', + 0,15,true,true,'test')""" + ), + { + "claim": uuid4(), + "deployment": deployment_id, + "doc": uuid4(), + "chunk": uuid4(), + }, + ) + with pytest.raises(RuntimeError, match="do not convert a store"): + command.upgrade(config=config, revision="p9_32_0053") + assert _head_revision(database_url=database_url) == "p9_31_0052" + finally: + engine.dispose() + reset_database(config=config) + command.upgrade(config=config, revision="head") + assert _head_revision(database_url=database_url) == "p9_32_0053" diff --git a/src/tests/workers/e3_test_doubles.py b/src/tests/workers/e3_test_doubles.py index dc22168a0..3e7e7ed75 100644 --- a/src/tests/workers/e3_test_doubles.py +++ b/src/tests/workers/e3_test_doubles.py @@ -40,9 +40,11 @@ def record( class RecordingResolver: """Resolver that records resolve calls.""" - def __init__(self) -> None: - """Start with an empty call log.""" + def __init__(self, *, identities: dict[str, object] | None = None) -> None: + """Start with an empty call log and optional exact-name identities.""" self.calls: list[EntityRef] = [] + self.identities = dict(identities or {}) + self.resolved: list[ResolvedEntity] = [] def resolve( self, @@ -56,7 +58,12 @@ def resolve( """Record the reference and return a synthetic entity id.""" del deployment_id, claim, meter, call_key self.calls.append(reference) - return ResolvedEntity(entity_id=uuid4(), created=True) + entity_id = self.identities.get(reference.name, uuid4()) + resolved = ResolvedEntity( + entity_id=entity_id, created=True, decision_id=uuid4() # type: ignore[arg-type] + ) + self.resolved.append(resolved) + return resolved class RecordingFacts: diff --git a/src/tests/workers/test_e3_context_references.py b/src/tests/workers/test_e3_context_references.py new file mode 100644 index 000000000..e62081ddb --- /dev/null +++ b/src/tests/workers/test_e3_context_references.py @@ -0,0 +1,119 @@ +"""E3 context-reference resolution uses canonical ids, not casefolded names.""" + +from uuid import uuid4 + +from rememberstack.adapters.testing import FakeModelProvider +from rememberstack.adapters.testing import NoopCostMeter +from tests.workers.e3_test_doubles import _claim +from tests.workers.e3_test_doubles import _handler +from tests.workers.e3_test_doubles import _payload +from tests.workers.e3_test_doubles import RecordingFacts +from tests.workers.e3_test_doubles import RecordingResolver + + +def _run(*, payload: dict[str, object], resolver: RecordingResolver) -> RecordingFacts: + """Normalize one canned observation through the real E3 handler.""" + facts = RecordingFacts() + handler = _handler( + provider=FakeModelProvider(generate_payload=_payload(payload)), + resolver=resolver, + facts=facts, + ) + handler._normalize_claim( + deployment_id=uuid4(), + claim=_claim(), + version_ids=(uuid4(),), + meter=NoopCostMeter(), + ) + return facts + + +def test_equal_names_stay_distinct_until_resolution() -> None: + """Two 'The Open' references can resolve to different entities.""" + payload = { + "relations": [], + "observations": [ + { + "subject": {"name": "Joanna"}, + "statement": "Joanna said The Open then The Open", + "context_refs": [{"name": "The Open"}, {"name": "The Open"}], + } + ], + } + facts = _run(payload=payload, resolver=RecordingResolver()) + bindings = facts.applications.staged[0]["context_bindings"] + assert [ordinal for ordinal, _entity, _decision in bindings] == [0, 1] + assert bindings[0][1] != bindings[1][1] + + +def test_aliases_of_one_entity_keep_the_first_ordinal() -> None: + """Resolved identity is canonical; a second alias does not abort staging.""" + tournament = uuid4() + payload = { + "relations": [], + "observations": [ + { + "subject": {"name": "Joanna"}, + "statement": "Joanna said Nate won the Riverside Cup", + "context_refs": [ + {"name": "the cup"}, + {"name": "Riverside Cup"}, + {"name": "Nate"}, + ], + } + ], + } + facts = _run( + payload=payload, + resolver=RecordingResolver( + identities={"the cup": tournament, "Riverside Cup": tournament} + ), + ) + staged = facts.applications.staged[0] + bindings = staged["context_bindings"] + assert [ordinal for ordinal, entity, _decision in bindings] == [0, 2] + assert bindings[0][1] == tournament + assert bindings[1][1] != tournament + + +def test_canonical_subject_is_excluded_after_resolution() -> None: + """A context name that resolves to the subject is dropped after resolve.""" + joanna = uuid4() + payload = { + "relations": [], + "observations": [ + { + "subject": {"name": "Joanna Smith"}, + "statement": "Joanna Smith said Joanna won", + "context_refs": [{"name": "Joanna"}], + } + ], + } + facts = _run( + payload=payload, + resolver=RecordingResolver( + identities={"Joanna Smith": joanna, "Joanna": joanna} + ), + ) + assert facts.applications.staged[0]["context_bindings"] == () + assert facts.applications.staged[0]["subject_entity_id"] == joanna + + +def test_overflow_still_stages_the_assertion() -> None: + """Auxiliary extras are truncated; the assertion is still published.""" + payload = { + "relations": [], + "observations": [ + { + "subject": {"name": "Joanna"}, + "statement": "Joanna listed extra referents", + "context_refs": [{"name": f"Entity {index}"} for index in range(6)], + } + ], + } + facts = _run(payload=payload, resolver=RecordingResolver()) + frozen, accepted = facts.applications.published + assert accepted == (("observation", 0),) + assert len(frozen.observations[0].context_refs) == 6 + bindings = facts.applications.staged[0]["context_bindings"] + assert [ordinal for ordinal, _entity, _decision in bindings] == [0, 1, 2, 3] diff --git a/website/src/app/docs/ingestion/pipeline/page.mdx b/website/src/app/docs/ingestion/pipeline/page.mdx index 16f2a12cd..df3941f41 100644 --- a/website/src/app/docs/ingestion/pipeline/page.mdx +++ b/website/src/app/docs/ingestion/pipeline/page.mdx @@ -165,6 +165,13 @@ model output has the correct kind or date. ## E3 — Facts +Normalized assertions may name a few extra source-backed context entities +(a tournament, company, or person the claim refers to besides the subject). +Those bindings live on the assertion application. Candidate nomination still +starts with the same-subject baseline and may add a small number of facts that +share that context. Shared context never proves two assertions are the same +fact, and an empty context search does not authorize a new fact. + ### Entity resolution **Job:** map surface forms to **canonical entity ids** (write path). From c9f7b2f71e853f75e4d9fa54a6a3a3074726467e Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 13:07:29 +0200 Subject: [PATCH 02/14] fix(processing): keep D122/D123 identity and catalog contracts Preserve distinct cards that share a passage, measure Claimify bounds on the rendered block, require merged status on identity redirects, and pin the observed catalog constraint counts. Record the implementation eval. --- .../document_reference_context_design.md | 7 +- ...123_document_reference_context_20260914.md | 105 ++++++++++++++++++ .../core/selection_references.py | 45 +++++--- .../spine/fact_application_inputs.py | 5 +- src/rememberstack/workers/e3.py | 5 +- src/tests/fact_application_support.py | 3 +- .../spine/test_d123_context_nomination.py | 6 +- src/tests/workers/e3_test_doubles.py | 4 +- .../workers/test_e3_context_references.py | 4 +- 9 files changed, 153 insertions(+), 31 deletions(-) create mode 100644 plan/implementation_evals/d122_d123_document_reference_context_20260914.md diff --git a/plan/designs/document_reference_context_design.md b/plan/designs/document_reference_context_design.md index 96d37bf0b..947a92153 100644 --- a/plan/designs/document_reference_context_design.md +++ b/plan/designs/document_reference_context_design.md @@ -33,8 +33,11 @@ Generated summaries and section orientation cannot justify a reference. Only definitions with at least one target-chunk body passage are published by that Selection unit; its allowed neighbor evidence may clarify them. This avoids every neighbor publishing duplicate introductions. Do not merge cards by equal -name/date/participants. A particular unnamed tournament is eligible when source -context identifies it; a bare unqualified “tournament” is not an identity proof. +name/date/participants, and do not treat the same supporting passage as identity: +one paragraph can introduce both a person and a tournament. Preserve distinct +emitted cards and cap them as whole cards. A particular unnamed tournament is +eligible when source context identifies it; a bare unqualified “tournament” is +not an identity proof. Ambiguous references may remain unresolved. The card shown to Claimify includes its descriptive label and exact supporting diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md new file mode 100644 index 000000000..a5f66b3d1 --- /dev/null +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -0,0 +1,105 @@ +# D122/D123 implementation checkpoint — 2026-09-14 + +Implementation PR: [#403](https://github.com/writeitai/remember-stack/pull/403). +Wip checkpoint `a01217c07b097b8887cf4c9465d78065d2f9bacd`. The exact review +SHA is the GitHub PR head after the contract-fix follow-up. +Binding designs: [D122](../designs/document_reference_context_design.md), +[D123](../designs/contextual_fact_nomination_design.md). +Parent owns final integration, review, merge, and release. This branch must +not be self-merged. + +## What this head implements + +D123's independent path is implemented on this head: + +- The existing normalizer may emit up to four extra `EntityRef` context + references per assertion. Overflow stays on the frozen response and does not + reject the assertion or prove novelty. +- Original emitted ordinals are kept. Equal names stay distinct until ordinary + entity resolution assigns ids. Aliases that resolve to one entity keep the + first ordinal; staging does not abort the assertion. +- Canonical subject and object are excluded after resolution, not by casefolded + names. +- Bindings are written in the same transaction as the application and version + staging rows. An application with zero junction rows is a complete empty set. + There is no `context_complete` flag and no legacy conversion. +- Staging validates a live resolver decision for this claim and entity. +- Nomination keeps the existing same-subject baseline of 20 and may add up to + eight additional facts whose supporting applications share incoming context. + Empty context is not a new-fact authorization. Extra facts cannot displace a + baseline target. +- Snapshot fingerprints include junction rows, reverse-closure membership, and + supporting applications that affect extra nomination even when they sit + outside the bounded assertion payload. Empty UUID arrays are typed + `uuid[]`, not sentinel values. +- Hard-forget deletes `selection_results` and cascaded context bindings. + +D122 helpers exist for later E2 integration and are tested without a live +Selection worker: + +- Engine-supplied passage labels, not quote search. A missing or forged label + rejects the whole card. +- Distinct emitted cards are preserved. One passage may introduce two + referents. Cards are capped whole. +- Claimify render labels are request-unique (`R1`, `R2`, …). Passage support + keeps the supplied catalog labels. The 4096-character bound measures the + actual rendered block. +- Claimify reuse hashing includes empty preceding Selection producers. + +## What this head does not implement + +E2 Selection freeze, the representation barrier, Claimify scheduling, and +occurrence remapping are intentionally absent. They depend on completed +multi-span extraction ([#400](https://github.com/writeitai/remember-stack/pull/400)) +and then D120/D121. This branch does not invent a parallel multi-span +implementation. + +`PassageSupport` / `GroundedPassage` are pre-integration stand-ins. When D119 +lands, replace them with its catalog types and mapping helpers, keep +request-unique card labels, and keep source labels usable by Claimify +grounding. + +The migration still follows `p9_30_0051`. Rebase onto the D119 revision and +keep populated-store refusal before final migration validation. + +## Why there is no Claimify receipt table + +D122 requires one source-owned Selection-result store. That is +`selection_results`: the frozen Selection response, cards, generation, and +stable input hash. Claimify's extra reuse basis is the ordered Selection-input +hashes of the previous eight source chunks plus the reference-policy +generation. Existing chunk completion and extraction reuse already persist a +content/input hash per occurrence. When E2 is wired, that existing receipt can +carry `claimify_input_hash`; a second Claimify table would duplicate the +per-chunk completion/reuse contract. If integration proves the existing row +cannot hold that key, document the extra store then. Do not add it +speculatively. + +## Tests run on this head + +Dedicated database only: +`REMEMBERSTACK_DATABASE_URL=postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55442/ugm_d122_test`. + +- Unit: `test_selection_references`, `test_context_references`, + `test_e3_context_references`, `test_e3_bare_head_noun`, + `test_e3_claim_normalize_fanout`, `test_locomo_protocol` — 85 passed. +- PostgreSQL: `test_d123_context_nomination` (8), writer acceptance, and + migration graph / populated-store refusal / fresh lifecycle catalog + contract — 37 passed after catalog-count and merge-status corrections. +- Pyright on changed library files: 0 errors. +- Ruff check on changed files: passed. + +No paid LoCoMo run, no remote benchmark access, no provider-default change. +Rendered-card character accounting is proven with the actual formatted block in +unit tests, not billed model tokens. Extra-nomination candidate counts are +proven with the writer fixture (baseline 20 preserved, union ≤ 28), not as a +semantic-quality claim. + +## Remaining risks + +- E2 worker-order, barrier restart, 500-version claim reuse, and forget during + Selection/Claimify are untested because those workers are not on this branch. +- Context resolution cost is not measured against a live resolver model tier. +- Constraint counts and table inventory must be re-checked after the D119 + migration is inserted. +- Parent review of #403 is still required before merge. diff --git a/src/rememberstack/core/selection_references.py b/src/rememberstack/core/selection_references.py index 524dcb7f8..be1e2af4f 100644 --- a/src/rememberstack/core/selection_references.py +++ b/src/rememberstack/core/selection_references.py @@ -33,7 +33,11 @@ @dataclass(frozen=True) class PassageSupport: - """One engine-supplied source passage the model may cite (D119 descriptor).""" + """Pre-integration stand-in for D119's engine-supplied source passage. + + Selection cites these labels; it does not search quote strings. Replace + this type with the shared D119 catalog descriptor when that PR lands. + """ label: str char_start: int @@ -263,7 +267,7 @@ def _unique_region( *, char_start: int, char_end: int, windows: Mapping[PassageRegion, tuple[int, int]] ) -> PassageRegion | None: """Region of the unique window that fully contains the range.""" - matches = [ + matches: list[PassageRegion] = [ region for region, (start, end) in windows.items() if start <= char_start and char_end <= end @@ -348,21 +352,34 @@ def card_payload(*, card: GroundedCard) -> dict[str, object]: def card_from_payload(*, payload: dict[str, object]) -> GroundedCard: """Rehydrate one stored card.""" - passages = tuple( - GroundedPassage( - label=str(item["label"]), - char_start=int(item["char_start"]), - char_end=int(item["char_end"]), - region=item["region"], # type: ignore[arg-type] - text=str(item["text"]), + raw_passages = payload["passages"] + if not isinstance(raw_passages, list): + raise ValueError("card payload passages must be a list") + raw_aliases = payload.get("aliases", ()) + if not isinstance(raw_aliases, (list, tuple)): + raise ValueError("card payload aliases must be a sequence") + grounded: list[GroundedPassage] = [] + for item in raw_passages: + if not isinstance(item, dict): + raise ValueError("card payload passage must be an object") + region = item["region"] + if region not in ("target", "previous", "next"): + raise ValueError("card payload passage region is not a catalog region") + grounded.append( + GroundedPassage( + label=str(item["label"]), + char_start=int(str(item["char_start"])), + char_end=int(str(item["char_end"])), + region=region, + text=str(item["text"]), + ) ) - for item in payload["passages"] # type: ignore[union-attr] - ) + passages = tuple(grounded) return GroundedCard( name=str(payload["name"]), - aliases=tuple(str(alias) for alias in payload.get("aliases", ())), + aliases=tuple(str(alias) for alias in raw_aliases), passages=passages, - ordinal=int(payload["ordinal"]), + ordinal=int(str(payload["ordinal"])), owner_chunk_id=UUID(str(payload["owner_chunk_id"])), - owner_ordinal=int(payload["owner_ordinal"]), + owner_ordinal=int(str(payload["owner_ordinal"])), ) diff --git a/src/rememberstack/spine/fact_application_inputs.py b/src/rememberstack/spine/fact_application_inputs.py index 0814c2b33..9c4bd1ef2 100644 --- a/src/rememberstack/spine/fact_application_inputs.py +++ b/src/rememberstack/spine/fact_application_inputs.py @@ -178,10 +178,7 @@ def _nominate_fact_ids() -> list[Any]: extra = _rows( connection=connection, sql=extra_sql, - params={ - **params, - "baseline_ids": [row["fact_id"] for row in baseline], - }, + params={**params, "baseline_ids": [row["fact_id"] for row in baseline]}, ) by_id = {row["fact_id"]: row for row in baseline} for row in extra: diff --git a/src/rememberstack/workers/e3.py b/src/rememberstack/workers/e3.py index b75622ae7..39676aad5 100644 --- a/src/rememberstack/workers/e3.py +++ b/src/rememberstack/workers/e3.py @@ -394,10 +394,7 @@ def _normalize_claim( raise NonRetryableHandlerError( "context resolution produced no validating decision" ) - if ( - resolved.entity_id in exclude - or resolved.entity_id in seen_entities - ): + if resolved.entity_id in exclude or resolved.entity_id in seen_entities: continue seen_entities.add(resolved.entity_id) context_bindings.append( diff --git a/src/tests/fact_application_support.py b/src/tests/fact_application_support.py index f2b97f3eb..6f1e738db 100644 --- a/src/tests/fact_application_support.py +++ b/src/tests/fact_application_support.py @@ -188,11 +188,12 @@ def record_resolution( connection.execute( text("""INSERT INTO mentions(mention_id,deployment_id,surface_form, normalized_lemma,canonical_name_form,claim_id,doc_id) - VALUES(:mention,:dep,:name,lower(:name),:name,:claim,:doc)"""), + VALUES(:mention,:dep,:name,:lemma,:name,:claim,:doc)"""), { "mention": mention_id, "dep": self.dep, "name": name, + "lemma": name.casefold(), "claim": claim_id, "doc": doc_id, }, diff --git a/src/tests/spine/test_d123_context_nomination.py b/src/tests/spine/test_d123_context_nomination.py index a2177c17c..46d0b535f 100644 --- a/src/tests/spine/test_d123_context_nomination.py +++ b/src/tests/spine/test_d123_context_nomination.py @@ -204,7 +204,7 @@ def test_canonical_membership_changes_the_context_fingerprint( with database_engine.begin() as connection: connection.execute( text( - "UPDATE entities SET merged_into=:survivor WHERE entity_id=:absorbed" + "UPDATE entities SET status='merged', merged_into=:survivor WHERE entity_id=:absorbed" ), {"survivor": tournament, "absorbed": alias}, ) @@ -221,9 +221,7 @@ def test_context_extra_does_not_displace_baseline_targets( case = WriterCase(engine=database_engine) tournament = _tournament(engine=database_engine, case=case) _, win_app = case.stage( - day=10, - statement="Nate took first place in May", - context_entities=(tournament,), + day=10, statement="Nate took first place in May", context_entities=(tournament,) ) case.decide( decision={ diff --git a/src/tests/workers/e3_test_doubles.py b/src/tests/workers/e3_test_doubles.py index 3e7e7ed75..55185b382 100644 --- a/src/tests/workers/e3_test_doubles.py +++ b/src/tests/workers/e3_test_doubles.py @@ -60,7 +60,9 @@ def resolve( self.calls.append(reference) entity_id = self.identities.get(reference.name, uuid4()) resolved = ResolvedEntity( - entity_id=entity_id, created=True, decision_id=uuid4() # type: ignore[arg-type] + entity_id=entity_id, + created=True, + decision_id=uuid4(), # type: ignore[arg-type] ) self.resolved.append(resolved) return resolved diff --git a/src/tests/workers/test_e3_context_references.py b/src/tests/workers/test_e3_context_references.py index e62081ddb..8e28fad95 100644 --- a/src/tests/workers/test_e3_context_references.py +++ b/src/tests/workers/test_e3_context_references.py @@ -112,7 +112,9 @@ def test_overflow_still_stages_the_assertion() -> None: ], } facts = _run(payload=payload, resolver=RecordingResolver()) - frozen, accepted = facts.applications.published + published = facts.applications.published + assert published is not None + frozen, accepted = published assert accepted == (("observation", 0),) assert len(frozen.observations[0].context_refs) == 6 bindings = facts.applications.staged[0]["context_bindings"] From 4739d58ee05ad764ee0a683c0b3ef6195c9daf22 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 13:14:18 +0200 Subject: [PATCH 03/14] docs: record D122/D123 Antigravity review of f60fb511 The review found no blockers or material findings. Optional nits are left unfixed so the reviewed code SHA remains the contract head. --- .../d122_d123_document_reference_context_20260914.md | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md index a5f66b3d1..2aca8169d 100644 --- a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -1,8 +1,13 @@ # D122/D123 implementation checkpoint — 2026-09-14 Implementation PR: [#403](https://github.com/writeitai/remember-stack/pull/403). -Wip checkpoint `a01217c07b097b8887cf4c9465d78065d2f9bacd`. The exact review -SHA is the GitHub PR head after the contract-fix follow-up. +Wip checkpoint `a01217c07b097b8887cf4c9465d78065d2f9bacd`. +Antigravity read-only review SHA: `f60fb511623fdafbef78582dcbf08db7d7863c6a` +(`agy --dangerously-skip-permissions --print-timeout 180m0s`). +Verdict: **acceptable** for parent integration review of the D123-independent +slice. Blockers 0, material findings 0. Two optional nits (hardcoded `> 4` +vs `MAX_CONTEXT_REFS`; alias `strip` compared to unstripped card name) were +left unfixed so the reviewed code SHA stays the contract head. Binding designs: [D122](../designs/document_reference_context_design.md), [D123](../designs/contextual_fact_nomination_design.md). Parent owns final integration, review, merge, and release. This branch must From 1a6802b44aedb5d825073fa3f8d5b87f5efa0729 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 14:16:57 +0200 Subject: [PATCH 04/14] fix(core): resolve D122 cards through D119 SourcePassage Replace the temporary PassageSupport stand-in with the shared catalog descriptor and PassageRegion. Card publication still requires a target body passage, not keep-origin eligibility. --- .../core/selection_references.py | 31 +-- src/tests/core/test_selection_references.py | 198 ++++++++++++++++-- 2 files changed, 189 insertions(+), 40 deletions(-) diff --git a/src/rememberstack/core/selection_references.py b/src/rememberstack/core/selection_references.py index be1e2af4f..6fa009501 100644 --- a/src/rememberstack/core/selection_references.py +++ b/src/rememberstack/core/selection_references.py @@ -15,9 +15,10 @@ import hashlib import re from typing import Final -from typing import Literal from uuid import UUID +from rememberstack.core.source_passages import PassageRegion +from rememberstack.core.source_passages import SourcePassage from rememberstack.model.chunks import ChunkForEmbedding from rememberstack.model.claims import SourceReferenceCard @@ -28,21 +29,6 @@ PRECEDING_CHUNK_LIMIT: Final = 8 _TOKEN_RE: Final = re.compile(r"\w+") -PassageRegion = Literal["target", "previous", "next"] - - -@dataclass(frozen=True) -class PassageSupport: - """Pre-integration stand-in for D119's engine-supplied source passage. - - Selection cites these labels; it does not search quote strings. Replace - this type with the shared D119 catalog descriptor when that PR lands. - """ - - label: str - char_start: int - char_end: int - region: PassageRegion @dataclass(frozen=True) @@ -102,8 +88,8 @@ def token_set(*, text: str) -> frozenset[str]: def catalog_by_label( - *, passages: tuple[PassageSupport, ...] -) -> dict[str, PassageSupport]: + *, passages: tuple[SourcePassage, ...] +) -> dict[str, SourcePassage]: """Label map; labels are unique by construction in the engine catalog.""" return {passage.label: passage for passage in passages} @@ -111,7 +97,7 @@ def catalog_by_label( def resolve_card( *, card: SourceReferenceCard, - catalog: Mapping[str, PassageSupport], + catalog: Mapping[str, SourcePassage], document_md: str, owner_chunk: ChunkForEmbedding, ordinal: int, @@ -166,14 +152,15 @@ def resolve_card( gate="no_target_passage", detail="a published card needs at least one target-chunk body passage", ) + name = card.name.strip() aliases = tuple( alias.strip() for alias in card.aliases - if alias.strip() and alias.strip() != card.name + if alias.strip() and alias.strip() != name ) return ( GroundedCard( - name=card.name.strip(), + name=name, aliases=aliases, passages=tuple(resolved), ordinal=ordinal, @@ -187,7 +174,7 @@ def resolve_card( def publish_selection_cards( *, cards: tuple[SourceReferenceCard, ...], - catalog: Mapping[str, PassageSupport], + catalog: Mapping[str, SourcePassage], document_md: str, owner_chunk: ChunkForEmbedding, ) -> tuple[tuple[GroundedCard, ...], bool, tuple[CardDiagnostic, ...]]: diff --git a/src/tests/core/test_selection_references.py b/src/tests/core/test_selection_references.py index 8dba1397e..96aab1463 100644 --- a/src/tests/core/test_selection_references.py +++ b/src/tests/core/test_selection_references.py @@ -1,16 +1,19 @@ """Provider-free D122 catalog resolution, distinct cards, and complete support.""" +from collections.abc import Mapping from uuid import uuid4 from rememberstack.core.selection_references import catalog_by_label from rememberstack.core.selection_references import claimify_input_hash from rememberstack.core.selection_references import GroundedCard from rememberstack.core.selection_references import GroundedPassage -from rememberstack.core.selection_references import PassageSupport +from rememberstack.core.selection_references import MAX_CARDS_PER_CLAIMIFY from rememberstack.core.selection_references import publish_selection_cards from rememberstack.core.selection_references import rank_and_fit_cards from rememberstack.core.selection_references import remap_card from rememberstack.core.selection_references import render_cards_for_claimify +from rememberstack.core.source_passages import PassageRegion +from rememberstack.core.source_passages import SourcePassage from rememberstack.model.chunks import ChunkForEmbedding from rememberstack.model.claims import SourceReferenceCard @@ -31,7 +34,25 @@ def _chunk(*, ordinal: int, start: int, end: int, chunk_id=None) -> ChunkForEmbe ) -def _catalog(*passages: PassageSupport) -> dict[str, PassageSupport]: +def _passage( + *, + label: str, + char_start: int, + char_end: int, + region: PassageRegion, + origin_eligible: bool, +) -> SourcePassage: + """D119 catalog descriptor; origin_eligible is independent of card publication.""" + return SourcePassage( + label=label, + char_start=char_start, + char_end=char_end, + region=region, + origin_eligible=origin_eligible, + ) + + +def _catalog(*passages: SourcePassage) -> dict[str, SourcePassage]: """Engine-supplied label map.""" return catalog_by_label(passages=passages) @@ -41,7 +62,13 @@ def test_unknown_label_rejects_the_whole_card() -> None: document = "Nate won the Riverside Cup today." owner = _chunk(ordinal=0, start=0, end=len(document)) catalog = _catalog( - PassageSupport(label="S1", char_start=13, char_end=26, region="target") + _passage( + label="S1", + char_start=13, + char_end=26, + region="target", + origin_eligible=True, + ) ) published, truncated, diagnostics = publish_selection_cards( cards=( @@ -61,7 +88,13 @@ def test_neighbour_only_support_is_not_published() -> None: document = "Earlier the cup was named. Nate won that tournament today." owner = _chunk(ordinal=1, start=26, end=len(document)) catalog = _catalog( - PassageSupport(label="S1", char_start=8, char_end=25, region="previous") + _passage( + label="S1", + char_start=8, + char_end=25, + region="previous", + origin_eligible=False, + ) ) published, _, diagnostics = publish_selection_cards( cards=(SourceReferenceCard(name="the cup", source_refs=("S1",)),), @@ -73,13 +106,49 @@ def test_neighbour_only_support_is_not_published() -> None: assert diagnostics[0].gate == "no_target_passage" +def test_target_support_publishes_without_keep_eligibility() -> None: + """Cards need a target-chunk body passage, not a Selection-kept origin.""" + document = "Nate won the Riverside Cup today." + owner = _chunk(ordinal=0, start=0, end=len(document)) + catalog = _catalog( + _passage( + label="S1", + char_start=13, + char_end=26, + region="target", + origin_eligible=False, + ) + ) + published, truncated, diagnostics = publish_selection_cards( + cards=(SourceReferenceCard(name="Riverside Cup", source_refs=("S1",)),), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert truncated is False + assert diagnostics == () + assert published[0].name == "Riverside Cup" + assert published[0].passages[0].char_start == 13 + assert published[0].passages[0].char_end == 26 + assert published[0].passages[0].text == "Riverside Cup" + assert published[0].passages[0].region == "target" + + def test_same_name_distinct_ranges_are_both_published() -> None: """Equal names are not identity; two tournaments stay two cards.""" document = "The Open on Monday. The Open on Friday." owner = _chunk(ordinal=0, start=0, end=len(document)) catalog = _catalog( - PassageSupport(label="S1", char_start=0, char_end=18, region="target"), - PassageSupport(label="S2", char_start=20, char_end=39, region="target"), + _passage( + label="S1", char_start=0, char_end=18, region="target", origin_eligible=True + ), + _passage( + label="S2", + char_start=20, + char_end=39, + region="target", + origin_eligible=True, + ), ) published, truncated, diagnostics = publish_selection_cards( cards=( @@ -94,6 +163,10 @@ def test_same_name_distinct_ranges_are_both_published() -> None: assert diagnostics == () assert [card.ordinal for card in published] == [0, 1] assert [card.passages[0].char_start for card in published] == [0, 20] + assert [card.passages[0].text for card in published] == [ + document[0:18], + document[20:39], + ] def test_two_referents_may_share_one_passage() -> None: @@ -101,7 +174,13 @@ def test_two_referents_may_share_one_passage() -> None: document = "Nate won Tournament A today." owner = _chunk(ordinal=0, start=0, end=len(document)) catalog = _catalog( - PassageSupport(label="S1", char_start=0, char_end=len(document), region="target") + _passage( + label="S1", + char_start=0, + char_end=len(document), + region="target", + origin_eligible=True, + ) ) published, truncated, diagnostics = publish_selection_cards( cards=( @@ -125,15 +204,16 @@ def test_cap_keeps_first_four_distinct_cards() -> None: document = " ".join(names) owner = _chunk(ordinal=0, start=0, end=len(document)) cursor = 0 - passages: list[PassageSupport] = [] + passages: list[SourcePassage] = [] for index, name in enumerate(names, start=1): start = document.find(name, cursor) passages.append( - PassageSupport( + _passage( label=f"S{index}", char_start=start, char_end=start + len(name), region="target", + origin_eligible=False, ) ) cursor = start + len(name) @@ -294,7 +374,9 @@ def test_remap_rejects_incomplete_or_rescued_mapping() -> None: owner_chunk_id=uuid4(), owner_ordinal=1, ) - windows = {"target": (second, second + length)} + windows: Mapping[PassageRegion, tuple[int, int]] = { + "target": (second, second + length) + } assert ( remap_card( card=card, remapped_spans=None, current_md=document, current_windows=windows @@ -370,18 +452,98 @@ def test_character_cap_counts_the_rendered_block() -> None: rendered = render_cards_for_claimify(cards=(card,)) assert len(rendered) > len("NateNate") chosen, truncated = rank_and_fit_cards( - cards=(card,), - target_text="Nate", - target_ordinal=1, - max_chars=len(rendered) - 1, + cards=(card,), target_text="Nate", target_ordinal=1, max_chars=len(rendered) - 1 ) assert truncated is True assert chosen == () kept, kept_truncated = rank_and_fit_cards( - cards=(card,), - target_text="Nate", - target_ordinal=1, - max_chars=len(rendered), + cards=(card,), target_text="Nate", target_ordinal=1, max_chars=len(rendered) ) assert kept_truncated is False assert kept == (card,) + + +def test_resolution_keeps_the_cited_range_not_the_first_match() -> None: + """Catalog offsets are the source of truth; the same words may appear twice.""" + document = "Riverside Cup then Riverside Cup later" + second = document.rfind("Riverside Cup") + length = len("Riverside Cup") + owner = _chunk(ordinal=0, start=0, end=len(document)) + catalog = _catalog( + _passage( + label="S1", + char_start=second, + char_end=second + length, + region="target", + origin_eligible=False, + ) + ) + published, truncated, diagnostics = publish_selection_cards( + cards=(SourceReferenceCard(name="Riverside Cup", source_refs=("S1",)),), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert truncated is False + assert diagnostics == () + assert published[0].passages[0].char_start == second + assert published[0].passages[0].text == "Riverside Cup" + assert document.find("Riverside Cup") != second + + +def test_claimify_cap_keeps_eight_whole_cards() -> None: + """A ninth eligible card is a recorded cap loss, not a trim.""" + cards = tuple( + GroundedCard( + name=f"Name{index}", + aliases=(), + passages=( + GroundedPassage( + label=f"S{index}", + char_start=0, + char_end=1, + region="target", + text="x", + ), + ), + ordinal=index, + owner_chunk_id=uuid4(), + owner_ordinal=0, + ) + for index in range(MAX_CARDS_PER_CLAIMIFY + 1) + ) + chosen, truncated = rank_and_fit_cards( + cards=cards, target_text="x", target_ordinal=1 + ) + assert truncated is True + assert len(chosen) == MAX_CARDS_PER_CLAIMIFY + assert [card.ordinal for card in chosen] == list(range(MAX_CARDS_PER_CLAIMIFY)) + + +def test_alias_whitespace_is_stripped_and_name_duplicates_dropped() -> None: + """Surrounding whitespace is not a distinct alias of the published name.""" + document = "Nate, also the kid, won today." + owner = _chunk(ordinal=0, start=0, end=len(document)) + catalog = _catalog( + _passage( + label="S1", + char_start=0, + char_end=len(document), + region="target", + origin_eligible=False, + ) + ) + published, truncated, diagnostics = publish_selection_cards( + cards=( + SourceReferenceCard( + name=" Nate ", aliases=(" Nate ", " the kid "), source_refs=("S1",) + ), + ), + catalog=catalog, + document_md=document, + owner_chunk=owner, + ) + assert truncated is False + assert diagnostics == () + assert published[0].name == "Nate" + assert published[0].aliases == ("the kid",) From 7f0b5996add7f0ee5e5afbc0278572d770eda536 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 14:36:16 +0200 Subject: [PATCH 05/14] feat(e2): freeze Selection and run Claimify on ground_claims EXTRACT_CLAIMS now publishes one frozen Selection result per chunk, including zero-candidate/zero-card outcomes and remapped same-input reuse. GROUND_CLAIMS requires the target freeze and every previous-eight producer, hashes Claimify inputs from those source bases, remaps occurrences through target-9..+1 windows, and completes no-keep chunks without a provider call. --- src/rememberstack/workers/e2.py | 629 ++++++++++++++---- .../workers/extraction_references.py | 256 +++++++ 2 files changed, 747 insertions(+), 138 deletions(-) create mode 100644 src/rememberstack/workers/extraction_references.py diff --git a/src/rememberstack/workers/e2.py b/src/rememberstack/workers/e2.py index eb87c8dbe..6e1fd39ce 100644 --- a/src/rememberstack/workers/e2.py +++ b/src/rememberstack/workers/e2.py @@ -1,15 +1,16 @@ -"""The E2 extractor (D31-D35): two-call Claimify over the context bundle. - -Per chunk: a Selection call judges every proposition (keep / keep-flagged / -drop — drops and flags go to the D33 ledger), then one fused call -decontextualizes, decomposes, and self-grounds the keeps. The deterministic -grounding gate (D32 layers 1-2) accepts a claim only if its verbatim source -span anchors inside the chunk and every content token in added text exists in -the union of the bundle's source-derived texts. A closed set of functional -scaffolding tokens is permitted; the model's source tag is advisory provenance, -not an acceptance boundary. Every kept span ends in accepted claim(s), -grounding_rejected row(s), or a claimify_omitted row so Claimify-stage losses -are never silent (#161). +"""The E2 extractor (D31-D35, D122): Selection then Claimify over the bundle. + +EXTRACT_CLAIMS runs Selection only: it judges propositions, publishes grounded +source-reference cards, and freezes the complete result. GROUND_CLAIMS runs +Claimify after every required Selection producer exists. The deterministic +grounding gate (D32 layers 1-2) accepts a claim only if its origin is a target +keep-overlapping passage and every content token in added text exists in the +union of the bundle's source-derived texts plus cited card passage text. A +closed set of functional scaffolding tokens is permitted; the model's source +tag is advisory provenance, not an acceptance boundary. Card names are +orientation only. Every kept span ends in accepted claim(s), grounding_rejected +row(s), or a claimify_omitted row so Claimify-stage losses are never silent +(#161). """ from dataclasses import dataclass @@ -30,6 +31,12 @@ from pydantic_settings import SettingsConfigDict from rememberstack.core import blocks_from_sidecar +from rememberstack.core.selection_references import CardDiagnostic +from rememberstack.core.selection_references import claimify_input_hash +from rememberstack.core.selection_references import GroundedCard +from rememberstack.core.selection_references import publish_selection_cards +from rememberstack.core.selection_references import rank_and_fit_cards +from rememberstack.core.selection_references import render_cards_for_claimify from rememberstack.core.source_passages import build_passage_catalog from rememberstack.core.source_passages import origin_span_from_record from rememberstack.core.source_passages import PassageCatalog @@ -38,7 +45,6 @@ from rememberstack.core.source_passages import render_passage_catalog from rememberstack.core.source_passages import resolve_source_refs from rememberstack.core.source_passages import same_section_neighbours -from rememberstack.core.source_passages import window_bounds from rememberstack.model import Block from rememberstack.model import CandidateClaim from rememberstack.model import ChunkForEmbedding @@ -78,10 +84,21 @@ from rememberstack.ports.object_store import ObjectStorePort from rememberstack.spine.chunk_catalog import ChunkCatalog from rememberstack.spine.claim_catalog import ClaimCatalog +from rememberstack.spine.selection_catalog import FrozenSelection from rememberstack.workers.base import ExtractChunkBarrier from rememberstack.workers.base import HandlerOutcome +from rememberstack.workers.base import SelectionChunkBarrier from rememberstack.workers.e1 import E2_EXTRACTOR_VERSION from rememberstack.workers.e3 import E3_NORMALIZER_VERSION +from rememberstack.workers.extraction_references import attach_card_passages +from rememberstack.workers.extraction_references import card_passage_texts +from rememberstack.workers.extraction_references import collect_eligible_cards +from rememberstack.workers.extraction_references import MissingSelectionError +from rememberstack.workers.extraction_references import preceding_producer_ids +from rememberstack.workers.extraction_references import reference_windows +from rememberstack.workers.extraction_references import remap_frozen_cards +from rememberstack.workers.extraction_references import render_selection_passages +from rememberstack.workers.extraction_references import require_frozen_producers from rememberstack.workers.section_orientation import render_section_orientation _logger = logging.getLogger(__name__) @@ -188,6 +205,15 @@ Choose exactly one outcome from: {outcomes}. Each drop_* outcome already names the reason; there is no separate reason field. +Also emit references for people, companies, works, or particular events the +TARGET CHUNK introduces. Cite only the supplied SOURCE PASSAGES labels; never +invent a label or character offset. Neighbour passages may clarify a target +introduction. Names are orientation, not evidence. Do not merge two referents +because they share a name. A particular unnamed event is eligible when the +shown source identifies it; a bare unqualified noun is not. + +{passages} + {bundle}""" _CLAIMIFY_PROMPT: Final = """You are the Claimify stage of a claim extractor. @@ -215,15 +241,18 @@ - source_refs: every supplied SOURCE PASSAGES label needed to support it. The first label is the origin: a TARGET passage marked origin-eligible that contains the kept proposition. This means it overlaps a Selection keep. - Further labels supply support from the target or permitted same-section - neighbours. Cite all required support, not just the origin. A larger passage - may also contain dropped statements; citing it does not authorize extracting - those statements. Never invent a label or character offset. + Further labels supply support from the target, permitted same-section + neighbours, or cited source-reference-card supporting passages. Cite all + required support, not just the origin. A larger passage may also contain + dropped statements; citing it does not authorize extracting those + statements. Never invent a label or character offset. - added_context: each substring added from outside the TARGET CHUNK. Text already in the target needs no entry. Each addition must occur verbatim in - the DOCUMENT HEADER, permitted PREVIOUS/NEXT CHUNK or typed LOCATION elements, - except resolved dates under the rules below. Mark its origin with - header|neighbour|prefix; the tag is advisory and does not establish support. + the DOCUMENT HEADER, permitted PREVIOUS/NEXT CHUNK, typed LOCATION elements, + or cited source-reference-card supporting passages, except resolved dates + under the rules below. Card names are orientation only and cannot ground an + addition. Mark its origin with header|neighbour|prefix; the tag is advisory + and does not establish support. - entailment_self_verdict: whether the source and permitted context actually support the whole claim, rather than merely containing the same words. - is_attributed: whether the claim records someone's statement or stance. @@ -330,6 +359,11 @@ {passages} +SOURCE REFERENCE CARDS (names are orientation only; never treat a generated +name as evidence. Cite the supporting SOURCE PASSAGES labels. A card cannot +resurrect a dropped proposition or replace the TARGET origin rule): +{cards} + KEPT PROPOSITIONS: {keeps} @@ -345,7 +379,7 @@ class E2Settings(BaseSettings): class ExtractClaimsHandler: - """The extract stage: every chunk of one representation through Claimify.""" + """Selection on EXTRACT_CLAIMS, Claimify on GROUND_CLAIMS, same handler.""" def __init__( self, @@ -366,12 +400,18 @@ def __init__( self._chunker_version = chunker_version def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: - """Extract claims: D84 chunk grain, or legacy version coordinator.""" + """Run Selection or Claimify at chunk grain, or fan out legacy extract.""" source = self._chunk_catalog.chunk_source( representation_id=_payload_uuid(work=work, field="representation_id") ) + if work.stage is PipelineStage.GROUND_CLAIMS: + if work.target_kind is not ProcessingTarget.CHUNK: + raise NonRetryableHandlerError( + f"ground_claims work {work.processing_id} is not chunk grain" + ) + return self._handle_claimify(work=work, source=source, meter=meter) if work.target_kind is ProcessingTarget.CHUNK: - return self._handle_chunk(work=work, source=source, meter=meter) + return self._handle_selection(work=work, source=source, meter=meter) # Legacy document/version extract row: fan out only (ids, not full rows). chunk_ids = self._chunk_catalog.list_chunk_ids( representation_id=source.representation_id, @@ -401,67 +441,124 @@ def handle(self, *, work: ClaimedWork, meter: CostMeterPort) -> HandlerOutcome: ) ) - def _handle_chunk( + def _handle_selection( self, *, work: ClaimedWork, source: ChunkSource, meter: CostMeterPort ) -> HandlerOutcome: - """Run Claimify for one chunk and schedule the atomic barrier on complete.""" + """Freeze one chunk's Selection result; Claimify is scheduled by the barrier.""" chunk_id = work.target_id chunks = self._chunk_catalog.chunks_for_extract( representation_id=source.representation_id, chunker_version=self._chunker_version, chunk_id=chunk_id, ) - index = next( - (i for i, chunk in enumerate(chunks) if chunk.chunk_id == chunk_id), None + index, chunk = _require_chunk( + chunks=chunks, chunk_id=chunk_id, representation_id=source.representation_id ) - if index is None: - raise NonRetryableHandlerError( - f"chunk {chunk_id} is not part of representation" - f" {source.representation_id}" - ) - chunk = chunks[index] - if not self._catalog.chunk_already_extracted( + frozen = self._catalog.selections.load( chunk_id=chunk.chunk_id, extractor_version=E2_EXTRACTOR_VERSION - ): - occurrence_context = self._load_occurrence_context(source=source) - document_md = self._artifact_store.read_bytes( - key=ObjectKey(source.markdown_uri) - ).decode("utf-8") - if not self._reuse_prior_extraction( + ) + if frozen is None: + document_md = self._read_markdown(source=source) + if not self._reuse_prior_selection( source=source, chunk=chunk, chunks=chunks, index=index, document_md=document_md, - occurrence_context=occurrence_context, ): - self._extract_chunk( + self._select_chunk( source=source, chunks=chunks, index=index, document_md=document_md, - blocks=_load_blocks( - artifact_store=self._artifact_store, - source=source, - document_md=document_md, - ), meter=meter, - occurrence_context=occurrence_context, ) - return HandlerOutcome( - extract_chunk_barrier=ExtractChunkBarrier( - deployment_id=work.deployment_id, - version_id=source.version_id, + return _selection_barrier( + work=work, source=source, chunker_version=self._chunker_version + ) + + def _handle_claimify( + self, *, work: ClaimedWork, source: ChunkSource, meter: CostMeterPort + ) -> HandlerOutcome: + """Ground keeps against frozen Selection producers, then extract-complete.""" + chunk_id = work.target_id + if not self._catalog.chunk_already_extracted( + chunk_id=chunk_id, extractor_version=E2_EXTRACTOR_VERSION + ): + extract_chunks = self._chunk_catalog.chunks_for_extract( representation_id=source.representation_id, chunker_version=self._chunker_version, - extractor_version=E2_EXTRACTOR_VERSION, - content_hash=work.content_hash, - lane=work.lane, - normalize_component_version=E3_NORMALIZER_VERSION, + chunk_id=chunk_id, + ) + index, chunk = _require_chunk( + chunks=extract_chunks, + chunk_id=chunk_id, + representation_id=source.representation_id, + ) + reference_chunks = self._chunk_catalog.chunks_for_references( + representation_id=source.representation_id, + chunker_version=self._chunker_version, + chunk_id=chunk_id, + ) + document_md = self._read_markdown(source=source) + target_frozen, preceding = self._required_selection_producers( + chunk=chunk, reference_chunks=reference_chunks + ) + input_hash = claimify_input_hash( + target_selection_input_hash=target_frozen.input_hash, + preceding_selection_input_hashes=tuple( + frozen.input_hash for frozen in preceding + ), ) + occurrence_context = self._load_occurrence_context(source=source) + if not self._reuse_prior_claimify( + source=source, + chunk=chunk, + reference_chunks=reference_chunks, + document_md=document_md, + occurrence_context=occurrence_context, + claimify_hash=input_hash, + ): + self._claimify_chunk( + source=source, + chunks=extract_chunks, + index=index, + document_md=document_md, + meter=meter, + occurrence_context=occurrence_context, + target_frozen=target_frozen, + preceding=preceding, + claimify_hash=input_hash, + ) + return _extract_barrier( + work=work, source=source, chunker_version=self._chunker_version ) - def _reuse_prior_extraction( + def _required_selection_producers( + self, + *, + chunk: ChunkForEmbedding, + reference_chunks: tuple[ChunkForEmbedding, ...], + ) -> tuple[FrozenSelection, tuple[FrozenSelection, ...]]: + """Load the target freeze and every previous-eight producer, including empties.""" + target_frozen = self._catalog.selections.load( + chunk_id=chunk.chunk_id, extractor_version=E2_EXTRACTOR_VERSION + ) + if target_frozen is None: + raise MissingSelectionError( + f"required Selection result is missing for chunk {chunk.chunk_id}" + ) + producer_ids = preceding_producer_ids(chunks=reference_chunks, target=chunk) + if not producer_ids: + return target_frozen, () + loaded = self._catalog.selections.preceding( + chunk_ids=producer_ids, extractor_version=E2_EXTRACTOR_VERSION + ) + return target_frozen, require_frozen_producers( + loaded=loaded, required_ids=producer_ids + ) + + def _reuse_prior_selection( self, *, source: ChunkSource, @@ -469,85 +566,120 @@ def _reuse_prior_extraction( chunks: tuple[ChunkForEmbedding, ...], index: int, document_md: str, - occurrence_context: RepresentationOccurrenceContext | None = None, ) -> bool: - """The D56 chunk-grain reuse rung: re-attach instead of re-extract. - - An unchanged ``extraction_input_hash`` within the lineage means some - already-extracted chunk read the exact same stable inputs — its - claims are re-attached to this version's chunk row (occurrence - links, F4) and no model is called. Every evidence span is remapped - through the matching content-identical window. If any span cannot - be remapped uniquely, this returns False and ordinary extraction - runs. A prior extraction that found nothing claim-worthy carries - its terminal marker forward the same way. Returns False when the - lineage holds no extracted match. - """ - prior = self._catalog.prior_extracted_chunk( + """Replay a same-input earlier Selection, remapping every published card.""" + prior = self._catalog.selections.prior( deployment_id=source.deployment_id, doc_id=source.doc_id, version_id=chunk.version_id, - extraction_input_hash=chunk.extraction_input_hash, + input_hash=chunk.extraction_input_hash, + extractor_version=E2_EXTRACTOR_VERSION, ) if prior is None: return False - remapped = self._remap_reused_spans( - source=source, + remapped = self._remap_prior_selection_cards( chunk=chunk, chunks=chunks, index=index, document_md=document_md, - prior_chunk_id=prior, + prior=prior, ) if remapped is None: return False - occurrences = self._reused_occurrences( - remapped_spans=remapped, occurrence_context=occurrence_context - ) - attached = self._catalog.attach_reused_claims( + self._catalog.selections.freeze( deployment_id=source.deployment_id, + representation_id=source.representation_id, chunk_id=chunk.chunk_id, - prior_chunk_id=prior, - occurrences=occurrences, - evidence_spans=remapped, + extractor_version=E2_EXTRACTOR_VERSION, + input_hash=chunk.extraction_input_hash, + selection=prior.selection, + cards=remapped, + diagnostics=prior.diagnostics, + truncated=prior.truncated, + reused_from=prior.chunk_id, ) - if attached == 0: - # the prior chunk carries no claims. Zero claims no longer means - # no_info — the prior may hold claimify_omitted / - # grounding_rejected rows (#161) — so carry the prior transcript - # forward verbatim; fabricate the no_info marker only when the - # prior transcript is itself empty. Either way replay stays - # closed for this chunk. - copied = self._catalog.copy_reused_decisions( - chunk_id=chunk.chunk_id, prior_chunk_id=prior - ) - if copied == 0: - self._catalog.record_extraction( - claims=(), - decisions=(_empty_extraction_marker(source=source, chunk=chunk),), - ) return True - def _extract_chunk( + def _remap_prior_selection_cards( + self, + *, + chunk: ChunkForEmbedding, + chunks: tuple[ChunkForEmbedding, ...], + index: int, + document_md: str, + prior: FrozenSelection, + ) -> tuple[GroundedCard, ...] | None: + """Map prior card ranges through local D119 windows onto this occurrence.""" + prior_representation_id = self._chunk_catalog.representation_id_for_chunk( + chunk_id=prior.chunk_id + ) + if prior_representation_id is None: + return None + prior_source = self._chunk_catalog.chunk_source( + representation_id=prior_representation_id + ) + prior_chunks = self._chunk_catalog.chunks_for_extract( + representation_id=prior_representation_id, + chunker_version=self._chunker_version, + chunk_id=prior.chunk_id, + ) + prior_index = next( + ( + position + for position, item in enumerate(prior_chunks) + if item.chunk_id == prior.chunk_id + ), + None, + ) + if prior_index is None: + return None + prior_md = self._read_markdown(source=prior_source) + return remap_frozen_cards( + cards=prior.cards, + prior_chunks=prior_chunks, + prior_index=prior_index, + current_chunks=chunks, + current_index=index, + prior_md=prior_md, + current_md=document_md, + current_chunk=chunk, + ) + + def _select_chunk( self, *, source: ChunkSource, chunks: tuple[ChunkForEmbedding, ...], index: int, document_md: str, - blocks: tuple[Block, ...], meter: CostMeterPort, - occurrence_context: RepresentationOccurrenceContext | None = None, ) -> None: - """Run the two Claimify calls for one chunk and land the results.""" + """Call Selection once, resolve cards against engine labels, freeze the winner.""" chunk = chunks[index] + previous, following = same_section_neighbours(chunks=chunks, index=index) + blocks = _load_blocks( + artifact_store=self._artifact_store, source=source, document_md=document_md + ) + catalog = build_passage_catalog( + blocks=blocks, + target=chunk, + previous=previous, + following=following, + kept_ranges=(), + ) bundle = _bundle_text( source=source, chunks=chunks, index=index, document_md=document_md ) selection_call = self._model_provider.generate( request=ModelRequest( model=self._settings.extract_model, - prompt=_SELECTION_PROMPT.format(outcomes=_OUTCOMES, bundle=bundle), + prompt=_SELECTION_PROMPT.format( + outcomes=_OUTCOMES, + bundle=bundle, + passages=render_selection_passages( + catalog=catalog, document_md=document_md + ), + ), temperature=0.0, ), response_type=SelectionResponse, @@ -558,6 +690,85 @@ def _extract_chunk( usage=selection_call.usage, ) selection = selection_call.output + cards, truncated, diagnostics = publish_selection_cards( + cards=selection.references, + catalog=catalog.by_label(), + document_md=document_md, + owner_chunk=chunk, + ) + self._catalog.selections.freeze( + deployment_id=source.deployment_id, + representation_id=source.representation_id, + chunk_id=chunk.chunk_id, + extractor_version=E2_EXTRACTOR_VERSION, + input_hash=chunk.extraction_input_hash, + selection=selection, + cards=cards, + diagnostics=diagnostics, + truncated=truncated, + ) + + def _reuse_prior_claimify( + self, + *, + source: ChunkSource, + chunk: ChunkForEmbedding, + reference_chunks: tuple[ChunkForEmbedding, ...], + document_md: str, + occurrence_context: RepresentationOccurrenceContext | None, + claimify_hash: str, + ) -> bool: + """The D56 Claimify reuse rung: same claim IDs only with the full hash. + + Every stored span remaps through the target-9..+1 windows. Incomplete + mapping refuses reuse. Zero-claim completion is persisted by attach. + """ + prior = self._catalog.prior_extracted_chunk( + deployment_id=source.deployment_id, + doc_id=source.doc_id, + version_id=chunk.version_id, + extraction_input_hash=chunk.extraction_input_hash, + claimify_input_hash=claimify_hash, + ) + if prior is None: + return False + remapped = self._remap_reused_spans( + chunk=chunk, + reference_chunks=reference_chunks, + document_md=document_md, + prior_chunk_id=prior, + ) + if remapped is None: + return False + occurrences = self._reused_occurrences( + remapped_spans=remapped, occurrence_context=occurrence_context + ) + self._catalog.attach_reused_claims( + deployment_id=source.deployment_id, + chunk_id=chunk.chunk_id, + prior_chunk_id=prior, + occurrences=occurrences, + evidence_spans=remapped, + claimify_input_hash=claimify_hash, + ) + return True + + def _claimify_chunk( + self, + *, + source: ChunkSource, + chunks: tuple[ChunkForEmbedding, ...], + index: int, + document_md: str, + meter: CostMeterPort, + occurrence_context: RepresentationOccurrenceContext | None, + target_frozen: FrozenSelection, + preceding: tuple[FrozenSelection, ...], + claimify_hash: str, + ) -> None: + """Run Claimify against frozen keeps and admitted reference cards.""" + chunk = chunks[index] + selection = target_frozen.selection decisions = list( _selection_decisions(source=source, chunk=chunk, selection=selection) ) @@ -567,34 +778,53 @@ def _extract_chunk( if candidate.verdict is not SelectionVerdict.DROP ) claims: list[ClaimRecord] = [] + claimify_truncated = False if keeps: keep_ranges = tuple( _keep_range(keep=keep, chunk=chunk, document_md=document_md) for keep in keeps ) kept_ranges = tuple(span for span in keep_ranges if span is not None) + eligible = collect_eligible_cards(target=target_frozen, preceding=preceding) + fitted, claimify_truncated = rank_and_fit_cards( + cards=eligible, + target_text=document_md[chunk.char_start : chunk.char_end], + target_ordinal=chunk.ordinal, + ) previous, following = same_section_neighbours(chunks=chunks, index=index) catalog = build_passage_catalog( - blocks=blocks, + blocks=_load_blocks( + artifact_store=self._artifact_store, + source=source, + document_md=document_md, + ), target=chunk, previous=previous, following=following, kept_ranges=kept_ranges, ) + catalog, fitted = attach_card_passages(catalog=catalog, cards=fitted) flagged_spans = { candidate.source_span for candidate in keeps if candidate.verdict is SelectionVerdict.KEEP_FLAGGED } + grounding_texts = card_passage_texts(cards=fitted) response_call = self._model_provider.generate( request=ModelRequest( model=self._settings.extract_model, prompt=_CLAIMIFY_PROMPT.format( keeps="\n".join(f"- {keep.source_span}" for keep in keeps), - bundle=bundle, + bundle=_bundle_text( + source=source, + chunks=chunks, + index=index, + document_md=document_md, + ), passages=render_passage_catalog( catalog=catalog, document_md=document_md ), + cards=render_cards_for_claimify(cards=fitted), ), temperature=0.0, ), @@ -629,6 +859,7 @@ def _extract_chunk( flagged_spans=flagged_spans, kept_ranges=kept_ranges, catalog=catalog, + card_passage_texts=grounding_texts, ) origin_range = _origin_range_for_accounting( result=result, candidate=candidate, catalog=catalog @@ -662,6 +893,15 @@ def _extract_chunk( source=source, chunk=chunk, keep=keep ) ) + decisions.extend( + _card_loss_decisions( + source=source, + chunk=chunk, + diagnostics=target_frozen.diagnostics, + selection_truncated=target_frozen.truncated, + claimify_truncated=claimify_truncated, + ) + ) decisions = _link_flagged_decisions( decisions=decisions, claims=claims, chunk=chunk, document_md=document_md ) @@ -677,8 +917,15 @@ def _extract_chunk( claims=accepted, decisions=tuple(decisions), occurrences=_occurrences_for_claims(claims=accepted, context=context), + claimify_input_hash=claimify_hash, ) + def _read_markdown(self, *, source: ChunkSource) -> str: + """Load the representation markdown; absence is a retryable store miss.""" + return self._artifact_store.read_bytes( + key=ObjectKey(source.markdown_uri) + ).decode("utf-8") + def _load_occurrence_context( self, *, source: ChunkSource ) -> RepresentationOccurrenceContext | None: @@ -729,14 +976,12 @@ def _load_occurrence_context( def _remap_reused_spans( self, *, - source: ChunkSource, chunk: ChunkForEmbedding, - chunks: tuple[ChunkForEmbedding, ...], - index: int, + reference_chunks: tuple[ChunkForEmbedding, ...], document_md: str, prior_chunk_id: UUID, ) -> dict[UUID, tuple[EvidenceSpan, ...]] | None: - """Remap every prior occurrence span into this representation's windows.""" + """Remap every prior span through target-9..+1 relative-ordinal windows.""" prior_representation_id = self._chunk_catalog.representation_id_for_chunk( chunk_id=prior_chunk_id ) @@ -745,38 +990,19 @@ def _remap_reused_spans( prior_source = self._chunk_catalog.chunk_source( representation_id=prior_representation_id ) - prior_chunks = self._chunk_catalog.chunks_for_extract( + prior_chunks = self._chunk_catalog.chunks_for_references( representation_id=prior_representation_id, chunker_version=self._chunker_version, chunk_id=prior_chunk_id, ) - prior_index = next( - ( - position - for position, item in enumerate(prior_chunks) - if item.chunk_id == prior_chunk_id - ), - None, + prior_chunk = next( + (item for item in prior_chunks if item.chunk_id == prior_chunk_id), None ) - if prior_index is None: + if prior_chunk is None: return None - prior_md = self._artifact_store.read_bytes( - key=ObjectKey(prior_source.markdown_uri) - ).decode("utf-8") - prior_previous, prior_following = same_section_neighbours( - chunks=prior_chunks, index=prior_index - ) - current_previous, current_following = same_section_neighbours( - chunks=chunks, index=index - ) - prior_windows = window_bounds( - target=prior_chunks[prior_index], - previous=prior_previous, - following=prior_following, - ) - current_windows = window_bounds( - target=chunk, previous=current_previous, following=current_following - ) + prior_md = self._read_markdown(source=prior_source) + prior_windows = reference_windows(chunks=prior_chunks, target=prior_chunk) + current_windows = reference_windows(chunks=reference_chunks, target=chunk) remapped: dict[UUID, tuple[EvidenceSpan, ...]] = {} for anchor in self._catalog.claims_for_occurrence_reuse( chunk_id=prior_chunk_id @@ -825,6 +1051,8 @@ class GroundingGate(StrEnum): ORIGIN_NOT_ELIGIBLE = "origin_not_eligible" TOO_MANY_SOURCE_REFS = "too_many_source_refs" EMPTY_SOURCE_REFS = "empty_source_refs" + REFERENCE_CARD_REJECTED = "reference_card_rejected" + REFERENCE_CARD_CAP = "reference_card_cap" @dataclass(frozen=True) @@ -850,6 +1078,7 @@ def _grounded_claim( flagged_spans: set[str], kept_ranges: tuple[tuple[int, int], ...], catalog: PassageCatalog, + card_passage_texts: tuple[str, ...] = (), ) -> ClaimRecord | GroundingRejection: """Apply the deterministic grounding gate (D32 layers 1-2, D119 refs). @@ -897,7 +1126,11 @@ def _grounded_claim( ) claim_span = document_md[origin.char_start : origin.char_end] grounding_elements = _source_grounding_elements( - source=source, chunks=chunks, index=index, document_md=document_md + source=source, + chunks=chunks, + index=index, + document_md=document_md, + card_passage_texts=card_passage_texts, ) valid_from, valid_until, valid_precision, valid_kind = _parse_claim_valid_time( candidate=candidate @@ -1151,13 +1384,15 @@ def _source_grounding_elements( chunks: tuple[ChunkForEmbedding, ...], index: int, document_md: str, + card_passage_texts: tuple[str, ...] = (), ) -> tuple[tuple[str, str], ...]: """Return the complete D32 layer-2 membership union. Every member is source-derived: the target chunk slice, deterministic - document header, same-section neighbours, and validated D80 - LocationElement rows. Free-form location headers and section summaries - are deliberately absent (D79/D80). + document header, same-section neighbours, validated D80 LocationElement + rows, and verbatim supporting passages of admitted reference cards. + Generated card names, free-form location headers, and section summaries + are deliberately absent (D79/D80/D122). """ chunk = chunks[index] elements = [ @@ -1178,6 +1413,8 @@ def _source_grounding_elements( ) for kind, text in _location_grounding_pairs(chunk=chunk): elements.append((kind, text)) + for ordinal, text in enumerate(card_passage_texts, start=1): + elements.append((f"reference_card_passage_{ordinal}", text)) return tuple(elements) @@ -1448,6 +1685,114 @@ def _empty_extraction_marker( ) +def _require_chunk( + *, chunks: tuple[ChunkForEmbedding, ...], chunk_id: UUID, representation_id: UUID +) -> tuple[int, ChunkForEmbedding]: + """Return the target inside a loaded window or fail permanently.""" + index = next( + ( + position + for position, chunk in enumerate(chunks) + if chunk.chunk_id == chunk_id + ), + None, + ) + if index is None: + raise NonRetryableHandlerError( + f"chunk {chunk_id} is not part of representation {representation_id}" + ) + return index, chunks[index] + + +def _selection_barrier( + *, work: ClaimedWork, source: ChunkSource, chunker_version: str +) -> HandlerOutcome: + """Selection completion; the ledger opens Claimify after every freeze exists.""" + return HandlerOutcome( + selection_chunk_barrier=SelectionChunkBarrier( + deployment_id=work.deployment_id, + version_id=source.version_id, + representation_id=source.representation_id, + chunker_version=chunker_version, + extractor_version=E2_EXTRACTOR_VERSION, + content_hash=work.content_hash, + lane=work.lane, + normalize_component_version=E3_NORMALIZER_VERSION, + ) + ) + + +def _extract_barrier( + *, work: ClaimedWork, source: ChunkSource, chunker_version: str +) -> HandlerOutcome: + """Claimify completion; normalizing waits for every ground_claims row.""" + return HandlerOutcome( + extract_chunk_barrier=ExtractChunkBarrier( + deployment_id=work.deployment_id, + version_id=source.version_id, + representation_id=source.representation_id, + chunker_version=chunker_version, + extractor_version=E2_EXTRACTOR_VERSION, + content_hash=work.content_hash, + lane=work.lane, + normalize_component_version=E3_NORMALIZER_VERSION, + ) + ) + + +def _card_loss_decisions( + *, + source: ChunkSource, + chunk: ChunkForEmbedding, + diagnostics: tuple[CardDiagnostic, ...], + selection_truncated: bool, + claimify_truncated: bool, +) -> list[DecisionRecord]: + """D33 rows for unpublished or cap-dropped reference cards.""" + rows: list[DecisionRecord] = [] + for diagnostic in diagnostics: + rows.append( + _grounding_rejected_decision( + source=source, + chunk=chunk, + rejection=GroundingRejection( + gate=GroundingGate.REFERENCE_CARD_REJECTED, + claim_span=diagnostic.detail, + kind="reference_card", + text=diagnostic.gate, + failed_tokens=(str(diagnostic.ordinal),), + ), + ) + ) + if selection_truncated: + rows.append( + _grounding_rejected_decision( + source=source, + chunk=chunk, + rejection=GroundingRejection( + gate=GroundingGate.REFERENCE_CARD_CAP, + claim_span="selection_card_cap", + kind="reference_card", + text="selection", + ), + ) + ) + if claimify_truncated: + rows.append( + _grounding_rejected_decision( + source=source, + chunk=chunk, + rejection=GroundingRejection( + gate=GroundingGate.REFERENCE_CARD_CAP, + claim_span="claimify_card_cap", + kind="reference_card", + text="claimify", + ), + ) + ) + return rows + + def _grounding_rejected_decision( *, source: ChunkSource, chunk: ChunkForEmbedding, rejection: GroundingRejection ) -> DecisionRecord: @@ -1462,6 +1807,14 @@ def _grounding_rejected_decision( edit_detail["text"] = _truncate_for_ledger(rejection.text or "") edit_detail["searched_elements"] = list(rejection.searched_elements) edit_detail["failed_tokens"] = list(rejection.failed_tokens) + elif rejection.gate in ( + GroundingGate.REFERENCE_CARD_REJECTED, + GroundingGate.REFERENCE_CARD_CAP, + ): + edit_detail["kind"] = _truncate_for_ledger(rejection.kind or "reference_card") + edit_detail["detail"] = _truncate_for_ledger(rejection.text or "") + if rejection.failed_tokens: + edit_detail["ordinal"] = rejection.failed_tokens[0] return DecisionRecord( decision_id=uuid4(), deployment_id=source.deployment_id, diff --git a/src/rememberstack/workers/extraction_references.py b/src/rememberstack/workers/extraction_references.py new file mode 100644 index 000000000..19af0b29c --- /dev/null +++ b/src/rememberstack/workers/extraction_references.py @@ -0,0 +1,256 @@ +"""D122 helpers: remap Selection cards and attach them to a Claimify catalog. + +E2 Selection sees only the local target/previous/next windows. Claimify later +reads frozen cards from the previous eight source chunks. Those cards may cite +the earliest producer's previous neighbour, so occurrence remapping uses the +fixed ordinal slots from target-9 through target+1. Temporary labels are +request-local and are assigned here, never stored as identity. +""" + +from __future__ import annotations + +from typing import Final +from uuid import UUID + +from rememberstack.core.selection_references import GroundedCard +from rememberstack.core.selection_references import GroundedPassage +from rememberstack.core.selection_references import PRECEDING_CHUNK_LIMIT +from rememberstack.core.selection_references import remap_card +from rememberstack.core.source_passages import EvidenceSpan +from rememberstack.core.source_passages import PassageCatalog +from rememberstack.core.source_passages import PassageRegion +from rememberstack.core.source_passages import remap_evidence_spans +from rememberstack.core.source_passages import same_section_neighbours +from rememberstack.core.source_passages import SourcePassage +from rememberstack.core.source_passages import window_bounds +from rememberstack.model.chunks import ChunkForEmbedding +from rememberstack.spine.selection_catalog import FrozenSelection + +# Earliest preceding producer (target-8) may cite its previous neighbour. +_REFERENCE_BEHIND: Final = PRECEDING_CHUNK_LIMIT + 1 +_REFERENCE_AHEAD: Final = 1 + + +class MissingSelectionError(Exception): + """A required frozen Selection producer is absent; Claimify must not invent empty.""" + + +def reference_windows( + *, chunks: tuple[ChunkForEmbedding, ...], target: ChunkForEmbedding +) -> tuple[tuple[int, int] | None, ...]: + """Non-overlapping remapping slots keyed by ordinal relative to the target. + + Index 0 is target-9, then each following ordinal through target+1. A missing + ordinal stays None so a neighbour cannot change sides when a boundary moves. + """ + by_ordinal = {chunk.ordinal: chunk for chunk in chunks} + windows: list[tuple[int, int] | None] = [] + for relative in range(-_REFERENCE_BEHIND, _REFERENCE_AHEAD + 1): + chunk = by_ordinal.get(target.ordinal + relative) + windows.append(None if chunk is None else (chunk.char_start, chunk.char_end)) + return tuple(windows) + + +def preceding_producer_ids( + *, chunks: tuple[ChunkForEmbedding, ...], target: ChunkForEmbedding +) -> tuple[UUID, ...]: + """Source chunks in the previous-eight window, document order, excluding target-9.""" + start = target.ordinal - PRECEDING_CHUNK_LIMIT + return tuple( + chunk.chunk_id for chunk in chunks if start <= chunk.ordinal < target.ordinal + ) + + +def require_frozen_producers( + *, loaded: dict[UUID, FrozenSelection], required_ids: tuple[UUID, ...] +) -> tuple[FrozenSelection, ...]: + """Return producers in required order; a missing row is not an empty result.""" + missing = tuple(chunk_id for chunk_id in required_ids if chunk_id not in loaded) + if missing: + joined = ", ".join(str(chunk_id) for chunk_id in missing) + raise MissingSelectionError( + f"required Selection result is missing for chunk(s) {joined}" + ) + return tuple(loaded[chunk_id] for chunk_id in required_ids) + + +def collect_eligible_cards( + *, target: FrozenSelection, preceding: tuple[FrozenSelection, ...] +) -> tuple[GroundedCard, ...]: + """Target cards plus every previous-eight producer's published cards.""" + cards = list(target.cards) + for frozen in preceding: + cards.extend(frozen.cards) + return tuple(cards) + + +def card_passage_texts(*, cards: tuple[GroundedCard, ...]) -> tuple[str, ...]: + """Verbatim supporting passage text admitted into D32 layer-2 membership.""" + return tuple(passage.text for card in cards for passage in card.passages) + + +def render_selection_passages(*, catalog: PassageCatalog, document_md: str) -> str: + """Engine-built local labels Selection may cite; not Claimify origin rules.""" + if not catalog.passages: + return "(no source passages)" + lines = [ + "SOURCE PASSAGES (cite only these labels; never invent a label " + "or character offset):" + ] + for passage in catalog.passages: + body = document_md[passage.char_start : passage.char_end] + lines.append(f"[{passage.label}] {passage.region.upper()}:\n{body}") + return "\n\n".join(lines) + + +def attach_card_passages( + *, catalog: PassageCatalog, cards: tuple[GroundedCard, ...] +) -> tuple[PassageCatalog, tuple[GroundedCard, ...]]: + """Append card supports as origin-ineligible passages with request-unique labels.""" + extra: list[SourcePassage] = [] + relabeled: list[GroundedCard] = [] + next_index = len(catalog.passages) + 1 + for card in cards: + new_passages: list[GroundedPassage] = [] + for passage in card.passages: + label = f"S{next_index}" + next_index += 1 + extra.append( + SourcePassage( + label=label, + char_start=passage.char_start, + char_end=passage.char_end, + region=passage.region, + origin_eligible=False, + ) + ) + new_passages.append( + GroundedPassage( + label=label, + char_start=passage.char_start, + char_end=passage.char_end, + region=passage.region, + text=passage.text, + ) + ) + relabeled.append( + GroundedCard( + name=card.name, + aliases=card.aliases, + passages=tuple(new_passages), + ordinal=card.ordinal, + owner_chunk_id=card.owner_chunk_id, + owner_ordinal=card.owner_ordinal, + ) + ) + if not extra: + return catalog, cards + return (PassageCatalog(passages=(*catalog.passages, *extra)), tuple(relabeled)) + + +def remap_frozen_cards( + *, + cards: tuple[GroundedCard, ...], + prior_chunks: tuple[ChunkForEmbedding, ...], + prior_index: int, + current_chunks: tuple[ChunkForEmbedding, ...], + current_index: int, + prior_md: str, + current_md: str, + current_chunk: ChunkForEmbedding, +) -> tuple[GroundedCard, ...] | None: + """Translate every card range through D119 local windows onto this occurrence. + + Incomplete, ambiguous, or text-mismatched mapping rejects the whole reuse. + Owner identity is this chunk, not the prior version's row. + """ + if not cards: + return () + prior_previous, prior_following = same_section_neighbours( + chunks=prior_chunks, index=prior_index + ) + current_previous, current_following = same_section_neighbours( + chunks=current_chunks, index=current_index + ) + prior_bounds = window_bounds( + target=prior_chunks[prior_index], + previous=prior_previous, + following=prior_following, + ) + current_bounds = window_bounds( + target=current_chunk, previous=current_previous, following=current_following + ) + current_regions = _region_windows( + target=current_chunk, previous=current_previous, following=current_following + ) + remapped: list[GroundedCard] = [] + for card in cards: + translated = _remap_card_ranges( + card=card, + prior_windows=prior_bounds, + current_windows=current_bounds, + prior_md=prior_md, + current_md=current_md, + ) + grounded = remap_card( + card=card, + remapped_spans=translated, + current_md=current_md, + current_windows=current_regions, + ) + if grounded is None: + return None + remapped.append( + GroundedCard( + name=grounded.name, + aliases=grounded.aliases, + passages=grounded.passages, + ordinal=grounded.ordinal, + owner_chunk_id=current_chunk.chunk_id, + owner_ordinal=current_chunk.ordinal, + ) + ) + return tuple(remapped) + + +def _remap_card_ranges( + *, + card: GroundedCard, + prior_windows: tuple[tuple[int, int] | None, ...], + current_windows: tuple[tuple[int, int] | None, ...], + prior_md: str, + current_md: str, +) -> tuple[tuple[int, int], ...] | None: + """Remap each passage independently so canonicalize cannot reorder supports.""" + translated: list[tuple[int, int]] = [] + for passage in card.passages: + result = remap_evidence_spans( + prior_spans=( + EvidenceSpan(char_start=passage.char_start, char_end=passage.char_end), + ), + prior_windows=prior_windows, + current_windows=current_windows, + prior_md=prior_md, + current_md=current_md, + ) + if result is None or len(result) != 1: + return None + translated.append((result[0].char_start, result[0].char_end)) + return tuple(translated) + + +def _region_windows( + *, + target: ChunkForEmbedding, + previous: ChunkForEmbedding | None, + following: ChunkForEmbedding | None, +) -> dict[PassageRegion, tuple[int, int]]: + """Present local windows only; a missing side is omitted, not shifted.""" + windows: dict[PassageRegion, tuple[int, int]] = { + "target": (target.char_start, target.char_end) + } + if previous is not None: + windows["previous"] = (previous.char_start, previous.char_end) + if following is not None: + windows["next"] = (following.char_start, following.char_end) + return windows From 8616a6e2dcc04b54bd0272d721e8adad535387cb Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 14:36:26 +0200 Subject: [PATCH 06/14] wip(processing): integrate frozen Selection storage and shared-context barriers --- .github/ci/integration-paths.txt | 1 + .github/workflows/ci.yml | 8 +- compose.yaml | 7 + ...123_document_reference_context_20260914.md | 44 +++- .../core/concise_adjudication.py | 29 ++- src/rememberstack/profiles/selfhost.py | 4 +- src/rememberstack/spine/chunk_catalog.py | 33 +++ src/rememberstack/spine/claim_catalog.py | 66 +++++ src/rememberstack/spine/fact_adjudication.py | 10 +- .../spine/fact_application_inputs.py | 51 +++- .../p9_32_0053_source_reference_context.py | 16 +- src/rememberstack/spine/selection_catalog.py | 239 ++++++++++++++++++ src/rememberstack/spine/work_ledger.py | 98 ++++++- src/rememberstack/workers/base.py | 13 +- src/rememberstack/workers/e3.py | 6 +- src/tests/core/test_concise_adjudication.py | 25 ++ src/tests/profiles/test_selfhost_profile.py | 2 +- src/tests/spine/test_d122_selection.py | 216 ++++++++++++++++ .../spine/test_d123_context_nomination.py | 33 +++ src/tests/workers/test_d119_versions.py | 40 ++- 20 files changed, 905 insertions(+), 36 deletions(-) create mode 100644 src/rememberstack/spine/selection_catalog.py create mode 100644 src/tests/spine/test_d122_selection.py diff --git a/.github/ci/integration-paths.txt b/.github/ci/integration-paths.txt index 86284e7d8..a9a4f6ee8 100644 --- a/.github/ci/integration-paths.txt +++ b/.github/ci/integration-paths.txt @@ -59,3 +59,4 @@ src/tests/spine/test_claim_occurrence_provenance.py src/tests/spine/test_d119_multi_span.py src/tests/spine/test_d119_migration.py src/tests/workers/test_d119_versions.py +src/tests/spine/test_d122_selection.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index eb1cc0397..5f6df897f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -346,7 +346,7 @@ jobs: config = Config("alembic.ini") config.set_main_option("sqlalchemy.url", database_url) reset_database(config=config) - command.upgrade(config=config, revision="p9_30_0051") + command.upgrade(config=config, revision="p9_31_0052") engine = create_engine(database_url) DeploymentBootstrapper(engine=engine).bootstrap_deployment( deployment_input=deployment @@ -355,7 +355,7 @@ jobs: PY test "$(docker compose --env-file .env.example exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ - 'SELECT version_num FROM alembic_version')" = 'p9_30_0051' + 'SELECT version_num FROM alembic_version')" = 'p9_31_0052' test "$(docker compose --env-file .env.example exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ 'SELECT count(*) FROM deployments')" = '1' @@ -395,14 +395,14 @@ jobs: | grep -E '^(api|worker-(convert|structure|chunk|embed-chunk|extract-claims|normalize-relations|adjudicate-observations|adjudicate-supersession|embed-claim|reconcile|label-relation))$' || true)" test "$(docker compose "${compose_args[@]}" exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ - 'SELECT version_num FROM alembic_version')" = 'p9_30_0051' + 'SELECT version_num FROM alembic_version')" = 'p9_31_0052' release_gate wait "$compose_pid" trap - EXIT test "$(docker compose --env-file .env.example exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ - 'SELECT version_num FROM alembic_version')" = 'p9_31_0052' + 'SELECT version_num FROM alembic_version')" = 'p9_32_0053' test "$(docker compose --env-file .env.example exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ 'SELECT count(*) FROM deployments')" = '1' diff --git a/compose.yaml b/compose.yaml index e1e9bfed0..001c389a5 100644 --- a/compose.yaml +++ b/compose.yaml @@ -201,6 +201,13 @@ services: setup: condition: service_completed_successfully + worker-ground-claims: + <<: *app + command: ["worker", "--stage", "ground_claims"] + depends_on: + setup: + condition: service_completed_successfully + worker-normalize-relations: <<: *app command: ["worker", "--stage", "normalize_relations"] diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md index 2aca8169d..6286003d2 100644 --- a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -13,7 +13,7 @@ Binding designs: [D122](../designs/document_reference_context_design.md), Parent owns final integration, review, merge, and release. This branch must not be self-merged. -## What this head implements +## Earlier independent D123 checkpoint D123's independent path is implemented on this head: @@ -108,3 +108,45 @@ semantic-quality claim. - Constraint counts and table inventory must be re-checked after the D119 migration is inserted. - Parent review of #403 is still required before merge. + +## Parent integration checkpoint + +D119 merged in PR400 as `4411774b`; D120/D121 merged in PR402 as `6205fe09`. +The document-context branch has incorporated the published combined runtime; +its final rebase onto these squash merges follows the current shared edits. + +Parent has implemented the source-owned Selection catalog, first-publication +wins (including zero-output responses), late-publication source/forget checks, +and a representation barrier using the existing work ledger. Selection remains +`extract_claims`; the existing `ground_claims` stage now runs Claimify, with +normalization behind its completion barrier. Both stages use the same E2 handler. +The self-host and Compose worker sets include both phases. No third model call, +queue, cache or claim-receipt table was introduced. A hash on the existing chunk +row records Claimify's completed input identity atomically with its output. + +Grounded context is now projected into the concise adjudication input as named +entities linked to the assertion and its claim. Canonical aliases/names are +frozen with the snapshot and invalidate a prepared answer when changed. The +full membership checks remain internal. A normalizer instruction now permits +a particular unnamed event with a descriptive name; it does not invent a +proper name or require an event type. + +Parent checks completed at this checkpoint: four PostgreSQL Selection/barrier/ +source-removal/window proofs passed;36 concise-input/profile tests passed; +eight contextual nomination PostgreSQL tests passed. A ninth test initially +failed because its call used the wrong keyword for the existing snapshot-hash +helper; the test was corrected and its final result is recorded subsequently. +Changed storage, ledger and profile modules passed Pyright. Grok replaced the +temporary passage type with D119's actual SourcePassage and passed15 core tests, +ruff and Pyright. Both minor earlier review nits are now addressed. + +The handler split and complete source-reference/reuse wiring are still being +implemented by Grok in a bounded task while parent owns storage, scheduling, +combined tests and final wording. Do not treat this checkpoint as complete or +merge-ready. Final protocol31 pins, full combined tests, Antigravity review and +parent adjustments remain required. No paid model call has run. + +The user authorized re-processing conv-42 with Gemma on Vertex after all three +PRs land. Parent must verify every processing-stage binding before those calls, +then report processing cost, latency and source-linked claim/fact quality. +Answering/judging remain outside that run. diff --git a/src/rememberstack/core/concise_adjudication.py b/src/rememberstack/core/concise_adjudication.py index 85b7c7eeb..89644ff00 100644 --- a/src/rememberstack/core/concise_adjudication.py +++ b/src/rememberstack/core/concise_adjudication.py @@ -18,7 +18,7 @@ from rememberstack.model.fact_application import NewFact from rememberstack.model.fact_windows import GroundedFactWindow -PROMPT_RENDERER_VERSION = "concise-handles-1" +PROMPT_RENDERER_VERSION = "concise-handles-2" """Pinned projector/response-adapter generation included in the fingerprint.""" # F/C/A/E/S are citable supplied rows. T is factored text. W is a window @@ -144,6 +144,8 @@ def _compact_content( if not isinstance(content, Mapping): return content compacted = dict(content) + # Resolved context is presented separately with the attempt's entity names. + compacted.pop("context_refs", None) field, rendered = _text_value( text=compacted.get("statement"), repeats=repeats, @@ -242,6 +244,24 @@ def project_concise_inputs( ) same_as[_as_id(object_raw)] = canonical_id same_as[canonical_id] = canonical_id + for row in assertion_rows: + for context in row.get("context_entities", ()): + entity_id = _as_id(context["entity_id"]) + canonical_id = _as_id(context["canonical_entity_id"]) + _remember_entity( + entity_ids=entity_ids, + names=entity_names, + entity_id=entity_id, + name=context.get("name"), + ) + _remember_entity( + entity_ids=entity_ids, + names=entity_names, + entity_id=canonical_id, + name=context.get("canonical_name"), + ) + same_as[entity_id] = canonical_id + same_as[canonical_id] = canonical_id for entity_id, canonical_id in same_as.items(): if entity_names.get(entity_id) and not entity_names.get(canonical_id): entity_names[canonical_id] = entity_names[entity_id] @@ -406,6 +426,11 @@ def entity_ref(raw: object) -> tuple[str, str | None]: item["object"] = obj if canonical_object is not None: item["canonical_object"] = canonical_object + if row.get("context_entities"): + item["context"] = [ + entity_ref(context["entity_id"])[0] + for context in row["context_entities"] + ] presented_assertions.append(item) evidence = [] @@ -452,6 +477,8 @@ def entity_ref(raw: object) -> tuple[str, str | None]: names for names in contradiction_groups.values() if len(names) > 1 ], } + if snapshot.get("context_truncated"): + presentation["context_truncated"] = True if evidence_not_supplied: presentation["evidence_not_supplied"] = evidence_not_supplied mapping = AttemptMapping( diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index 7570499bd..447247bc7 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -80,6 +80,7 @@ PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, PipelineStage.NORMALIZE_RELATIONS, PipelineStage.ADJUDICATE_OBSERVATIONS, PipelineStage.ADJUDICATE_SUPERSESSION, @@ -1263,7 +1264,7 @@ def _handler(self, *, stage: PipelineStage) -> StageHandler: settings=e1_settings, params=params, ) - if stage is PipelineStage.EXTRACT_CLAIMS: + if stage in (PipelineStage.EXTRACT_CLAIMS, PipelineStage.GROUND_CLAIMS): return ExtractClaimsHandler( catalog=claims, chunk_catalog=chunks, @@ -1516,6 +1517,7 @@ def _expected_components() -> dict[PipelineStage, str]: PipelineStage.CHUNK: E1_CHUNK_VERSION, PipelineStage.EMBED_CHUNK: E1_EMBED_VERSION, PipelineStage.EXTRACT_CLAIMS: E2_EXTRACTOR_VERSION, + PipelineStage.GROUND_CLAIMS: E2_EXTRACTOR_VERSION, PipelineStage.NORMALIZE_RELATIONS: E3_NORMALIZER_VERSION, PipelineStage.ADJUDICATE_OBSERVATIONS: OBS_FLUSH_VERSION, PipelineStage.ADJUDICATE_SUPERSESSION: ADJUDICATOR_VERSION, diff --git a/src/rememberstack/spine/chunk_catalog.py b/src/rememberstack/spine/chunk_catalog.py index c8814462c..0bf48e6a3 100644 --- a/src/rememberstack/spine/chunk_catalog.py +++ b/src/rememberstack/spine/chunk_catalog.py @@ -132,6 +132,28 @@ def chunks_for_extract( for row in rows ) + def chunks_for_references( + self, *, representation_id: UUID, chunker_version: str, chunk_id: UUID + ) -> tuple[ChunkForEmbedding, ...]: + """Load target, eight preceding producers and their possible neighbor support.""" + with self._engine.connect() as connection: + rows = ( + connection.execute( + _SELECT_FOR_REFERENCE_WINDOW, + { + "representation_id": representation_id, + "chunker_version": chunker_version, + "chunk_id": chunk_id, + }, + ) + .mappings() + .all() + ) + return tuple( + ChunkForEmbedding.model_validate(_normalize_chunk_embed_row(dict(row))) + for row in rows + ) + def list_chunk_ids( self, *, representation_id: UUID, chunker_version: str ) -> tuple[UUID, ...]: @@ -366,3 +388,14 @@ def _normalize_chunk_embed_row(row: dict) -> dict: WHERE chunk_id = :chunk_id """ ) + + +_SELECT_FOR_REFERENCE_WINDOW = text( + str(_SELECT_FOR_EMBEDDING).replace( + "ORDER BY c.ordinal", + """AND c.ordinal BETWEEN + (SELECT ordinal-9 FROM chunks WHERE chunk_id=:chunk_id) AND + (SELECT ordinal+1 FROM chunks WHERE chunk_id=:chunk_id) + ORDER BY c.ordinal""", + ) +) diff --git a/src/rememberstack/spine/claim_catalog.py b/src/rememberstack/spine/claim_catalog.py index 0c0242423..70d9d976c 100644 --- a/src/rememberstack/spine/claim_catalog.py +++ b/src/rememberstack/spine/claim_catalog.py @@ -25,6 +25,8 @@ from rememberstack.model.occurrence_provenance import OccurrenceProvenance from rememberstack.model.occurrence_provenance import ReusedClaimAnchor from rememberstack.ports.p1_index import CLAIM_INPUT_POLICY +from rememberstack.spine.selection_catalog import require_extraction_sources_on +from rememberstack.spine.selection_catalog import SelectionCatalog class ClaimCatalog: @@ -33,6 +35,7 @@ class ClaimCatalog: def __init__(self, *, engine: Engine) -> None: """Bind the catalog to the spine database.""" self._engine = engine + self.selections = SelectionCatalog(engine=engine) def chunk_already_extracted( self, *, chunk_id: UUID, extractor_version: str @@ -60,6 +63,7 @@ def prior_extracted_chunk( doc_id: UUID, version_id: UUID, extraction_input_hash: str, + claimify_input_hash: str | None = None, ) -> UUID | None: """The D56 reuse lookup: an already-extracted chunk with the same key. @@ -81,6 +85,7 @@ def prior_extracted_chunk( "doc_id": doc_id, "version_id": version_id, "extraction_input_hash": extraction_input_hash, + "claimify_input_hash": claimify_input_hash, }, ).scalar_one_or_none() @@ -115,6 +120,7 @@ def attach_reused_claims( prior_chunk_id: UUID, occurrences: Mapping[UUID, OccurrenceProvenance] | None = None, evidence_spans: Mapping[UUID, tuple[EvidenceSpan, ...]] | None = None, + claimify_input_hash: str | None = None, ) -> int: """Re-attach a prior chunk's claims to a new version's chunk (D56/F4). @@ -131,9 +137,26 @@ def attach_reused_claims( empty). """ with self._engine.begin() as connection: + if claimify_input_hash is not None: + require_extraction_sources_on( + connection=connection, + deployment_id=deployment_id, + chunk_ids=(chunk_id, prior_chunk_id), + ) prior_links = connection.execute( _COUNT_CHUNK_CLAIMS, {"chunk_id": prior_chunk_id} ).scalar_one() + if claimify_input_hash is not None: + existing = connection.execute( + text( + "SELECT claimify_input_hash FROM chunks WHERE chunk_id=:chunk_id FOR UPDATE" + ), + {"chunk_id": chunk_id}, + ).scalar_one() + if existing is not None: + if existing != claimify_input_hash: + raise ValueError("Claimify completion has different inputs") + return prior_links if prior_links: claim_ids = connection.execute( _SELECT_DISTINCT_CHUNK_CLAIM_IDS, {"chunk_id": prior_chunk_id} @@ -162,6 +185,18 @@ def attach_reused_claims( evidence_spans=spans, ), ) + if claimify_input_hash is not None: + if not prior_links: + copied = connection.execute( + _COPY_CHUNK_DECISIONS, + {"chunk_id": chunk_id, "prior_chunk_id": prior_chunk_id}, + ).rowcount + if not copied: + raise ValueError("reused extraction has no terminal evidence") + connection.execute( + _STAMP_CLAIMIFY, + {"chunk_id": chunk_id, "input_hash": claimify_input_hash}, + ) return prior_links def copy_reused_decisions(self, *, chunk_id: UUID, prior_chunk_id: UUID) -> int: @@ -268,6 +303,7 @@ def record_extraction( claims: tuple[ClaimRecord, ...], decisions: tuple[DecisionRecord, ...], occurrences: Mapping[UUID, OccurrenceProvenance] | None = None, + claimify_input_hash: str | None = None, ) -> None: """Land one chunk's claims, occurrence links, and decisions atomically. @@ -278,7 +314,25 @@ def record_extraction( """ if not claims and not decisions: return + owner = claims[0] if claims else decisions[0] with self._engine.begin() as connection: + if claimify_input_hash is not None: + require_extraction_sources_on( + connection=connection, + deployment_id=owner.deployment_id, + chunk_ids=(owner.chunk_id,), + ) + # A retry or concurrent helper cannot publish a second set of claims. + existing = connection.execute( + text( + "SELECT claimify_input_hash FROM chunks WHERE chunk_id=:chunk_id FOR UPDATE" + ), + {"chunk_id": owner.chunk_id}, + ).scalar_one() + if existing is not None: + if existing != claimify_input_hash: + raise ValueError("Claimify completion has different inputs") + return for claim in claims: payload = claim.model_dump(mode="json") payload["added_context"] = [ @@ -303,6 +357,11 @@ def record_extraction( ) for decision in decisions: connection.execute(_INSERT_DECISION, decision.model_dump(mode="json")) + if claimify_input_hash is not None: + connection.execute( + _STAMP_CLAIMIFY, + {"chunk_id": owner.chunk_id, "input_hash": claimify_input_hash}, + ) _SELECT_EXTRACTED = text( @@ -331,6 +390,8 @@ def record_extraction( WHERE c.deployment_id = :deployment_id AND c.doc_id = :doc_id AND c.extraction_input_hash = :extraction_input_hash + AND (CAST(:claimify_input_hash AS text) IS NULL + OR c.claimify_input_hash = :claimify_input_hash) AND cv.version_no < (SELECT version_no FROM document_versions WHERE version_id = :version_id) AND (EXISTS (SELECT 1 FROM chunk_claims x WHERE x.chunk_id = c.chunk_id) @@ -523,3 +584,8 @@ def _chunk_claim_params( "source_locators": locators, "evidence_spans": spans_as_json(evidence_spans), } + + +_STAMP_CLAIMIFY = text( + "UPDATE chunks SET claimify_input_hash=:input_hash WHERE chunk_id=:chunk_id" +) diff --git a/src/rememberstack/spine/fact_adjudication.py b/src/rememberstack/spine/fact_adjudication.py index 906256eba..4ec750d66 100644 --- a/src/rememberstack/spine/fact_adjudication.py +++ b/src/rememberstack/spine/fact_adjudication.py @@ -31,15 +31,15 @@ from rememberstack.spine.fact_applications import snapshot_hash RELATION_APPLICATION_VERSION = ( - "relation-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1" + "relation-adjudicator-2026.09d:concise-handles-5:d123-context-nom-2" ) OBSERVATION_APPLICATION_VERSION = ( - "obs-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1" + "obs-adjudicator-2026.09d:concise-handles-5:d123-context-nom-2" ) FACT_NORMALIZER_VERSION = ( "e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:no-types-1:" "binary-t4-1:document-t0-1:mutable-window-1:assertion-clarity-3:" - "d123-context-refs-1" + "d123-context-refs-2" ) FACT_FLUSH_VERSION = f"e3-obs-flush:entity-fanout-1:{FACT_NORMALIZER_VERSION}:{RELATION_APPLICATION_VERSION}:{OBSERVATION_APPLICATION_VERSION}" @@ -51,7 +51,9 @@ A claim records what a source said. An assertion is one proposition taken from that claim. A fact is the stored interpretation of testimony about that proposition. An entity is a person, event, place, or other referent. Sharing an -entity does not make two assertions the same proposition. +entity does not make two assertions the same proposition. An assertion's +context lists other resolved referents from its source claim. A shared event +helps comparison; it is not proof of the same assertion. Context entities named on an assertion are other referents the source mentioned. They help find related facts; they do not prove two assertions are the same fact. Empty context does not mean the assertion is new. diff --git a/src/rememberstack/spine/fact_application_inputs.py b/src/rememberstack/spine/fact_application_inputs.py index 9c4bd1ef2..c05cd9988 100644 --- a/src/rememberstack/spine/fact_application_inputs.py +++ b/src/rememberstack/spine/fact_application_inputs.py @@ -8,6 +8,7 @@ from sqlalchemy import text from sqlalchemy.engine import Connection +from rememberstack.core.context_references import MAX_CONTEXT_REFS from rememberstack.spine.fact_applications import ApplicationInputChanged from rememberstack.spine.fact_applications import canonical_entity from rememberstack.spine.fact_applications import canonical_json @@ -392,7 +393,54 @@ def _nominate_fact_ids() -> list[Any]: all_assertions = sorted( [*incoming, *assertions], key=lambda row: row["application_id"] ) + context_rows = _rows( + connection=connection, + sql=""" + WITH RECURSIVE bindings AS ( + SELECT b.application_id,b.ordinal,e.entity_id,e.canonical_name + FROM application_context_bindings b JOIN entities e + ON e.deployment_id=b.deployment_id AND e.entity_id=b.entity_id + WHERE b.deployment_id=:deployment_id + AND b.application_id=ANY(CAST(:application_ids AS uuid[])) + ), chain AS ( + SELECT b.entity_id AS origin,e.entity_id,e.merged_into,e.canonical_name, + ARRAY[e.entity_id] AS path + FROM (SELECT DISTINCT entity_id FROM bindings) b JOIN entities e + ON e.entity_id=b.entity_id AND e.deployment_id=:deployment_id + UNION ALL + SELECT c.origin,e.entity_id,e.merged_into,e.canonical_name,c.path || e.entity_id + FROM chain c JOIN entities e ON e.entity_id=c.merged_into + WHERE e.deployment_id=:deployment_id AND NOT e.entity_id=ANY(c.path) + ) + SELECT b.application_id,b.ordinal,b.entity_id,b.canonical_name AS name, + c.entity_id AS canonical_entity_id,c.canonical_name + FROM bindings b LEFT JOIN chain c ON c.origin=b.entity_id AND c.merged_into IS NULL + ORDER BY b.application_id,b.ordinal + """, + params={ + "deployment_id": deployment_id, + "application_ids": [row["application_id"] for row in all_assertions], + }, + ) + contexts_by_application: dict[UUID, list[dict[str, Any]]] = {} + for context in context_rows: + if context["canonical_entity_id"] is None: + raise ApplicationInputChanged( + "context entity has no surviving canonical root" + ) + contexts_by_application.setdefault(context["application_id"], []).append( + { + key: context[key] + for key in ( + "entity_id", + "name", + "canonical_entity_id", + "canonical_name", + ) + } + ) for row in all_assertions: + row["context_entities"] = contexts_by_application.get(row["application_id"], []) row["canonical_subject_id"] = canonical_entity( connection=connection, deployment_id=deployment_id, @@ -423,7 +471,8 @@ def _nominate_fact_ids() -> list[Any]: "support_hash": support_hash, "context_hash": context_hash, "context_member_ids": [str(entity_id) for entity_id in context_members], - "context_truncated": len(assertion.get("context_refs") or []) > 4, + "context_truncated": len(assertion.get("context_refs") or []) + > MAX_CONTEXT_REFS, "limits": { "facts": _FACT_LIMIT, "context_facts": _CONTEXT_FACT_LIMIT, diff --git a/src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py b/src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py index de15ed7ef..4119f0930 100644 --- a/src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py +++ b/src/rememberstack/spine/migrations/versions/p9_32_0053_source_reference_context.py @@ -19,6 +19,8 @@ depends_on: str | Sequence[str] | None = None _DDL = r""" +ALTER TABLE chunks ADD COLUMN claimify_input_hash text; +CREATE INDEX ix_chunks_claimify_reuse ON chunks (deployment_id,doc_id,claimify_input_hash); CREATE TABLE selection_results ( deployment_id uuid NOT NULL, chunk_id uuid NOT NULL, @@ -64,9 +66,11 @@ def upgrade() -> None: """Refuse a populated store, then add the Selection store and context junction.""" connection = op.get_bind() - if connection.execute(text("SELECT EXISTS(SELECT 1 FROM claims)")).scalar_one(): + if connection.execute( + text("SELECT EXISTS(SELECT 1 FROM claims) OR EXISTS(SELECT 1 FROM chunks)") + ).scalar_one(): raise RuntimeError( - "D122/D123 do not convert a store that already holds claims; " + "D122/D123 do not convert a store that already holds claims or chunks; " "recreate the deployment and ingest its sources again" ) apply_ddl(sql=_DDL) @@ -74,9 +78,5 @@ def upgrade() -> None: def downgrade() -> None: """Drop additive tables.""" - drop_tables( - table_names=( - "application_context_bindings", - "selection_results", - ) - ) + op.execute("ALTER TABLE chunks DROP COLUMN claimify_input_hash") + drop_tables(table_names=("application_context_bindings", "selection_results")) diff --git a/src/rememberstack/spine/selection_catalog.py b/src/rememberstack/spine/selection_catalog.py new file mode 100644 index 000000000..81482d85c --- /dev/null +++ b/src/rememberstack/spine/selection_catalog.py @@ -0,0 +1,239 @@ +"""Frozen source-owned Selection results shared with later Claimify work.""" + +from dataclasses import dataclass +from uuid import UUID + +from sqlalchemy import bindparam +from sqlalchemy import Connection +from sqlalchemy import JSON +from sqlalchemy import text +from sqlalchemy.engine import Engine + +from rememberstack.core.selection_references import card_from_payload +from rememberstack.core.selection_references import card_payload +from rememberstack.core.selection_references import CardDiagnostic +from rememberstack.core.selection_references import GroundedCard +from rememberstack.model import ForgetInProgressError +from rememberstack.model import SelectionResponse +from rememberstack.spine.admission import active_forget_id_on + + +@dataclass(frozen=True) +class FrozenSelection: + """The committed response and grounded cards for one source occurrence.""" + + chunk_id: UUID + input_hash: str + selection: SelectionResponse + cards: tuple[GroundedCard, ...] + diagnostics: tuple[CardDiagnostic, ...] + truncated: bool + + +def require_extraction_sources_on( + *, connection: Connection, deployment_id: UUID, chunk_ids: tuple[UUID, ...] +) -> None: + """Fence late publication against forget and require every source to survive.""" + connection.execute( + text("SELECT pg_advisory_xact_lock_shared(hashtextextended(:key,0))"), + {"key": f"hard-forget:{deployment_id}"}, + ) + if ( + active_forget_id_on(connection=connection, deployment_id=deployment_id) + is not None + ): + raise ForgetInProgressError("extraction publication is fenced by hard forget") + present = set( + connection.execute( + text(""" + SELECT c.chunk_id FROM chunks c JOIN documents d + ON d.deployment_id=c.deployment_id AND d.doc_id=c.doc_id + JOIN document_representations r ON r.representation_id=c.representation_id + WHERE c.deployment_id=:deployment_id + AND c.chunk_id=ANY(CAST(:chunk_ids AS uuid[])) AND d.deleted_at IS NULL + FOR SHARE OF d, r + """), + {"deployment_id": deployment_id, "chunk_ids": list(chunk_ids)}, + ).scalars() + ) + if present != set(chunk_ids): + raise LookupError("extraction source disappeared before publication") + + +class SelectionCatalog: + """One committed Selection result per chunk and extraction generation.""" + + def __init__(self, *, engine: Engine) -> None: + """Bind the source-result store to the deployment database.""" + self._engine = engine + + def load(self, *, chunk_id: UUID, extractor_version: str) -> FrozenSelection | None: + """Load the authoritative result, including an explicitly empty response.""" + with self._engine.connect() as connection: + row = ( + connection.execute( + text(""" + SELECT * FROM selection_results + WHERE chunk_id=:chunk_id AND extractor_version=:extractor_version + """), + {"chunk_id": chunk_id, "extractor_version": extractor_version}, + ) + .mappings() + .one_or_none() + ) + return None if row is None else _decode(row=dict(row)) + + def preceding( + self, *, chunk_ids: tuple[UUID, ...], extractor_version: str + ) -> dict[UUID, FrozenSelection]: + """Load a bounded known set; missing results remain missing, never empty.""" + with self._engine.connect() as connection: + rows = ( + connection.execute( + text(""" + SELECT * FROM selection_results + WHERE chunk_id=ANY(CAST(:chunk_ids AS uuid[])) + AND extractor_version=:extractor_version + """), + { + "chunk_ids": list(chunk_ids), + "extractor_version": extractor_version, + }, + ) + .mappings() + .all() + ) + results = tuple(_decode(row=dict(row)) for row in rows) + return {result.chunk_id: result for result in results} + + def prior( + self, + *, + deployment_id: UUID, + doc_id: UUID, + version_id: UUID, + input_hash: str, + extractor_version: str, + ) -> FrozenSelection | None: + """Reuse only an earlier version of this document with identical inputs.""" + with self._engine.connect() as connection: + row = ( + connection.execute( + text(""" + SELECT s.* FROM selection_results s JOIN chunks c + ON c.chunk_id=s.chunk_id AND c.deployment_id=s.deployment_id + JOIN document_versions v ON v.version_id=c.version_id + WHERE s.deployment_id=:deployment_id AND c.doc_id=:doc_id + AND s.selection_input_hash=:input_hash + AND s.extractor_version=:extractor_version + AND v.version_no < (SELECT version_no FROM document_versions + WHERE version_id=:version_id) + ORDER BY v.version_no DESC,c.ordinal LIMIT 1 + """), + { + "deployment_id": deployment_id, + "doc_id": doc_id, + "version_id": version_id, + "input_hash": input_hash, + "extractor_version": extractor_version, + }, + ) + .mappings() + .one_or_none() + ) + return None if row is None else _decode(row=dict(row)) + + def freeze( + self, + *, + deployment_id: UUID, + representation_id: UUID, + chunk_id: UUID, + extractor_version: str, + input_hash: str, + selection: SelectionResponse, + cards: tuple[GroundedCard, ...], + diagnostics: tuple[CardDiagnostic, ...], + truncated: bool, + reused_from: UUID | None = None, + ) -> FrozenSelection: + """Publish once under forget coordination; concurrent losers read the winner.""" + payload = { + "selection": selection.model_dump(mode="json"), + "diagnostics": [ + {"ordinal": d.ordinal, "gate": d.gate, "detail": d.detail} + for d in diagnostics + ], + } + with self._engine.begin() as connection: + require_extraction_sources_on( + connection=connection, + deployment_id=deployment_id, + chunk_ids=(chunk_id,) + if reused_from is None + else (chunk_id, reused_from), + ) + connection.execute( + _INSERT, + { + "deployment_id": deployment_id, + "representation_id": representation_id, + "chunk_id": chunk_id, + "extractor_version": extractor_version, + "input_hash": input_hash, + "output": payload, + "cards": [card_payload(card=card) for card in cards], + "truncated": truncated, + }, + ) + row = ( + connection.execute( + text(""" + SELECT * FROM selection_results WHERE deployment_id=:deployment_id + AND chunk_id=:chunk_id AND extractor_version=:extractor_version + """), + { + "deployment_id": deployment_id, + "chunk_id": chunk_id, + "extractor_version": extractor_version, + }, + ) + .mappings() + .one() + ) + result = _decode(row=dict(row)) + if result.input_hash != input_hash: + raise ValueError("committed Selection input identity differs") + return result + + +def _decode(*, row: dict[str, object]) -> FrozenSelection: + """Validate persisted values before they can become another model's input.""" + output = row["output"] + cards = row["cards"] + if not isinstance(output, dict) or not isinstance(cards, list): + raise ValueError("invalid frozen Selection payload") + diagnostics = output.get("diagnostics", []) + if not isinstance(diagnostics, list): + raise ValueError("invalid frozen Selection diagnostics") + return FrozenSelection( + chunk_id=UUID(str(row["chunk_id"])), + input_hash=str(row["selection_input_hash"]), + selection=SelectionResponse.model_validate(output["selection"]), + cards=tuple(card_from_payload(payload=card) for card in cards), + diagnostics=tuple( + CardDiagnostic( + ordinal=int(d["ordinal"]), gate=str(d["gate"]), detail=str(d["detail"]) + ) + for d in diagnostics + ), + truncated=bool(row["truncated"]), + ) + + +_INSERT = text(""" + INSERT INTO selection_results + (deployment_id,chunk_id,representation_id,extractor_version,selection_input_hash,output,cards,truncated) + VALUES (:deployment_id,:chunk_id,:representation_id,:extractor_version,:input_hash,:output,:cards,:truncated) + ON CONFLICT (deployment_id,chunk_id,extractor_version) DO NOTHING +""").bindparams(bindparam("output", type_=JSON), bindparam("cards", type_=JSON)) diff --git a/src/rememberstack/spine/work_ledger.py b/src/rememberstack/spine/work_ledger.py index 479b82f58..37c4bb0b0 100644 --- a/src/rememberstack/spine/work_ledger.py +++ b/src/rememberstack/spine/work_ledger.py @@ -252,6 +252,83 @@ def complete( enqueue_on(connection=connection, work=work) for work in follow_up ) + def complete_chunk_selection( + self, + *, + processing_id: UUID, + barrier: object, + follow_up: tuple[EnqueueWork, ...] = (), + ) -> tuple[EnqueueOutcome, ...]: + """Complete Selection and atomically open Claimify after all results exist.""" + from rememberstack.model import ProcessingTarget + from rememberstack.spine.selection_catalog import require_extraction_sources_on + from rememberstack.workers.base import SelectionChunkBarrier + + if not isinstance(barrier, SelectionChunkBarrier): + raise TypeError("barrier must be SelectionChunkBarrier") + for work in follow_up: + _require_valid_lane(stage=work.stage, lane=work.lane) + with self._engine.begin() as connection: + chunk_id = connection.execute( + _SELECT_TARGET_ID, {"processing_id": processing_id} + ).scalar_one() + require_extraction_sources_on( + connection=connection, + deployment_id=barrier.deployment_id, + chunk_ids=(chunk_id,), + ) + connection.execute( + _ADVISORY_LOCK_REPRESENTATION, + {"representation_id": barrier.representation_id}, + ) + if ( + connection.execute(_COMPLETE, {"processing_id": processing_id}).rowcount + == 0 + ): + raise WorkNotRunningError("Selection work is no longer running") + outcomes = [ + enqueue_on(connection=connection, work=work) for work in follow_up + ] + params = { + "deployment_id": barrier.deployment_id, + "representation_id": barrier.representation_id, + "chunker_version": barrier.chunker_version, + "extractor_version": barrier.extractor_version, + } + missing = connection.execute( + _SELECTION_BARRIER_MISSING, params + ).scalar_one() + if missing: + return tuple(outcomes) + chunk_ids = connection.execute( + text(""" + SELECT chunk_id FROM chunks WHERE representation_id=:representation_id + AND chunker_version=:chunker_version ORDER BY ordinal + """), + params, + ).scalars() + for target_id in chunk_ids: + outcomes.append( + enqueue_on( + connection=connection, + work=EnqueueWork( + deployment_id=barrier.deployment_id, + target_kind=ProcessingTarget.CHUNK, + target_id=target_id, + stage=PipelineStage.GROUND_CLAIMS, + component_version=barrier.extractor_version, + content_hash=barrier.content_hash, + lane=barrier.lane, + payload={ + "version_id": str(barrier.version_id), + "representation_id": str(barrier.representation_id), + "chunk_id": str(target_id), + }, + ), + ) + ) + return tuple(outcomes) + def complete_chunk_extract( self, *, @@ -262,7 +339,7 @@ def complete_chunk_extract( """D84: mark one chunk extract succeeded and maybe enqueue normalize. After this row is succeeded in the same transaction, require every chunk - of the representation to have a succeeded extract_claims row at the + of the representation to have a succeeded ground_claims row at the extractor version **and** claim/decision/occurrence extract evidence. Only then enqueue version-level ``normalize_relations`` (idempotent). """ @@ -922,7 +999,7 @@ def _extract_barrier_ready( "representation_id": representation_id, "chunker_version": chunker_version, "extractor_version": extractor_version, - "stage": PipelineStage.EXTRACT_CLAIMS.value, + "stage": PipelineStage.GROUND_CLAIMS.value, }, ).scalar_one() return int(ready) == int(expected) @@ -1832,6 +1909,7 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: AND p.status = 'succeeded' WHERE c.representation_id = :representation_id AND c.chunker_version = :chunker_version + AND c.claimify_input_hash IS NOT NULL AND ( EXISTS ( SELECT 1 FROM claims cl @@ -1967,3 +2045,19 @@ def _claimed_work(*, row: RowMapping) -> ClaimedWork: AND u.normalizer_version = :normalizer_version """ ) + + +_SELECTION_BARRIER_MISSING = text(""" + SELECT EXISTS( + SELECT 1 FROM chunks c + WHERE c.representation_id=:representation_id AND c.chunker_version=:chunker_version + AND (NOT EXISTS(SELECT 1 FROM selection_results s + WHERE s.deployment_id=:deployment_id AND s.chunk_id=c.chunk_id + AND s.extractor_version=:extractor_version + AND s.selection_input_hash=c.extraction_input_hash) + OR NOT EXISTS(SELECT 1 FROM processing_state p + WHERE p.deployment_id=:deployment_id AND p.target_kind='chunk' + AND p.target_id=c.chunk_id AND p.stage='extract_claims' + AND p.component_version=:extractor_version AND p.status='succeeded')) + ) +""") diff --git a/src/rememberstack/workers/base.py b/src/rememberstack/workers/base.py index 4a0d35295..b21101c3e 100644 --- a/src/rememberstack/workers/base.py +++ b/src/rememberstack/workers/base.py @@ -61,6 +61,10 @@ class ExtractChunkBarrier(BaseModel): normalize_component_version: str +class SelectionChunkBarrier(ExtractChunkBarrier): + """Complete Selection before any chunk consumes the shared source references.""" + + class ClaimNormalizeBarrier(BaseModel): """D88: after a claim normalize succeeds, complete+barrier in one ledger txn.""" @@ -119,6 +123,7 @@ class HandlerOutcome(BaseModel): model_config = ConfigDict(frozen=True, extra="forbid") follow_up: tuple[EnqueueWork, ...] = () + selection_chunk_barrier: SelectionChunkBarrier | None = None extract_chunk_barrier: ExtractChunkBarrier | None = None claim_normalize_barrier: ClaimNormalizeBarrier | None = None entity_obs_flush_barrier: EntityObsFlushBarrier | None = None @@ -378,7 +383,13 @@ def run_one( return RunResult( processing_id=claimed.processing_id, outcome=result_outcome ) - if outcome.extract_chunk_barrier is not None: + if outcome.selection_chunk_barrier is not None: + self._ledger.complete_chunk_selection( + processing_id=claimed.processing_id, + barrier=outcome.selection_chunk_barrier, + follow_up=outcome.follow_up, + ) + elif outcome.extract_chunk_barrier is not None: self._ledger.complete_chunk_extract( processing_id=claimed.processing_id, barrier=outcome.extract_chunk_barrier, diff --git a/src/rememberstack/workers/e3.py b/src/rememberstack/workers/e3.py index 39676aad5..65c2c08f9 100644 --- a/src/rememberstack/workers/e3.py +++ b/src/rememberstack/workers/e3.py @@ -133,8 +133,10 @@ def _run_profile_refresh(*, action: Callable[[], object], call_key: str) -> None unqualified win. CONTEXT REFERENCES -For each assertion, list up to four other named entities the claim itself -refers to, besides the subject and besides a relation's object. These help +For each assertion, list up to four other identifiable people, organizations, +works or particular events explicitly discussed in the claim, besides the +subject and a relation's object. A particular event may have a descriptive +name, such as "Nate's May tournament"; do not invent an official name. These help later matching; they do not change who the assertion is about. "Joanna said Nate won Tournament A" stays an observation about Joanna; Nate and Tournament A are context. Equal names can still be different people or diff --git a/src/tests/core/test_concise_adjudication.py b/src/tests/core/test_concise_adjudication.py index 98c950be6..b7bbeb760 100644 --- a/src/tests/core/test_concise_adjudication.py +++ b/src/tests/core/test_concise_adjudication.py @@ -1080,3 +1080,28 @@ def test_prompt_schema_rejects_duplicate_window_replacement() -> None: "rationale": "Two replacements.", } ) + + +def test_resolved_context_has_readable_names_aliases_and_source_claim() -> None: + """Context is linked to its assertion's testimony, not an opaque UUID list.""" + snapshot = _snapshot(context_truncated=True) + assertion = snapshot["assertions"][0] + assertion["context_entities"] = [ + { + "entity_id": _OBJECT_ALIAS, + "name": "the May tournament", + "canonical_entity_id": _OBJECT, + "canonical_name": "Riverside Cup", + } + ] + assertion["assertion"]["context_refs"] = [{"name": "unresolved discarded hint"}] + presentation, mapping = project_concise_inputs(snapshot=snapshot) + item = presentation["assertions"][0] + entities = {entity["handle"]: entity for entity in presentation["entities"]} + alias = entities[item["context"][0]] + assert alias["name"] == "the May tournament" + assert entities[alias["same_as"]]["name"] == "Riverside Cup" + assert item["claim"] in mapping.claims + assert "context_refs" not in item["content"] + assert presentation["context_truncated"] is True + assert str(_OBJECT) not in canonical_json(presentation) diff --git a/src/tests/profiles/test_selfhost_profile.py b/src/tests/profiles/test_selfhost_profile.py index fd6131333..855a0735f 100644 --- a/src/tests/profiles/test_selfhost_profile.py +++ b/src/tests/profiles/test_selfhost_profile.py @@ -68,6 +68,7 @@ def test_selfhost_composes_every_implemented_continuous_route() -> None: PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, PipelineStage.NORMALIZE_RELATIONS, PipelineStage.ADJUDICATE_OBSERVATIONS, PipelineStage.ADJUDICATE_SUPERSESSION, @@ -81,7 +82,6 @@ def test_selfhost_composes_every_implemented_continuous_route() -> None: def test_enum_only_and_fused_stages_are_not_advertised_as_workers() -> None: """A stage enum is not proof that an independently runnable handler exists.""" assert { - PipelineStage.GROUND_CLAIMS, PipelineStage.RESOLVE_ENTITIES, PipelineStage.EMBED_RELATION, PipelineStage.EMBED_OBSERVATION, diff --git a/src/tests/spine/test_d122_selection.py b/src/tests/spine/test_d122_selection.py new file mode 100644 index 000000000..312e89b4a --- /dev/null +++ b/src/tests/spine/test_d122_selection.py @@ -0,0 +1,216 @@ +"""Frozen Selection publication and representation-barrier PostgreSQL proofs.""" + +from pathlib import Path +from uuid import UUID + +import pytest +from sqlalchemy import text +from sqlalchemy.engine import Engine + +from rememberstack.core import chunker_version +from rememberstack.model import ClaimedWork +from rememberstack.model import PipelineStage +from rememberstack.model import ProcessingLane +from rememberstack.model import SelectionCandidate +from rememberstack.model import SelectionOutcome +from rememberstack.model import SelectionResponse +from rememberstack.spine import ChunkCatalog +from rememberstack.spine import WorkLedger +from rememberstack.spine import WorkLedgerSettings +from rememberstack.spine.selection_catalog import FrozenSelection +from rememberstack.spine.selection_catalog import SelectionCatalog +from rememberstack.workers.base import SelectionChunkBarrier +from rememberstack.workers.e1 import E2_EXTRACTOR_VERSION +from rememberstack.workers.e3 import E3_NORMALIZER_VERSION +from tests.workers.test_d119_versions import _bootstrap +from tests.workers.test_d119_versions import _DEPLOYMENT_ID +from tests.workers.test_d119_versions import _PARAMS +from tests.workers.test_d119_versions import _VersionRig +from tests.workers.test_d119_versions import database_engine as database_engine + +_PRE_SELECTION = ( + PipelineStage.CONVERT, + PipelineStage.STRUCTURE, + PipelineStage.CHUNK, + PipelineStage.EMBED_CHUNK, +) + + +def _prepare(*, engine: Engine, root: Path) -> _VersionRig: + """Build real source chunks while leaving their Selection work pending.""" + _bootstrap(engine) + rig = _VersionRig(engine=engine, root=root) + rig.observe(extra="x") + rig.drain(stages=_PRE_SELECTION) + return rig + + +def _freeze( + *, engine: Engine, chunk_id: UUID, selection: SelectionResponse +) -> FrozenSelection: + """Persist one response against the actual chunk's source identity.""" + with engine.connect() as connection: + row = ( + connection.execute( + text("SELECT * FROM chunks WHERE chunk_id=:id"), {"id": chunk_id} + ) + .mappings() + .one() + ) + return SelectionCatalog(engine=engine).freeze( + deployment_id=_DEPLOYMENT_ID, + representation_id=row["representation_id"], + chunk_id=chunk_id, + extractor_version=E2_EXTRACTOR_VERSION, + input_hash=row["extraction_input_hash"], + selection=selection, + cards=(), + diagnostics=(), + truncated=False, + ) + + +def test_committed_empty_selection_wins_over_a_later_answer( + database_engine: Engine, tmp_path: Path +) -> None: + """A retry cannot replace a real zero-output result with another inference.""" + _prepare(engine=database_engine, root=tmp_path) + with database_engine.connect() as connection: + chunk_id = connection.execute( + text("SELECT chunk_id FROM chunks ORDER BY ordinal LIMIT 1") + ).scalar_one() + first = _freeze( + engine=database_engine, + chunk_id=chunk_id, + selection=SelectionResponse(candidates=()), + ) + second = _freeze( + engine=database_engine, + chunk_id=chunk_id, + selection=SelectionResponse( + candidates=( + SelectionCandidate(source_span="x", outcome=SelectionOutcome.KEEP), + ) + ), + ) + assert second == first + assert ( + SelectionCatalog(engine=database_engine).load( + chunk_id=chunk_id, extractor_version=E2_EXTRACTOR_VERSION + ) + == first + ) + + +def test_no_claimify_work_before_every_selection_is_committed_and_succeeded( + database_engine: Engine, tmp_path: Path +) -> None: + """Worker completion order cannot expose a partial document reference set.""" + _prepare(engine=database_engine, root=tmp_path) + ledger = WorkLedger(engine=database_engine, settings=WorkLedgerSettings()) + work = [] + while True: + claimed = ledger.claim_one( + deployment_id=_DEPLOYMENT_ID, + stage=PipelineStage.EXTRACT_CLAIMS, + lane=ProcessingLane.STEADY, + ) + if claimed is None: + break + assert isinstance(claimed, ClaimedWork) + work.append(claimed) + assert len(work) >= 2 + for index, claimed in enumerate(reversed(work)): + # A freshly composed catalog sees committed empty responses after a restart. + _freeze( + engine=database_engine, + chunk_id=claimed.target_id, + selection=SelectionResponse(candidates=()), + ) + barrier = SelectionChunkBarrier( + deployment_id=claimed.deployment_id, + version_id=UUID(str(claimed.payload["version_id"])), + representation_id=UUID(str(claimed.payload["representation_id"])), + chunker_version=chunker_version(params=_PARAMS), + extractor_version=E2_EXTRACTOR_VERSION, + content_hash=claimed.content_hash, + lane=claimed.lane, + normalize_component_version=E3_NORMALIZER_VERSION, + ) + ledger.complete_chunk_selection( + processing_id=claimed.processing_id, barrier=barrier + ) + with database_engine.connect() as connection: + count = connection.execute( + text( + "SELECT count(*) FROM processing_state WHERE stage='ground_claims'" + ) + ).scalar_one() + normalized = connection.execute( + text( + "SELECT count(*) FROM processing_state WHERE stage='normalize_relations'" + ) + ).scalar_one() + assert count == (len(work) if index == len(work) - 1 else 0) + assert normalized == 0 + + +def test_late_selection_cannot_republish_a_removed_source( + database_engine: Engine, tmp_path: Path +) -> None: + """A response arriving after source removal cannot restore erased payloads.""" + _prepare(engine=database_engine, root=tmp_path) + with database_engine.begin() as connection: + row = ( + connection.execute(text("SELECT * FROM chunks ORDER BY ordinal LIMIT 1")) + .mappings() + .one() + ) + connection.execute( + text("DELETE FROM chunks WHERE chunk_id=:id"), {"id": row["chunk_id"]} + ) + with pytest.raises(LookupError, match="source disappeared"): + SelectionCatalog(engine=database_engine).freeze( + deployment_id=_DEPLOYMENT_ID, + representation_id=row["representation_id"], + chunk_id=row["chunk_id"], + extractor_version=E2_EXTRACTOR_VERSION, + input_hash=row["extraction_input_hash"], + selection=SelectionResponse(candidates=()), + cards=(), + diagnostics=(), + truncated=False, + ) + with database_engine.connect() as connection: + assert ( + connection.execute( + text("SELECT count(*) FROM selection_results") + ).scalar_one() + == 0 + ) + + +def test_reference_window_is_bounded_and_keeps_cross_section_producers( + database_engine: Engine, tmp_path: Path +) -> None: + """The reference loader includes earlier sections, unlike the local bundle.""" + _prepare(engine=database_engine, root=tmp_path) + with database_engine.connect() as connection: + row = ( + connection.execute( + text("SELECT * FROM chunks ORDER BY ordinal DESC LIMIT 1") + ) + .mappings() + .one() + ) + catalog = ChunkCatalog(engine=database_engine) + chunks = catalog.chunks_for_references( + representation_id=row["representation_id"], + chunker_version=chunker_version(params=_PARAMS), + chunk_id=row["chunk_id"], + ) + assert len(chunks) >= 2 + assert len({chunk.section_path for chunk in chunks}) >= 2 + assert all( + row["ordinal"] - 9 <= chunk.ordinal <= row["ordinal"] + 1 for chunk in chunks + ) diff --git a/src/tests/spine/test_d123_context_nomination.py b/src/tests/spine/test_d123_context_nomination.py index 46d0b535f..e7647b3f8 100644 --- a/src/tests/spine/test_d123_context_nomination.py +++ b/src/tests/spine/test_d123_context_nomination.py @@ -254,3 +254,36 @@ def test_context_extra_does_not_displace_baseline_targets( assert win in fact_ids assert len(fact_ids) <= 28 assert len(fact_ids) >= 20 + + +def test_context_names_are_frozen_and_invalidate_a_prepared_presentation( + database_engine: Engine, +) -> None: + """A changed context name cannot leave an old model presentation applicable.""" + from rememberstack.core.concise_adjudication import project_concise_inputs + from rememberstack.spine.fact_applications import snapshot_hash + + case = WriterCase(engine=database_engine) + tournament = _tournament(engine=database_engine, case=case) + _, app = case.stage(day=10, context_entities=(tournament,)) + before = _snapshot(engine=database_engine, case=case, app=app) + presentation, mapping = project_concise_inputs(snapshot=before) + names = { + entity["handle"]: entity.get("name") for entity in presentation["entities"] + } + incoming = next( + item + for item in presentation["assertions"] + if item["handle"] == mapping.incoming_assertion + ) + assert names[incoming["context"][0]] == "Riverside Cup" + assert incoming["claim"] in mapping.claims + with database_engine.begin() as connection: + connection.execute( + text( + "UPDATE entities SET canonical_name='Riverside May Cup' WHERE entity_id=:id" + ), + {"id": tournament}, + ) + after = _snapshot(engine=database_engine, case=case, app=app) + assert snapshot_hash(snapshot=before) != snapshot_hash(snapshot=after) diff --git a/src/tests/workers/test_d119_versions.py b/src/tests/workers/test_d119_versions.py index fcb786a94..fae6e13dd 100644 --- a/src/tests/workers/test_d119_versions.py +++ b/src/tests/workers/test_d119_versions.py @@ -83,6 +83,7 @@ PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, ) _E3_STAGES = ( PipelineStage.NORMALIZE_RELATIONS, @@ -94,9 +95,17 @@ _TARGET_PATTERN = re.compile(r"TARGET CHUNK:\n(.+)", re.S) -def _document(*, extra: str, notes: str = _NOTES) -> str: - """Two-section source: changing appendix, stable notes body.""" - return f"# Appendix\n\n{extra}\n\n# Notes\n\n{notes}\n" +def _document(*, extra: str, notes: str = _NOTES, shift_origin: bool = False) -> str: + """Keep version edits outside the bounded preceding reference dependencies.""" + if shift_origin: + # Ten source chunks isolate the offset-changing prefix from the target's + # preceding eight Selection producers and their possible neighbors. + buffers = "".join( + f"# Buffer {index}\n\nStable background paragraph number {index}.\n\n" + for index in range(10) + ) + return f"# Appendix\n\n{extra}\n\n{buffers}# Notes\n\n{notes}\n" + return f"# Notes\n\n{notes}\n\n# Appendix\n\n{extra}\n" def _route(prompt: str, type_name: str) -> dict[str, object]: @@ -104,8 +113,10 @@ def _route(prompt: str, type_name: str) -> dict[str, object]: if type_name == "FallbackStructureResponse": return { "sections": [ - {"anchor": "Appendix", "occurrence_index": 0}, - {"anchor": "Notes", "occurrence_index": 0}, + {"anchor": heading, "occurrence_index": 0} + for heading in re.findall( + r"(?m)^# (Appendix|Notes|Buffer \d+)\s*$", prompt + ) ] } if type_name == "RootSummaryPlacementResponse": @@ -247,9 +258,12 @@ def database_engine() -> Iterator[Engine]: class _VersionRig: """E0–E3 chain with a living ingest path and a failing unexpected-extract flag.""" - def __init__(self, *, engine: Engine, root: Path) -> None: + def __init__( + self, *, engine: Engine, root: Path, shift_origin: bool = False + ) -> None: """Compose catalogs, fake provider, and registered handlers.""" self.engine = engine + self.shift_origin = shift_origin raw_store = LocalFSObjectStore(root=root / "raw") artifact_store = LocalFSObjectStore(root=root / "artifacts") self.provider = FakeModelProvider(generate_router=_route) @@ -324,6 +338,10 @@ def __init__(self, *, engine: Engine, root: Path) -> None: chunker_version=chunker_version(params=_PARAMS), ), ) + registry.register( + stage=PipelineStage.GROUND_CLAIMS, + handler=registry.handler_for(stage=PipelineStage.EXTRACT_CLAIMS), + ) registry.register( stage=PipelineStage.NORMALIZE_RELATIONS, handler=NormalizeRelationsHandler( @@ -411,7 +429,9 @@ def observe(self, *, extra: str, notes: str = _NOTES) -> None: upload=DocumentUpload( filename="d119.md", mime="text/markdown", - content=_document(extra=extra, notes=notes).encode("utf-8"), + content=_document( + extra=extra, notes=notes, shift_origin=self.shift_origin + ).encode("utf-8"), ), versioning_mode="living", source_modified_at=None, @@ -473,13 +493,13 @@ def test_envelope_origin_spans_match_identified_chunk_after_reuse( ) -> None: """After an offset shift, API spans still belong to the origin chunk.""" _bootstrap(database_engine) - rig = _VersionRig(engine=database_engine, root=tmp_path) + rig = _VersionRig(engine=database_engine, root=tmp_path, shift_origin=True) rig.observe(extra="x") rig.drain(stages=_E2_STAGES + _E3_STAGES) rig.observe(extra="xx") rig.drain(stages=_E2_STAGES) - origin_md = _document(extra="x") - shifted_md = _document(extra="xx") + origin_md = _document(extra="x", shift_origin=True) + shifted_md = _document(extra="xx", shift_origin=True) with database_engine.connect() as connection: claim = ( connection.execute( From 06191ae1733c2ccdad0ee0a3c03f75eaabb81a91 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 14:51:59 +0200 Subject: [PATCH 07/14] fix(extraction): validate cited context and wait for Claimify completion --- .github/ci/integration-paths.txt | 1 + ...123_document_reference_context_20260914.md | 35 ++++ src/rememberstack/spine/lifecycle.py | 2 +- src/rememberstack/spine/readiness.py | 22 ++- src/rememberstack/workers/e1.py | 2 +- src/rememberstack/workers/e2.py | 39 ++-- .../workers/extraction_references.py | 8 +- src/tests/spine/test_d122_e2.py | 178 ++++++++++++++++++ src/tests/spine/test_pipeline_readiness.py | 66 +++++++ src/tests/workers/test_d119_versions.py | 22 ++- .../src/app/docs/ingestion/pipeline/page.mdx | 27 ++- website/src/app/docs/project-status/page.mdx | 1 + 12 files changed, 371 insertions(+), 32 deletions(-) create mode 100644 src/tests/spine/test_d122_e2.py diff --git a/.github/ci/integration-paths.txt b/.github/ci/integration-paths.txt index a9a4f6ee8..f81c586e3 100644 --- a/.github/ci/integration-paths.txt +++ b/.github/ci/integration-paths.txt @@ -60,3 +60,4 @@ src/tests/spine/test_d119_multi_span.py src/tests/spine/test_d119_migration.py src/tests/workers/test_d119_versions.py src/tests/spine/test_d122_selection.py +src/tests/spine/test_d122_e2.py diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md index 6286003d2..fa2225181 100644 --- a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -150,3 +150,38 @@ The user authorized re-processing conv-42 with Gemma on Vertex after all three PRs land. Parent must verify every processing-stage binding before those calls, then report processing cost, latency and source-linked claim/fact quality. Answering/judging remain outside that run. + +## Integrated runtime review and acceptance + +The E2 split is now implemented. Parent review removed duplicate target-owned +cards from the earlier-reference set and duplicate rendered evidence. Citation +labels are assigned before enforcing the actual 4,096-character card limit; +only admitted cards enter the grounding catalog. An added name/date from earlier +context must cite that source passage: another admitted but uncited card cannot +supply its grounding tokens. + +Readiness now derives both Selection and Claimify status from their chunk work. +Connector-cycle finalization also waits for Claimify; Selection success alone +cannot publish a ready pipeline or finalize a still-processing source cycle. +The extractor generation rolls with these prompt and scheduling changes. + +Completed parent checks on the integrated working tree: + +- Five PostgreSQL Selection/barrier/remapping tests passed (80.13 seconds). +- Three actual E0–E2 cross-section tests passed (52.78 seconds): chunk-2 event and + source alias used in chunk 7; same-date distinct tournament contexts retained; + attribution and two exact source ranges preserved; omitted earlier citation + rejected; changed zero-card producer invalidates Claimify while target + Selection is reused. These are canned-model mechanics proofs, not measured + coreference quality. +- Sixteen readiness tests passed (42.90 seconds), including Selection succeeded + with Claimify pending, then Claimify succeeded. +- The additional contextual-name snapshot test passed (12.47 seconds): changing + a resolved name invalidates the prepared model presentation. +- Changed runtime and new acceptance test files passed Pyright and Ruff. + +The full actual 500-version test is running against the integrated runtime. +Existing worker fixtures and Full-v31 benchmark pins are being updated in +bounded Grok tasks. Final Antigravity review, exact-head CI, main rebase and +parent merge review remain outstanding. No live processing quality/cost result +is claimed before the authorized Gemma/Vertex conv-42 run. diff --git a/src/rememberstack/spine/lifecycle.py b/src/rememberstack/spine/lifecycle.py index b2d819a1d..3c681c098 100644 --- a/src/rememberstack/spine/lifecycle.py +++ b/src/rememberstack/spine/lifecycle.py @@ -1092,7 +1092,7 @@ def _record_adjudication( ON w.deployment_id = y.deployment_id AND w.target_kind = 'chunk' AND w.target_id = c.chunk_id - AND w.stage = 'extract_claims' + AND w.stage IN ('extract_claims', 'ground_claims') WHERE v.sync_cycle_id = y.cycle_id AND w.status IN ('pending', 'running', 'failed', 'dead_letter') ) diff --git a/src/rememberstack/spine/readiness.py b/src/rememberstack/spine/readiness.py index 30e943f5f..d911cede4 100644 --- a/src/rememberstack/spine/readiness.py +++ b/src/rememberstack/spine/readiness.py @@ -109,16 +109,22 @@ def inspect( .mappings() .all() ) - extract_rows = () - if extract_version is not None and chunk_version is not None: - extract_rows = ( + extract_rows = [] + for stage, component_version in self._expected: + if stage not in ( + PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, + ): + continue + extract_rows.extend( connection.execute( _EXTRACT_CHUNK_STATUS, { "deployment_id": deployment_id, "version_ids": version_ids, - "extractor_version": extract_version, + "extractor_version": component_version, "chunker_version": chunk_version, + "extraction_stage": stage.value, }, ) .mappings() @@ -199,7 +205,7 @@ def inspect( for row in extract_rows: key = ( UUID(str(row["target_id"])), - PipelineStage.EXTRACT_CLAIMS, + PipelineStage(str(row["stage"])), str(row["component_version"]), ) by_key[key] = row @@ -534,7 +540,7 @@ def _live_graph_status( pass -# D84: extract_claims primary rows target chunks; derive a version-level status +# D84/D122: Selection and Claimify target chunks; derive their version status # for the version's current representation only. _EXTRACT_CHUNK_STATUS = text( """ @@ -556,7 +562,7 @@ def _live_graph_status( END AS finished_at FROM ( SELECT v.version_id AS target_id, - 'extract_claims'::text AS stage, + CAST(:extraction_stage AS text) AS stage, :extractor_version AS component_version, CASE -- No current representation at all: convert/structure have not @@ -613,7 +619,7 @@ def _live_graph_status( ON p.deployment_id = :deployment_id AND p.target_kind = 'chunk' AND p.target_id = c.chunk_id - AND p.stage = 'extract_claims' + AND p.stage = :extraction_stage AND p.component_version = :extractor_version LEFT JOIN processing_state embed ON embed.deployment_id = :deployment_id diff --git a/src/rememberstack/workers/e1.py b/src/rememberstack/workers/e1.py index 33d31190e..ea64808de 100644 --- a/src/rememberstack/workers/e1.py +++ b/src/rememberstack/workers/e1.py @@ -64,7 +64,7 @@ E2_EXTRACTOR_VERSION: Final = ( f"e2-extract-2026.09:d119-multi-span-1:d80-location-elements-1:" f"token-union-grounding-1:temporal-anchor-4:d107-kind-vocabulary-1:" - f"{SECTION_ORIENTATION_VERSION}:assertion-clarity-4" + f"{SECTION_ORIENTATION_VERSION}:assertion-clarity-4:d122-source-references-1" ) """Extractor generation in extraction_input_hash (D56). d119-multi-span-1: coherent claims cite engine-labeled source passages; occurrence rows store diff --git a/src/rememberstack/workers/e2.py b/src/rememberstack/workers/e2.py index 6e1fd39ce..51ec673a0 100644 --- a/src/rememberstack/workers/e2.py +++ b/src/rememberstack/workers/e2.py @@ -91,7 +91,6 @@ from rememberstack.workers.e1 import E2_EXTRACTOR_VERSION from rememberstack.workers.e3 import E3_NORMALIZER_VERSION from rememberstack.workers.extraction_references import attach_card_passages -from rememberstack.workers.extraction_references import card_passage_texts from rememberstack.workers.extraction_references import collect_eligible_cards from rememberstack.workers.extraction_references import MissingSelectionError from rememberstack.workers.extraction_references import preceding_producer_ids @@ -785,12 +784,6 @@ def _claimify_chunk( for keep in keeps ) kept_ranges = tuple(span for span in keep_ranges if span is not None) - eligible = collect_eligible_cards(target=target_frozen, preceding=preceding) - fitted, claimify_truncated = rank_and_fit_cards( - cards=eligible, - target_text=document_md[chunk.char_start : chunk.char_end], - target_ordinal=chunk.ordinal, - ) previous, following = same_section_neighbours(chunks=chunks, index=index) catalog = build_passage_catalog( blocks=_load_blocks( @@ -803,13 +796,30 @@ def _claimify_chunk( following=following, kept_ranges=kept_ranges, ) - catalog, fitted = attach_card_passages(catalog=catalog, cards=fitted) + local_catalog = catalog + eligible = collect_eligible_cards(preceding=preceding) + catalog, relabeled = attach_card_passages(catalog=catalog, cards=eligible) + fitted, claimify_truncated = rank_and_fit_cards( + cards=relabeled, + target_text=document_md[chunk.char_start : chunk.char_end], + target_ordinal=chunk.ordinal, + ) + admitted_labels = { + passage.label for card in fitted for passage in card.passages + } + catalog = PassageCatalog( + passages=tuple( + passage + for passage in catalog.passages + if passage in local_catalog.passages + or passage.label in admitted_labels + ) + ) flagged_spans = { candidate.source_span for candidate in keeps if candidate.verdict is SelectionVerdict.KEEP_FLAGGED } - grounding_texts = card_passage_texts(cards=fitted) response_call = self._model_provider.generate( request=ModelRequest( model=self._settings.extract_model, @@ -822,7 +832,7 @@ def _claimify_chunk( document_md=document_md, ), passages=render_passage_catalog( - catalog=catalog, document_md=document_md + catalog=local_catalog, document_md=document_md ), cards=render_cards_for_claimify(cards=fitted), ), @@ -859,7 +869,12 @@ def _claimify_chunk( flagged_spans=flagged_spans, kept_ranges=kept_ranges, catalog=catalog, - card_passage_texts=grounding_texts, + card_passage_texts=tuple( + passage.text + for card in fitted + for passage in card.passages + if passage.label in candidate.source_refs + ), ) origin_range = _origin_range_for_accounting( result=result, candidate=candidate, catalog=catalog @@ -1390,7 +1405,7 @@ def _source_grounding_elements( Every member is source-derived: the target chunk slice, deterministic document header, same-section neighbours, validated D80 LocationElement - rows, and verbatim supporting passages of admitted reference cards. + rows, and verbatim supporting passages cited by this claim. Generated card names, free-form location headers, and section summaries are deliberately absent (D79/D80/D122). """ diff --git a/src/rememberstack/workers/extraction_references.py b/src/rememberstack/workers/extraction_references.py index 19af0b29c..96ceaa247 100644 --- a/src/rememberstack/workers/extraction_references.py +++ b/src/rememberstack/workers/extraction_references.py @@ -16,13 +16,13 @@ from rememberstack.core.selection_references import GroundedPassage from rememberstack.core.selection_references import PRECEDING_CHUNK_LIMIT from rememberstack.core.selection_references import remap_card -from rememberstack.core.source_passages import EvidenceSpan from rememberstack.core.source_passages import PassageCatalog from rememberstack.core.source_passages import PassageRegion from rememberstack.core.source_passages import remap_evidence_spans from rememberstack.core.source_passages import same_section_neighbours from rememberstack.core.source_passages import SourcePassage from rememberstack.core.source_passages import window_bounds +from rememberstack.model import EvidenceSpan from rememberstack.model.chunks import ChunkForEmbedding from rememberstack.spine.selection_catalog import FrozenSelection @@ -75,10 +75,10 @@ def require_frozen_producers( def collect_eligible_cards( - *, target: FrozenSelection, preceding: tuple[FrozenSelection, ...] + *, preceding: tuple[FrozenSelection, ...] ) -> tuple[GroundedCard, ...]: - """Target cards plus every previous-eight producer's published cards.""" - cards = list(target.cards) + """Every previous-eight producer's cards; the target already supplies local text.""" + cards: list[GroundedCard] = [] for frozen in preceding: cards.extend(frozen.cards) return tuple(cards) diff --git a/src/tests/spine/test_d122_e2.py b/src/tests/spine/test_d122_e2.py new file mode 100644 index 000000000..33c02d333 --- /dev/null +++ b/src/tests/spine/test_d122_e2.py @@ -0,0 +1,178 @@ +"""Actual two-stage extraction with distant source evidence and version reuse.""" + +from pathlib import Path +import re + +import pytest +from sqlalchemy import text +from sqlalchemy.engine import Engine + +from tests.workers.test_d119_versions import _bootstrap +from tests.workers.test_d119_versions import _E2_STAGES +from tests.workers.test_d119_versions import _route +from tests.workers.test_d119_versions import _VersionRig +from tests.workers.test_d119_versions import database_engine as database_engine + +_INTRO = "Nate entered the Riverside Cup, also called the River Open, on 2024-05-10." +_OTHER = "Nate entered the Hill Cup on 2024-05-10." +_TARGET = "Nate said he won the River Open." +_CLAIM = "Nate said he won the Riverside Cup on 2024-05-10." + + +def _document(*, changed: str = "Quiet background.", prefix: str = "Preface.") -> str: + """Put the introduction in chunk 2 and its dependent assertion in chunk 7.""" + bodies = (prefix, _INTRO, _OTHER, changed, "Local notes.", "More notes.", _TARGET) + return ( + "\n\n".join(f"# Part {i + 1}\n\n{body}" for i, body in enumerate(bodies)) + "\n" + ) + + +class _ReferenceRouter: + """Assert source-bearing inputs, then emit canned semantic decisions.""" + + def __init__(self, *, cite_support: bool = True) -> None: + """Optionally simulate an omitted evidence citation.""" + self.cite_support = cite_support + self.claimify_calls = 0 + self.target_selection_calls = 0 + + def __call__(self, prompt: str, type_name: str) -> dict[str, object]: + """Supply source-derived labels; no paid provider or inferred test oracle.""" + if type_name == "FallbackStructureResponse": + return { + "sections": [ + {"anchor": h, "occurrence_index": 0} + for h in re.findall(r"(?m)^# (Part \d+)\s*$", prompt) + ] + } + if type_name == "SelectionResponse": + target = prompt.split("TARGET CHUNK:\n", 1)[1] + refs: list[dict[str, object]] = [] + for body, name, aliases in ( + (_INTRO, "Riverside Cup", ["River Open"]), + (_OTHER, "Hill Cup", []), + ): + if body not in target: + continue + label = re.search(r"\[(S\d+)\] TARGET:\n" + re.escape(body), prompt) + assert label is not None + refs.append( + {"name": name, "aliases": aliases, "source_refs": [label.group(1)]} + ) + candidates = [] + if _TARGET in target: + self.target_selection_calls += 1 + candidates = [{"source_span": _TARGET, "outcome": "keep"}] + # No propositions may still publish a useful introduction. + return {"candidates": candidates, "references": refs} + if type_name == "ClaimifyResponse": + self.claimify_calls += 1 + assert "Riverside Cup also called River Open" in prompt + assert "Hill Cup" in prompt # Same date does not merge the two events. + origin = re.search( + r"\[(S\d+)\] TARGET \(origin-eligible\):\n" + re.escape(_TARGET), prompt + ) + support = re.search(r'(S\d+): "' + re.escape(_INTRO) + '"', prompt) + assert origin is not None and support is not None + assert ( + prompt.count(_INTRO) == 1 + ) # Cards do not duplicate their evidence block. + claim_refs = [origin.group(1)] + if self.cite_support: + claim_refs.append(support.group(1)) + return { + "claims": [ + { + "claim_text": _CLAIM, + "source_refs": claim_refs, + "is_attributed": True, + "added_context": [ + { + "text": "Riverside Cup on 2024-05-10", + "source_kind": "neighbour", + } + ], + "entailment_self_verdict": True, + } + ] + } + return _route(prompt, type_name) + + +@pytest.mark.parametrize("cite_support", (True, False)) +def test_chunk_two_reference_grounds_chunk_seven_only_when_cited( + database_engine: Engine, tmp_path: Path, cite_support: bool +) -> None: + """Distant aliases preserve attribution and both exact source ranges.""" + _bootstrap(database_engine) + router = _ReferenceRouter(cite_support=cite_support) + rig = _VersionRig(engine=database_engine, root=tmp_path, router=router) + document = _document() + rig.observe(extra="", markdown=document) + rig.drain(stages=_E2_STAGES) + assert router.claimify_calls == 1 + with database_engine.connect() as connection: + rows = ( + connection.execute( + text( + "SELECT c.claim_text,c.is_attributed,cc.evidence_spans FROM claims c JOIN chunk_claims cc ON cc.claim_id=c.claim_id AND cc.chunk_id=c.chunk_id" + ) + ) + .mappings() + .all() + ) + cards = ( + connection.execute( + text( + "SELECT jsonb_array_length(cards) FROM selection_results WHERE jsonb_array_length(cards)>0" + ) + ) + .scalars() + .all() + ) + assert cards == [1, 1] + if not cite_support: + assert rows == [] + assert ( + connection.execute( + text( + "SELECT count(*) FROM claim_extraction_decisions WHERE decision_type='grounding_rejected'" + ) + ).scalar_one() + == 1 + ) + return + assert len(rows) == 1 + assert rows[0]["claim_text"] == _CLAIM + assert rows[0]["is_attributed"] is True + spans = rows[0]["evidence_spans"] + assert [document[s["char_start"] : s["char_end"]] for s in spans] == [ + _TARGET, + _INTRO, + ] + + +def test_changed_zero_card_producer_rechecks_claimify_but_reuses_selection( + database_engine: Engine, tmp_path: Path +) -> None: + """A changed earlier input invalidates reuse even when its old card set was empty.""" + _bootstrap(database_engine) + router = _ReferenceRouter() + rig = _VersionRig(engine=database_engine, root=tmp_path, router=router) + rig.observe(extra="", markdown=_document()) + rig.drain(stages=_E2_STAGES) + rig.observe( + extra="", + markdown=_document(changed="A competing introduction could now appear here."), + ) + rig.drain(stages=_E2_STAGES) + assert router.target_selection_calls == 1 + assert router.claimify_calls == 2 + with database_engine.connect() as connection: + assert ( + connection.execute( + text("SELECT count(*) FROM claims WHERE claim_text=:claim"), + {"claim": _CLAIM}, + ).scalar_one() + == 2 + ) diff --git a/src/tests/spine/test_pipeline_readiness.py b/src/tests/spine/test_pipeline_readiness.py index 39656bb20..33d3c679c 100644 --- a/src/tests/spine/test_pipeline_readiness.py +++ b/src/tests/spine/test_pipeline_readiness.py @@ -742,3 +742,69 @@ def test_non_succeeded_extract_carries_no_finished_at( assert extract_status == "succeeded" assert finished_at is not None assert ready is True + + +def test_selection_success_does_not_hide_pending_claimify( + ready_rows: tuple[Engine, UUID], +) -> None: + """Both chunk stages report their real status; only grounded claims are ready.""" + engine, version_id = ready_rows + _seed_version_representation( + engine, version_id=version_id, chunker_version=_DEFAULT_CHUNKER_VERSION + ) + catalog = PipelineReadinessCatalog( + engine=engine, + expected_components={ + PipelineStage.EXTRACT_CLAIMS: _EXTRACTOR_VERSION, + PipelineStage.GROUND_CLAIMS: _EXTRACTOR_VERSION, + }, + projections=ProjectionCatalog(engine=engine), + ) + with engine.begin() as connection: + chunk_id = connection.execute( + text("SELECT chunk_id FROM chunks WHERE version_id=:v"), {"v": version_id} + ).scalar_one() + for stage, status in ( + ("extract_claims", "succeeded"), + ("ground_claims", "pending"), + ): + connection.execute( + text(""" + INSERT INTO processing_state + (processing_id,deployment_id,target_kind,target_id,stage, + component_version,content_hash,lane,status,attempts,finished_at) + VALUES (:id,:d,'chunk',:chunk,CAST(:stage AS pipeline_stage), + :component,'hash','steady',CAST(:status AS processing_status),1, + CASE WHEN :status='succeeded' THEN now() ELSE NULL END) + """), + { + "id": uuid4(), + "d": _DEPLOYMENT_ID, + "chunk": chunk_id, + "stage": stage, + "component": _EXTRACTOR_VERSION, + "status": status, + }, + ) + report = catalog.inspect( + deployment_id=_DEPLOYMENT_ID, version_ids=(version_id,), require=_requirements() + ) + assert report.ready is False + statuses = {stage.stage: stage.status for stage in report.versions[0].stages} + assert statuses[PipelineStage.EXTRACT_CLAIMS] == "succeeded" + assert statuses[PipelineStage.GROUND_CLAIMS] == "pending" + with engine.begin() as connection: + connection.execute( + text( + "UPDATE processing_state SET status='succeeded',finished_at=now() WHERE stage='ground_claims' AND target_id=:chunk" + ), + {"chunk": chunk_id}, + ) + assert ( + catalog.inspect( + deployment_id=_DEPLOYMENT_ID, + version_ids=(version_id,), + require=_requirements(), + ).ready + is True + ) diff --git a/src/tests/workers/test_d119_versions.py b/src/tests/workers/test_d119_versions.py index fae6e13dd..38b720c27 100644 --- a/src/tests/workers/test_d119_versions.py +++ b/src/tests/workers/test_d119_versions.py @@ -1,5 +1,6 @@ """Handler-level D119 500-version reuse: hashes, remapping, lineage fact recount.""" +from collections.abc import Callable from collections.abc import Iterator from pathlib import Path import re @@ -259,14 +260,19 @@ class _VersionRig: """E0–E3 chain with a living ingest path and a failing unexpected-extract flag.""" def __init__( - self, *, engine: Engine, root: Path, shift_origin: bool = False + self, + *, + engine: Engine, + root: Path, + shift_origin: bool = False, + router: Callable[[str, str], dict[str, object]] = _route, ) -> None: """Compose catalogs, fake provider, and registered handlers.""" self.engine = engine self.shift_origin = shift_origin raw_store = LocalFSObjectStore(root=root / "raw") artifact_store = LocalFSObjectStore(root=root / "artifacts") - self.provider = FakeModelProvider(generate_router=_route) + self.provider = FakeModelProvider(generate_router=router) document_catalog = DocumentCatalog(engine=engine) chunk_catalog = ChunkCatalog(engine=engine) claim_catalog = ClaimCatalog(engine=engine) @@ -420,7 +426,9 @@ def __init__( ) self.worker = Worker(ledger=ledger, registry=registry) - def observe(self, *, extra: str, notes: str = _NOTES) -> None: + def observe( + self, *, extra: str, notes: str = _NOTES, markdown: str | None = None + ) -> None: """One living observation of the two-section lineage.""" self.ingestor.ingest_observed( deployment_id=_DEPLOYMENT_ID, @@ -429,8 +437,12 @@ def observe(self, *, extra: str, notes: str = _NOTES) -> None: upload=DocumentUpload( filename="d119.md", mime="text/markdown", - content=_document( - extra=extra, notes=notes, shift_origin=self.shift_origin + content=( + markdown + if markdown is not None + else _document( + extra=extra, notes=notes, shift_origin=self.shift_origin + ) ).encode("utf-8"), ), versioning_mode="living", diff --git a/website/src/app/docs/ingestion/pipeline/page.mdx b/website/src/app/docs/ingestion/pipeline/page.mdx index df3941f41..9289a92a4 100644 --- a/website/src/app/docs/ingestion/pipeline/page.mdx +++ b/website/src/app/docs/ingestion/pipeline/page.mdx @@ -13,7 +13,9 @@ Exhaustive stage reference for the per-document evidence chain. Parent overview: ``` ingest → convert → structure → chunk → embed(chunks) ↓ - extract claims → embed(claims) + select propositions and source references + ↓ + ground claims → embed(claims) ↓ normalize / resolve entities ↓ @@ -119,6 +121,29 @@ Each claim carries: - Source-asserted validity interval when the source states one (`asserted` validity — testimony, not system verdict) - Extractor / representation / structure generation coordinates (basis) +Extraction has two model calls. **Selection** chooses propositions and identifies +source-backed people, organizations, works and particular events. Its response +is saved once, including an empty result. After all chunks finish Selection, +**Claimify** writes standalone claims using their kept propositions and a bounded +set of earlier references. A reference can cross a section boundary, but remains +within the previous eight chunks of the same document representation. + +Each earlier reference includes exact source passages. Its descriptive name helps +orientation; the source passages must support the resulting claim and be cited. +For example, a tournament introduced in chunk 2 can clarify “that tournament” in +chunk 7. Two tournaments with the same date remain separate references. The +engine supplies passage labels and resolves them to exact occurrence ranges. + +The initial limits are four published references per Selection response and eight +references, totaling at most 4,096 characters including evidence, per Claimify +request. These are bounded context limits, not a guarantee that every distant +reference is available. No additional extraction model call is introduced. + +Version reuse includes the earlier chunks' source inputs even when they produced +no references. An edit there can introduce a competing referent and must trigger +rechecking. Unchanged inputs reuse the saved decisions and claim identities, +remapping all evidence ranges onto the new occurrence. + **Gates:** - Deterministic grounding checks reject unanchored inventions. diff --git a/website/src/app/docs/project-status/page.mdx b/website/src/app/docs/project-status/page.mdx index 05efed426..837ec249b 100644 --- a/website/src/app/docs/project-status/page.mdx +++ b/website/src/app/docs/project-status/page.mdx @@ -14,6 +14,7 @@ Target release coordinate: [`v0.17.0`](https://github.com/writeitai/remember-sta - Full evidence spine: ingest → convert → structure → chunk → claim extract → entity resolve → fact adjudicate - Immutable claims with occurrence-level multi-span source grounding, adjudicated relations and observations, bi-temporal validity, supersession, contradiction groups +- Frozen Selection results share bounded, source-backed references with later extraction; version reuse covers all cited ranges and earlier context inputs - Testimony currency and lineage-based evidence counting when documents change or extractors re-run - Watched sources and versioned document lineages (including a local directory watcher) From 3af2119c7c1c12a9e145eacdcee86fdf2242ccf5 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 15:02:37 +0200 Subject: [PATCH 08/14] fix(benchmark): identify combined processing as Full-v31 Pin RS-LoCoMo-Full-v31 to D122/D123 generations and the ground_claims E2 split. Extractor assertion-clarity-4:d122-source-references-1, normalizer d123-context-refs-2, adjudicators d123-context-nom-2, concise renderer concise-handles-2. GemmaVertex stays reader-only. Fingerprint regenerated from prepare. Question manifests unchanged. --- benchmarks/locomo/README.md | 49 +++++++++------ benchmarks/locomo/__init__.py | 2 +- benchmarks/locomo/cli.py | 2 +- benchmarks/locomo/model.py | 14 ++--- benchmarks/locomo/protocol.py | 57 ++++++++++------- benchmarks/locomo/runner.py | 10 +-- benchmarks/locomo/sharding/README.md | 5 +- benchmarks/locomo/sharding/run_shard.sh | 8 ++- src/tests/benchmarks/test_locomo_protocol.py | 63 ++++++++++++------- src/tests/benchmarks/test_locomo_runner.py | 14 ++--- .../benchmarks/test_locomo_store_backup.py | 8 ++- website/src/app/docs/evaluation/page.mdx | 4 +- website/src/app/docs/project-status/page.mdx | 6 +- 13 files changed, 146 insertions(+), 96 deletions(-) diff --git a/benchmarks/locomo/README.md b/benchmarks/locomo/README.md index 0c030ab41..9c6a7532b 100644 --- a/benchmarks/locomo/README.md +++ b/benchmarks/locomo/README.md @@ -1,4 +1,15 @@ -# RS-LoCoMo-Full-v30 setup +# RS-LoCoMo-Full-v31 setup + +v31 (2026-09-14) pins D122 source-backed document references and D123 +contextual fact nomination on the combined D119–D121 processing contract, and +requires the supported ingest stage `ground_claims` (Claimify after Selection). +Extractor generation includes `assertion-clarity-4:d122-source-references-1`; +normalizer `assertion-clarity-3:d123-context-refs-2`; relation and observation +adjudicators `concise-handles-5:d123-context-nom-2`; concise renderer +`concise-handles-2`. Stores ingested under v30 are not comparable and must be +re-ingested for this protocol. Dataset, provider defaults, answer/judge +behavior and scoring are unchanged. The changed pins do not establish improved +quality or lower cost. v30 (2026-09-14) combines D119 multi-span extraction with D120/D121 clear processing instructions and compact adjudication input. Extractor generation @@ -43,12 +54,12 @@ The safe first command is local and makes no API or model call: uv run --extra benchmark python -m benchmarks.locomo prepare \ --dataset /absolute/path/locomo10.json \ --tier smoke \ - --protocol full-v30 \ + --protocol full-v31 \ --output .benchmark-runs/locomo-smoke ``` The harness validates the pinned bytes, renders session documents, and fingerprints the -eight-question smoke plan. `--protocol` is prepare-only; `full-v30` is the one +eight-question smoke plan. `--protocol` is prepare-only; `full-v31` is the one current-system protocol, and every later stage reads that immutable choice from `run.json`. Do not run remote stages until reviewing [`locomo_benchmark_design.md`](../../plan/designs/locomo_benchmark_design.md). @@ -195,17 +206,19 @@ Pass the resulting with `--p3-root`. The runner rejects a mount whose `.snapshot-version` differs from readiness. -## Gemma 4 on Vertex as the answer agent (`full-v30-gemma-vertex`) +## Gemma 4 on Vertex as the answer agent (`full-v31-gemma-vertex`) -`full-v30-gemma-vertex` is a *variant* of `full-v30`, not a new benchmark -identity: every pin is identical -- ingestion bindings, prompts, tool catalog, -budgets, temperature, and the frozen Luna judge -- except that the answer -agent is `google/gemma-4-26b-a4b-it-maas`, Google's managed Gemma 4 26B-A4B -model on the Gemini Enterprise Agent Platform (formerly Vertex AI), and the -answer step is pinned as `DiscriminatedAnswerAgentStep`. Its scores therefore -compare answer agents over the same stores. The judge and the preflight -embedding stay on OpenRouter, so the OpenRouter key is still required; only -the answer-agent model name routes to Vertex. +`full-v31-gemma-vertex` is a *reader-only variant* of `full-v31`, not a new +benchmark identity and not a processing configuration: every ingest pin is +identical -- pipeline stages including `ground_claims`, component generations, +model bindings, prompts, tool catalog, budgets, temperature, and the frozen +Luna judge -- except that the answer agent is `google/gemma-4-26b-a4b-it-maas`, +Google's managed Gemma 4 26B-A4B model on the Gemini Enterprise Agent Platform +(formerly Vertex AI), and the answer step is pinned as +`DiscriminatedAnswerAgentStep`. Its scores therefore compare answer agents +over the same stores. The judge and the preflight embedding stay on OpenRouter, +so the OpenRouter key is still required; only the answer-agent model name +routes to Vertex. The step shape differs for a measured reason. Vertex's constrained decoder emits object keys in **alphabetical** order and demands every required key, @@ -226,7 +239,7 @@ Prepare it explicitly; every later stage reads the immutable choice: uv run --extra benchmark python -m benchmarks.locomo prepare \ --dataset /absolute/path/locomo10.json \ --tier smoke \ - --protocol full-v30-gemma-vertex \ + --protocol full-v31-gemma-vertex \ --output .benchmark-runs/locomo-gemma-smoke ``` @@ -268,7 +281,7 @@ any upload. ## Codex ChatGPT subscription for answer and judge -`full-v30-codex-subscription` runs both evaluator seats through the official +`full-v31-codex-subscription` runs both evaluator seats through the official local Codex app-server and the operator's existing ChatGPT login. It does not read or copy `~/.codex/auth.json`, accept an OpenAI API key, or call the private ChatGPT response route directly. Run `codex login` once, then prepare the @@ -278,14 +291,14 @@ separately fingerprinted protocol: uv run --extra benchmark python -m benchmarks.locomo prepare \ --dataset /absolute/path/locomo10.json \ --tier smoke \ - --protocol full-v30-codex-subscription \ + --protocol full-v31-codex-subscription \ --output .benchmark-runs/locomo-codex-smoke ``` -The v30 prompts, schemas, tool loop, call limits, judge rubric, and scoring stay +The v31 prompts, schemas, tool loop, call limits, judge rubric, and scoring stay the same. The provider controls do not: Codex pins `gpt-5.6-luna`, reasoning effort `high`, and temperature `null`. Therefore this is an experimental -provider variant, not a canonical v30 score. +provider variant, not a canonical v31 score. Each model call uses a fresh ephemeral thread, an empty temporary directory, read-only/no-network sandboxing, and deny-all approvals. It receives no custom diff --git a/benchmarks/locomo/__init__.py b/benchmarks/locomo/__init__.py index 5d347d178..231999439 100644 --- a/benchmarks/locomo/__init__.py +++ b/benchmarks/locomo/__init__.py @@ -1 +1 @@ -"""The pinned RS-LoCoMo-Full-v30 benchmark adapter.""" +"""The pinned RS-LoCoMo-Full-v31 benchmark adapter.""" diff --git a/benchmarks/locomo/cli.py b/benchmarks/locomo/cli.py index 02be6e63c..0c5c5c4eb 100644 --- a/benchmarks/locomo/cli.py +++ b/benchmarks/locomo/cli.py @@ -173,7 +173,7 @@ def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="python -m benchmarks.locomo", description=( - "RS-LoCoMo-Full-v30: prepare is local; ingest/answer/judge require " + "RS-LoCoMo-Full-v31: prepare is local; ingest/answer/judge require " "explicit execution acknowledgements" ), ) diff --git a/benchmarks/locomo/model.py b/benchmarks/locomo/model.py index cc03644d4..31d3d5b31 100644 --- a/benchmarks/locomo/model.py +++ b/benchmarks/locomo/model.py @@ -1,4 +1,4 @@ -"""Typed values for the full-system RS-LoCoMo-Full-v30 protocol.""" +"""Typed values for the full-system RS-LoCoMo-Full-v31 protocol.""" from __future__ import annotations @@ -33,12 +33,12 @@ RetainedCategory = Literal[1, 2, 3, 4] Tier = Literal["smoke", "development", "publication"] ProtocolKey = Literal[ - "full-v30", "full-v30-gemma-vertex", "full-v30-codex-subscription" + "full-v31", "full-v31-gemma-vertex", "full-v31-codex-subscription" ] ProtocolName = Literal[ - "RS-LoCoMo-Full-v30", - "RS-LoCoMo-Full-v30-GemmaVertex", - "RS-LoCoMo-Full-v30-CodexSubscription", + "RS-LoCoMo-Full-v31", + "RS-LoCoMo-Full-v31-GemmaVertex", + "RS-LoCoMo-Full-v31-CodexSubscription", ] SourceTimezoneBasis = Literal["assumed_utc"] AnswerAgentModel = Literal[ @@ -135,7 +135,7 @@ class QuestionManifest(FrozenModel): class RunConfiguration(FrozenModel): """Immutable identity of one prepared benchmark run.""" - protocol_name: ProtocolName = "RS-LoCoMo-Full-v30" + protocol_name: ProtocolName = "RS-LoCoMo-Full-v31" adapter_version: NonEmpty prepared_at: datetime repository_revision: NonEmpty @@ -486,7 +486,7 @@ class SessionDiagnosticSummary(FrozenModel): class RunSummary(FrozenModel): """Publication-ready local aggregate with no hidden denominator.""" - protocol_name: ProtocolName = "RS-LoCoMo-Full-v30" + protocol_name: ProtocolName = "RS-LoCoMo-Full-v31" protocol_fingerprint: NonEmpty tier: Tier questions: int = Field(ge=1) diff --git a/benchmarks/locomo/protocol.py b/benchmarks/locomo/protocol.py index 433234a33..0ee5a11bf 100644 --- a/benchmarks/locomo/protocol.py +++ b/benchmarks/locomo/protocol.py @@ -35,15 +35,18 @@ from rememberstack.model import ReasoningEffort from rememberstack.model import ToolDescriptor -PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v30" -DEFAULT_PROTOCOL_KEY: Final = "full-v30" -ADAPTER_VERSION: Final = "locomo-full-adapter-2026.09-concise-adjudication-v30" +PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v31" +DEFAULT_PROTOCOL_KEY: Final = "full-v31" +ADAPTER_VERSION: Final = "locomo-full-adapter-2026.09-document-context-v31" +"""Adapter identity for Full-v31: D122/D123 on the D119–D121 processing contract.""" MAX_TOOL_CALLS: Final = 8 MAX_AGENT_CALLS: Final = 9 ANSWER_READER_RETRY_BUDGET: Final = 2 API_TIMEOUT_SECONDS: Final = 60.0 """Transport budget for compound retrieval, larger than the server DB budget.""" EXPECTED_DOCUMENT_BINDING_GENERATION: Final = "document-t0-v1" +EXPECTED_PROMPT_RENDERER_VERSION: Final = "concise-handles-2" +"""Concise adjudication projector/response-adapter generation (D121/D123).""" EXPECTED_SURFACE_MANIFEST_HASH: Final = ( "d8be43966d90048ce3fc8ffe6dfdfc7943999fbf4f018ac2eb7998f2c995aae2" @@ -54,6 +57,7 @@ "chunk", "embed_chunk", "extract_claims", + "ground_claims", "normalize_relations", "adjudicate_observations", "adjudicate_supersession", @@ -61,6 +65,12 @@ "reconcile", "label_relation", ) +_E2_EXTRACTOR_GENERATION: Final = ( + "e2-extract-2026.09:d119-multi-span-1:d80-location-elements-1:" + "token-union-grounding-1:temporal-anchor-4:d107-kind-vocabulary-1:" + "d79-section-orientation-v1:max-chars2048:target-first:unicode-ellipsis:" + "assertion-clarity-4:d122-source-references-1" +) EXPECTED_INGEST_COMPONENT_VERSIONS: Final[Mapping[str, str]] = MappingProxyType( { "convert": "e0-convert-2026.08", @@ -70,19 +80,19 @@ "blockizer-heading-metadata" ), "embed_chunk": "e1-embed-2026.08-d80", - "extract_claims": ( - "e2-extract-2026.09:d119-multi-span-1:d80-location-elements-1:" - "token-union-grounding-1:temporal-anchor-4:d107-kind-vocabulary-1:" - "d79-section-orientation-v1:max-chars2048:target-first:unicode-ellipsis:" - "assertion-clarity-4" - ), + "extract_claims": _E2_EXTRACTOR_GENERATION, + "ground_claims": _E2_EXTRACTOR_GENERATION, "normalize_relations": ( "e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:" "no-types-1:binary-t4-1:document-t0-1:mutable-window-1:" - "assertion-clarity-3:d123-context-refs-1" + "assertion-clarity-3:d123-context-refs-2" ), "adjudicate_observations": ( - "e3-obs-flush:entity-fanout-1:e3-normalize-2026.09f:temp0-1:claim-fanout-1:bare-noun-1:no-types-1:binary-t4-1:document-t0-1:mutable-window-1:assertion-clarity-3:d123-context-refs-1:relation-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1:obs-adjudicator-2026.09d:concise-handles-5:d123-context-nom-1" + "e3-obs-flush:entity-fanout-1:e3-normalize-2026.09f:temp0-1:" + "claim-fanout-1:bare-noun-1:no-types-1:binary-t4-1:document-t0-1:" + "mutable-window-1:assertion-clarity-3:d123-context-refs-2:" + "relation-adjudicator-2026.09d:concise-handles-5:d123-context-nom-2:" + "obs-adjudicator-2026.09d:concise-handles-5:d123-context-nom-2" ), "adjudicate_supersession": "fact-followup-2026.09:mutable-window-1", "embed_claim": "p1-embed-claims-2026.07", @@ -118,21 +128,22 @@ JUDGE_MODEL: Final = "openai/gpt-5.6-luna" JUDGE_REASONING_EFFORT: Final = "none" TEMPERATURE: Final = 0.0 -GEMMA_VERTEX_PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v30-GemmaVertex" -GEMMA_VERTEX_PROTOCOL_KEY: Final = "full-v30-gemma-vertex" +GEMMA_VERTEX_PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v31-GemmaVertex" +GEMMA_VERTEX_PROTOCOL_KEY: Final = "full-v31-gemma-vertex" GEMMA_VERTEX_ANSWER_AGENT_MODEL: Final = "google/gemma-4-26b-a4b-it-maas" """Gemma 4 26B-A4B IT served by Google as a managed open model (MaaS). -The variant protocol keeps every v30 pin -- ingestion bindings, prompts, -tool catalog, budgets, judge -- and swaps only the answer agent to this model -on Vertex, with thinking deliberately pinned off and the answer step pinned as -`DiscriminatedAnswerAgentStep`, the -same decision in a two-branch JSON shape that Vertex's order-enforcing -decoder completes. Scores are therefore an answer-agent comparison over the -same stores, not a new benchmark identity. +The variant is reader-only. It keeps every canonical v31 ingest pin -- +pipeline stages including ground_claims, component generations, model +bindings, prompts, tool catalog, budgets, and judge -- and swaps only the +answer agent to this model on Vertex, with thinking deliberately pinned off +and the answer step pinned as `DiscriminatedAnswerAgentStep`, the same +decision in a two-branch JSON shape that Vertex's order-enforcing decoder +completes. It does not configure processing. Scores are therefore an +answer-agent comparison over the same stores, not a new benchmark identity. """ -CODEX_SUBSCRIPTION_PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v30-CodexSubscription" -CODEX_SUBSCRIPTION_PROTOCOL_KEY: Final = "full-v30-codex-subscription" +CODEX_SUBSCRIPTION_PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v31-CodexSubscription" +CODEX_SUBSCRIPTION_PROTOCOL_KEY: Final = "full-v31-codex-subscription" CODEX_SUBSCRIPTION_MODEL: Final = "gpt-5.6-luna" CODEX_SUBSCRIPTION_REASONING_EFFORT: Final = "high" @@ -269,7 +280,7 @@ class LoCoMoProtocol: _FULL_V25 = LoCoMoProtocol( - key="full-v30", + key="full-v31", name=PROTOCOL_NAME, answer_agent_model=ANSWER_AGENT_MODEL, judge_model=JUDGE_MODEL, diff --git a/benchmarks/locomo/runner.py b/benchmarks/locomo/runner.py index 1a7fa6aa9..e36a4ac26 100644 --- a/benchmarks/locomo/runner.py +++ b/benchmarks/locomo/runner.py @@ -424,7 +424,7 @@ def ingest_sample( _require_current_ingest_bindings(model_bindings=build.model_bindings) if build.document_binding_generation != EXPECTED_DOCUMENT_BINDING_GENERATION: raise ExecutionGuardError( - "deployment document binding generation differs from RS-LoCoMo-Full-v30" + "deployment document binding generation differs from RS-LoCoMo-Full-v31" ) _require_current_query_surface(context=context, client=client) _require_exact_live_ingests( @@ -587,7 +587,7 @@ def answer_sample( ): raise ExecutionGuardError( "the deployment did not report the exact completed" - " RS-LoCoMo-Full-v30 pipeline, live graph, and fresh P3 projection" + " RS-LoCoMo-Full-v31 pipeline, live graph, and fresh P3 projection" ) _require_serving_revision(context=context, readiness=readiness) prior_readiness = context.state.readiness.get(sample_id) @@ -1211,7 +1211,7 @@ def _validate_run( """Recompute immutable run identity before any local or remote stage.""" selected_protocol = protocol_for_name(configuration.protocol_name) if configuration.dataset_sha256 != DATASET_SHA256: - raise BenchmarkRunError("run dataset hash is not RS-LoCoMo-Full-v30") + raise BenchmarkRunError("run dataset hash is not RS-LoCoMo-Full-v31") if item_ids_hash(item_ids=manifest.item_ids) != manifest.item_ids_sha256: raise BenchmarkRunError("run manifest item hash changed") if manifest_bytes_hash(manifest=manifest) != configuration.manifest_sha256: @@ -1221,7 +1221,7 @@ def _validate_run( if manifest.tier != configuration.tier: raise BenchmarkRunError("run manifest tier changed") if configuration.dataset_commit != DATASET_COMMIT: - raise BenchmarkRunError("run dataset commit is not RS-LoCoMo-Full-v30") + raise BenchmarkRunError("run dataset commit is not RS-LoCoMo-Full-v31") if configuration.adapter_version != ADAPTER_VERSION: raise BenchmarkRunError("run adapter version differs from current code") if _models_hash(values=documents) != configuration.documents_sha256: @@ -1479,7 +1479,7 @@ def _require_current_ingest_bindings(*, model_bindings: dict[str, str]) -> None: if model_bindings.get(name) != expected.get(name) ) raise ExecutionGuardError( - "deployment ingest model bindings differ from RS-LoCoMo-Full-v30: " + "deployment ingest model bindings differ from RS-LoCoMo-Full-v31: " + ", ".join(mismatches) ) diff --git a/benchmarks/locomo/sharding/README.md b/benchmarks/locomo/sharding/README.md index abc947191..b000af837 100644 --- a/benchmarks/locomo/sharding/README.md +++ b/benchmarks/locomo/sharding/README.md @@ -178,7 +178,7 @@ as source-derived data. | --- | ---: | --- | | `LOCOMO_PYTHON` | `.venv/bin/python` | repository virtual-environment Python | | `LOCOMO_TIER` | `publication` | prepared manifest tier | -| `LOCOMO_PROTOCOL` | `full-v30` | prepare-time protocol key | +| `LOCOMO_PROTOCOL` | `full-v31` | prepare-time protocol key | | `LOCOMO_MOUNT_ROOT` | `$RUN_DIR/.mounts` | host/container-identical P3 mount root | | `LOCOMO_MAX_DOCUMENTS` | `100` | per-sample ingest authorization | | `LOCOMO_MAX_QUESTIONS` | `1540` | run-absolute answer item authorization | @@ -193,7 +193,8 @@ as source-derived data. | `LOCOMO_BACKUP_TOOL` | `benchmarks/locomo/sharding/store_backup.py` | backup tool path; use an absolute path only when operating a pinned clean campaign checkout with a newer compatible safety runner | | `LOCOMO_COMPOSE_PROJECT` | `rememberstack` | Compose label used to resolve exactly four volumes | | `LOCOMO_RUNNER_LOCK` | `/var/lock/rememberstack-locomo-shard.lock` | host-wide exclusive runner lock | -| `LOCOMO_EXTRACT_CLAIM_WORKERS` | `8` | chunk-level Claimify worker replicas | +| `LOCOMO_EXTRACT_CLAIM_WORKERS` | `8` | chunk-level Selection worker replicas | +| `LOCOMO_GROUND_CLAIM_WORKERS` | `8` | chunk-level Claimify worker replicas | | `LOCOMO_NORMALIZE_RELATION_WORKERS` | `6` | claim-level E3 normalize worker replicas | | `LOCOMO_ADJUDICATE_OBSERVATION_WORKERS` | `4` | post-barrier observation-flush worker replicas | | `LOCOMO_EMBED_CLAIM_WORKERS` | `2` | P1 claim/fact embedding worker replicas | diff --git a/benchmarks/locomo/sharding/run_shard.sh b/benchmarks/locomo/sharding/run_shard.sh index b8518d78c..12a97ba90 100755 --- a/benchmarks/locomo/sharding/run_shard.sh +++ b/benchmarks/locomo/sharding/run_shard.sh @@ -25,7 +25,7 @@ run_dir=$2 dataset_path=$3 python_bin=${LOCOMO_PYTHON:-.venv/bin/python} tier=${LOCOMO_TIER:-publication} -protocol=${LOCOMO_PROTOCOL:-full-v30} +protocol=${LOCOMO_PROTOCOL:-full-v31} mount_root=${LOCOMO_MOUNT_ROOT:-$run_dir/.mounts} max_documents=${LOCOMO_MAX_DOCUMENTS:-100} max_questions=${LOCOMO_MAX_QUESTIONS:-1540} @@ -40,6 +40,7 @@ backup_staging_root=${LOCOMO_BACKUP_STAGING_ROOT:-/var/lib/rememberstack-locomo- compose_project=${LOCOMO_COMPOSE_PROJECT:-rememberstack} runner_lock=${LOCOMO_RUNNER_LOCK:-/var/lock/rememberstack-locomo-shard.lock} extract_claim_workers=${LOCOMO_EXTRACT_CLAIM_WORKERS:-8} +ground_claim_workers=${LOCOMO_GROUND_CLAIM_WORKERS:-8} normalize_relation_workers=${LOCOMO_NORMALIZE_RELATION_WORKERS:-6} adjudicate_observation_workers=${LOCOMO_ADJUDICATE_OBSERVATION_WORKERS:-4} embed_claim_workers=${LOCOMO_EMBED_CLAIM_WORKERS:-2} @@ -59,7 +60,7 @@ backup_python() { "$python_bin" "$@" } -# RS-LoCoMo-Full-v30's non-secret ingest identity. Override ambient self-host +# RS-LoCoMo-Full-v31's non-secret ingest identity. Override ambient self-host # defaults so every shard runs the exact Luna/Qwen pipeline the protocol checks. export REMEMBERSTACK_STRUCTURER_MODEL=openai/gpt-5.6-luna export REMEMBERSTACK_SKELETON_CHECK_MODEL=openai/gpt-5.6-luna @@ -121,6 +122,7 @@ for value in \ "$drain_timeout_seconds" \ "$drain_poll_seconds" \ "$extract_claim_workers" \ + "$ground_claim_workers" \ "$normalize_relation_workers" \ "$adjudicate_observation_workers" \ "$embed_claim_workers"; do @@ -341,6 +343,7 @@ require_verified_final_backup() { start_existing_store() { "${compose[@]}" up --detach --wait --no-recreate \ --scale "worker-extract-claims=$extract_claim_workers" \ + --scale "worker-ground-claims=$ground_claim_workers" \ --scale "worker-normalize-relations=$normalize_relation_workers" \ --scale "worker-adjudicate-observations=$adjudicate_observation_workers" \ --scale "worker-embed-claim=$embed_claim_workers" @@ -474,6 +477,7 @@ for sample_id in "${pending_samples[@]}"; do log "sample=$sample_id stage=stack status=starting" "${compose[@]}" up --detach --wait \ --scale "worker-extract-claims=$extract_claim_workers" \ + --scale "worker-ground-claims=$ground_claim_workers" \ --scale "worker-normalize-relations=$normalize_relation_workers" \ --scale "worker-adjudicate-observations=$adjudicate_observation_workers" \ --scale "worker-embed-claim=$embed_claim_workers" diff --git a/src/tests/benchmarks/test_locomo_protocol.py b/src/tests/benchmarks/test_locomo_protocol.py index 245384438..017069c7e 100644 --- a/src/tests/benchmarks/test_locomo_protocol.py +++ b/src/tests/benchmarks/test_locomo_protocol.py @@ -18,6 +18,8 @@ from benchmarks.locomo.protocol import ANSWER_AGENT_PROMPT_TEMPLATE from benchmarks.locomo.protocol import DEFAULT_PROTOCOL_KEY from benchmarks.locomo.protocol import EXPECTED_INGEST_COMPONENT_VERSIONS +from benchmarks.locomo.protocol import EXPECTED_PIPELINE_STAGES +from benchmarks.locomo.protocol import EXPECTED_PROMPT_RENDERER_VERSION from benchmarks.locomo.protocol import EXPECTED_SURFACE_MANIFEST_HASH from benchmarks.locomo.protocol import official_f1 from benchmarks.locomo.protocol import prompt_sha256 @@ -38,6 +40,7 @@ from rememberstack.adapters import ModelRoutedProvider from rememberstack.adapters import OpenRouterModelProvider from rememberstack.adapters import VertexSettings +from rememberstack.core.concise_adjudication import PROMPT_RENDERER_VERSION from rememberstack.model import ChunkEvidenceResult from rememberstack.model import current_temporal_scope from rememberstack.model import Envelope @@ -189,6 +192,20 @@ def test_reader_trace_keeps_chunk_evidence_but_omits_rank_bookkeeping() -> None: def test_protocol_pins_the_shipping_extractor_generation() -> None: """The benchmark cannot silently ingest a different temporal extraction policy.""" assert EXPECTED_INGEST_COMPONENT_VERSIONS["extract_claims"] == E2_EXTRACTOR_VERSION + assert EXPECTED_INGEST_COMPONENT_VERSIONS["ground_claims"] == E2_EXTRACTOR_VERSION + + +def test_protocol_pins_ground_claims_as_the_e2_split() -> None: + """Claimify is a supported ingest stage at the same extractor generation.""" + assert EXPECTED_PIPELINE_STAGES.index("ground_claims") == ( + EXPECTED_PIPELINE_STAGES.index("extract_claims") + 1 + ) + assert tuple(EXPECTED_INGEST_COMPONENT_VERSIONS) == EXPECTED_PIPELINE_STAGES + + +def test_protocol_pins_the_shipping_concise_renderer_generation() -> None: + """Adjudication input rendering is part of the processing identity.""" + assert EXPECTED_PROMPT_RENDERER_VERSION == PROMPT_RENDERER_VERSION def test_protocol_pins_the_shipping_observation_flush_generation() -> None: @@ -253,10 +270,10 @@ def test_current_protocol_pins_manifest_and_complete_read_plane() -> None: assert len(tool_catalog_sha256()) == 64 -def test_protocol_is_v30_and_answer_prompt_has_reasoning_and_loop_guards() -> None: +def test_protocol_is_v31_and_answer_prompt_has_reasoning_and_loop_guards() -> None: """The current identity, bounded inference, and loop discipline are locked.""" - assert PROTOCOL_NAME == "RS-LoCoMo-Full-v30" - assert DEFAULT_PROTOCOL_KEY == "full-v30" + assert PROTOCOL_NAME == "RS-LoCoMo-Full-v31" + assert DEFAULT_PROTOCOL_KEY == "full-v31" prompt = ANSWER_AGENT_PROMPT_TEMPLATE normalized_prompt = " ".join(prompt.split()) assert ( @@ -301,13 +318,13 @@ def test_protocol_is_v30_and_answer_prompt_has_reasoning_and_loop_guards() -> No def test_typed_protocol_registry_pins_answer_agent_identity_and_effort() -> None: assert tuple(PROTOCOL_REGISTRY) == ( - "full-v30", - "full-v30-gemma-vertex", - "full-v30-codex-subscription", + "full-v31", + "full-v31-gemma-vertex", + "full-v31-codex-subscription", ) - protocol = PROTOCOL_REGISTRY["full-v30"] + protocol = PROTOCOL_REGISTRY["full-v31"] - assert protocol.name == "RS-LoCoMo-Full-v30" + assert protocol.name == "RS-LoCoMo-Full-v31" assert protocol.answer_agent_model == "openai/gpt-5.6-luna" assert protocol.answer_agent_reasoning_effort == "none" assert protocol.judge_reasoning_effort == "none" @@ -345,7 +362,7 @@ def fake_prepare_run(**values: object) -> _Prepared: ) assert exit_code == 0 - assert selected == ["full-v30"] + assert selected == ["full-v31"] def test_summarize_cli_accepts_multiple_run_flags( @@ -483,12 +500,12 @@ def test_parsed_arguments_rejects_non_objects_and_fragments(raw: str) -> None: def test_gemma_vertex_variant_swaps_only_the_answer_agent() -> None: - """The variant is a provider swap over identical v30 pins, so its scores are - an answer-agent comparison rather than a new benchmark identity.""" - base = PROTOCOL_REGISTRY["full-v30"] - variant = PROTOCOL_REGISTRY["full-v30-gemma-vertex"] + """The variant is a reader-only provider swap over identical v31 pins, so its + scores are an answer-agent comparison rather than a new benchmark identity.""" + base = PROTOCOL_REGISTRY["full-v31"] + variant = PROTOCOL_REGISTRY["full-v31-gemma-vertex"] - assert variant.name == "RS-LoCoMo-Full-v30-GemmaVertex" + assert variant.name == "RS-LoCoMo-Full-v31-GemmaVertex" assert variant.answer_agent_model == "google/gemma-4-26b-a4b-it-maas" assert variant.answer_agent_provider == "vertex" assert variant.answer_agent_reasoning_effort == "none" @@ -526,7 +543,7 @@ def test_gemma_vertex_variant_swaps_only_the_answer_agent() -> None: base.judge_repetitions, base.answer_word_cap, ) - assert DEFAULT_PROTOCOL_KEY == "full-v30" + assert DEFAULT_PROTOCOL_KEY == "full-v31" def _write_run_json(*, run_dir: Path, protocol_key: str) -> None: @@ -567,7 +584,7 @@ def test_cli_composes_only_the_vertex_answer_seat( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """Gemma answers on Vertex; judge and ingest compose OpenRouter separately.""" - _write_run_json(run_dir=tmp_path, protocol_key="full-v30-gemma-vertex") + _write_run_json(run_dir=tmp_path, protocol_key="full-v31-gemma-vertex") monkeypatch.setenv("REMEMBERSTACK_OPENROUTER_API_KEY", "test-key") monkeypatch.setenv("REMEMBERSTACK_VERTEX_PROJECT_ID", "umc-locomo-vertex-lab") built: list[VertexSettings] = [] @@ -604,12 +621,12 @@ def test_cli_keeps_plain_openrouter_for_the_default_protocol( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """No Vertex settings are required, or even read, for an OpenRouter-only run.""" - _write_run_json(run_dir=tmp_path, protocol_key="full-v30") + _write_run_json(run_dir=tmp_path, protocol_key="full-v31") monkeypatch.setenv("REMEMBERSTACK_OPENROUTER_API_KEY", "test-key") monkeypatch.delenv("REMEMBERSTACK_VERTEX_PROJECT_ID", raising=False) def refuse(**_values: object) -> object: # pragma: no cover - raise AssertionError("Vertex must not be composed for full-v30") + raise AssertionError("Vertex must not be composed for full-v31") monkeypatch.setattr(cli, "VertexModelProvider", refuse) @@ -624,7 +641,7 @@ def test_cli_fails_fast_when_a_vertex_protocol_lacks_a_project( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """A missing project id is caught before any stage work or paid call.""" - _write_run_json(run_dir=tmp_path, protocol_key="full-v30-gemma-vertex") + _write_run_json(run_dir=tmp_path, protocol_key="full-v31-gemma-vertex") monkeypatch.setenv("REMEMBERSTACK_OPENROUTER_API_KEY", "test-key") monkeypatch.delenv("REMEMBERSTACK_VERTEX_PROJECT_ID", raising=False) @@ -634,10 +651,10 @@ def test_cli_fails_fast_when_a_vertex_protocol_lacks_a_project( def test_codex_subscription_variant_pins_both_generation_seats() -> None: """The experimental variant changes provider controls, not LoCoMo logic.""" - base = PROTOCOL_REGISTRY["full-v30"] - variant = PROTOCOL_REGISTRY["full-v30-codex-subscription"] + base = PROTOCOL_REGISTRY["full-v31"] + variant = PROTOCOL_REGISTRY["full-v31-codex-subscription"] - assert variant.name == "RS-LoCoMo-Full-v30-CodexSubscription" + assert variant.name == "RS-LoCoMo-Full-v31-CodexSubscription" assert variant.answer_agent_model == "gpt-5.6-luna" assert variant.judge_model == "gpt-5.6-luna" assert variant.answer_agent_provider == "codex_subscription" @@ -658,7 +675,7 @@ def test_cli_codex_answer_and_judge_need_no_openrouter_key( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """An already-ingested run can evaluate solely through local Codex auth.""" - _write_run_json(run_dir=tmp_path, protocol_key="full-v30-codex-subscription") + _write_run_json(run_dir=tmp_path, protocol_key="full-v31-codex-subscription") monkeypatch.delenv("REMEMBERSTACK_OPENROUTER_API_KEY", raising=False) answer_provider = cli._provider(run_dir=tmp_path, stage="answer") diff --git a/src/tests/benchmarks/test_locomo_runner.py b/src/tests/benchmarks/test_locomo_runner.py index 25f4cd062..44105fefb 100644 --- a/src/tests/benchmarks/test_locomo_runner.py +++ b/src/tests/benchmarks/test_locomo_runner.py @@ -1057,9 +1057,9 @@ def test_answer_persists_usage_when_provider_drifts_after_tool_call() -> None: "invalid_reader_completions", ), ( - ("full-v30", "openai/gpt-5.6-luna", "openai/gpt-5.6-luna", "none", 0.0, 0, 2), + ("full-v31", "openai/gpt-5.6-luna", "openai/gpt-5.6-luna", "none", 0.0, 0, 2), ( - "full-v30-codex-subscription", + "full-v31-codex-subscription", "gpt-5.6-luna", "gpt-5.6-luna", "high", @@ -1704,7 +1704,7 @@ def drifted_binding(request: httpx.Request) -> httpx.Response: def test_ingest_refuses_document_binding_generation_drift_before_upload( tmp_path: Path, monkeypatch: pytest.MonkeyPatch ) -> None: - """Full-v30 cannot silently process with document-local T0 disabled.""" + """Full-v31 cannot silently process with document-local T0 disabled.""" _patch_prepared_inputs(monkeypatch=monkeypatch) run_dir = tmp_path / "run" prepare_run(dataset_path=tmp_path / "synthetic.json", tier="smoke", output=run_dir) @@ -1930,8 +1930,8 @@ def test_single_run_summary_json_is_unchanged( serialized = summarize_run(run_dir=run_dir).model_dump_json() assert serialized == ( - '{"protocol_name":"RS-LoCoMo-Full-v30","protocol_fingerprint":' - '"7c0f0501895d1c219667e807d003e0ccb154bef5accc97dbbcbdded957a4ab72",' + '{"protocol_name":"RS-LoCoMo-Full-v31","protocol_fingerprint":' + '"ee7d277f10e9b7d486f75f5221a7a174386248c3b5fc79c60815bcb7be1700b3",' '"tier":"smoke","questions":1,"judge_correct":0,"judge_percent":0.0,' '"official_f1":0.0,"categories":[{"category":1,"questions":0,' '"judge_correct":0,"judge_percent":0.0,"official_f1":0.0},{"category":2,' @@ -2150,7 +2150,7 @@ def test_prepared_protocol_pins_current_surface_and_luna( dataset_path=tmp_path / "synthetic.json", tier="smoke", output=run_dir ) - assert prepared.protocol_name == "RS-LoCoMo-Full-v30" + assert prepared.protocol_name == "RS-LoCoMo-Full-v31" assert prepared.answer_agent_model == "openai/gpt-5.6-luna" assert prepared.answer_agent_reasoning_effort == "none" assert prepared.answer_reader_retry_budget == 2 @@ -3422,7 +3422,7 @@ def test_preflight_reports_a_vertex_access_failure_as_unusable() -> None: def test_run_protocol_resolves_the_prepared_variant(tmp_path: Path) -> None: """The CLI composes providers from the frozen choice, not from ambient env.""" - protocol = PROTOCOL_REGISTRY["full-v30-gemma-vertex"] + protocol = PROTOCOL_REGISTRY["full-v31-gemma-vertex"] configuration = RunConfiguration( protocol_name=protocol.name, adapter_version="synthetic", diff --git a/src/tests/benchmarks/test_locomo_store_backup.py b/src/tests/benchmarks/test_locomo_store_backup.py index cae78328d..e3696d1e1 100644 --- a/src/tests/benchmarks/test_locomo_store_backup.py +++ b/src/tests/benchmarks/test_locomo_store_backup.py @@ -24,7 +24,7 @@ def _run_json(path: Path) -> None: (path / "run.json").write_text( json.dumps( { - "protocol_name": "RS-LoCoMo-Full-v30", + "protocol_name": "RS-LoCoMo-Full-v31", "protocol_fingerprint": "p" * 64, "repository_revision": "r" * 40, "prepared_at": "2026-08-11T00:00:00Z", @@ -660,7 +660,7 @@ def test_restore_validates_every_archive_before_running_docker( deployment_id="57000000-0000-0000-0000-000000000001", compose_project="rememberstack", run=store_backup.RunIdentity( - protocol_name="RS-LoCoMo-Full-v30", + protocol_name="RS-LoCoMo-Full-v31", protocol_fingerprint="p" * 64, repository_revision="r" * 40, prepared_at="2026-08-11T00:00:00Z", @@ -922,7 +922,7 @@ def test_runtime_validation_uses_the_image_revision_stamp( sample_id="conv-1", deployment_id=deployment_id, run=store_backup.RunIdentity( - protocol_name="RS-LoCoMo-Full-v30", + protocol_name="RS-LoCoMo-Full-v31", protocol_fingerprint="p" * 64, repository_revision=revision, prepared_at="2026-08-11T00:00:00Z", @@ -1033,6 +1033,8 @@ def test_shard_runner_guards_wipe_and_backs_up_before_scoring() -> None: "/var/lib/rememberstack/invalid-completions" ) in script assert "extract_claim_workers=${LOCOMO_EXTRACT_CLAIM_WORKERS:-8}" in script + assert "ground_claim_workers=${LOCOMO_GROUND_CLAIM_WORKERS:-8}" in script + assert '--scale "worker-ground-claims=$ground_claim_workers"' in script assert ( "adjudicate_observation_workers=${LOCOMO_ADJUDICATE_OBSERVATION_WORKERS:-4}" in script diff --git a/website/src/app/docs/evaluation/page.mdx b/website/src/app/docs/evaluation/page.mdx index fedd9ef7a..ec30306bf 100644 --- a/website/src/app/docs/evaluation/page.mdx +++ b/website/src/app/docs/evaluation/page.mdx @@ -75,7 +75,7 @@ Repository adapter: [`benchmarks/locomo/`](https://github.com/writeitai/remember - **Unshipped as a vendored dataset** — you supply pinned `locomo10.json` after confirming **CC BY-NC 4.0** terms. - **Operator-invoked** real provider runs; not silent CI spend. -- Current protocol is versioned and fingerprinted in the adapter README and design notes. +- Current protocol is `RS-LoCoMo-Full-v31`, versioned and fingerprinted in the adapter README. - Answer agent can use the **complete shipped read plane**: assured operations, direct primitives, open SQL/live graph helpers and saved queries, P1, and the ordinary published P3 mount. It has no private database/object-store shortcut. @@ -91,7 +91,7 @@ uv sync --extra benchmark uv run --extra benchmark python -m benchmarks.locomo prepare \ --dataset /absolute/path/locomo10.json \ --tier smoke \ - --protocol full-v16 \ + --protocol full-v31 \ --output .benchmark-runs/locomo-smoke ``` diff --git a/website/src/app/docs/project-status/page.mdx b/website/src/app/docs/project-status/page.mdx index 837ec249b..d03de5ef7 100644 --- a/website/src/app/docs/project-status/page.mdx +++ b/website/src/app/docs/project-status/page.mdx @@ -362,8 +362,10 @@ Facts have one chosen world-time window. Ordinary adjudication uses source dates and surrounding context to identify repeated events and revise a fact's dates. Claims retain the source's original testimony. Historical retrieval and dated summaries use the chosen window without a stored state/event taxonomy or separate -verdict dates. The evaluator generation is Full-v30; this change does not establish -a benchmark score improvement. +verdict dates. The evaluator generation is Full-v31; this change does not establish +a benchmark score improvement. Full-v31 additionally requires the `ground_claims` +ingest stage and pins D122 source-backed references plus D123 contextual +nomination. Dataset, models, retrieval, budgets, and scoring are unchanged. Stores created before this change are recreated and re-ingested; the migration refuses a populated database rather than converting it From d94667cef8be24d15a1b128c021fae495a4890cb Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 15:04:50 +0200 Subject: [PATCH 09/14] docs(processing): clarify earlier evidence and finalize generation contract --- plan/designs/locomo_benchmark_design.md | 17 ++++++++++------- src/rememberstack/profiles/selfhost.py | 2 +- src/rememberstack/workers/e2.py | 18 ++++++++++-------- .../workers/extraction_references.py | 5 ----- 4 files changed, 21 insertions(+), 21 deletions(-) diff --git a/plan/designs/locomo_benchmark_design.md b/plan/designs/locomo_benchmark_design.md index c9283f450..4b8880213 100644 --- a/plan/designs/locomo_benchmark_design.md +++ b/plan/designs/locomo_benchmark_design.md @@ -1,9 +1,12 @@ # LoCoMo full-system benchmark design -> **D119–D121 processing amendments (2026-09-14).** Full-v29 identifies +> **D119–D123 processing amendments (2026-09-14).** Full-v29 identifies > [D119 coherent multi-span extraction](multi_span_claim_extraction_design.md) > with version reuse. Full-v30 adds [clear processing instructions](processing_prompt_clarity_design.md) > and [concise adjudication inputs](concise_adjudication_inputs_design.md). +> Full-v31 adds [source-backed document references](document_reference_context_design.md) +> and [contextual fact nomination](contextual_fact_nomination_design.md), with +> separate Selection and Claimify work stages and unchanged two-call extraction. > The combined extractor, normalizer and adjudicator generations are pinned > separately from earlier stores. The adapter and protocol fingerprints roll > together. Dataset, provider defaults, answer/judge behavior and scoring do @@ -180,7 +183,7 @@ and spend ceiling. ## 2. Fixed protocol ```text -protocol RS-LoCoMo-Full-v30 +protocol RS-LoCoMo-Full-v31 dataset commit 3eb6f2c585f5e1699204e3c3bdf7adc5c28cb376 dataset SHA-256 79fa87e90f04081343b8c8debecb80a9a6842b76a7aa537dc9fdf651ea698ff4 categories 1, 2, 3, 4 @@ -528,7 +531,7 @@ accounting differ even though they use the same model. #### 2.1.1 Codex ChatGPT-subscription variant -`full-v30-codex-subscription` is an additive evaluator-provider variant for +`full-v31-codex-subscription` is an additive evaluator-provider variant for answer and judge experiments on an operator machine already logged into Codex with ChatGPT. It uses the official `openai-codex` Python SDK and its pinned app-server runtime. The benchmark never reads Codex's auth file, never receives @@ -827,7 +830,7 @@ compatibility form. The response contains: same-snapshot proven-absent-anchor execution checks when live graph is required; - an overall `ready` that is the conjunction of the requested capabilities; - every non-secret ingestion/query model binding; and -- the non-secret `document_binding_generation`, which Full-v30 requires to be +- the non-secret `document_binding_generation`, which Full-v31 requires to be exactly `document-t0-v1` and stores in `run.json` plus the protocol fingerprint. @@ -976,12 +979,12 @@ Local preparation: uv run --extra benchmark python -m benchmarks.locomo prepare \ --dataset /absolute/path/locomo10.json \ --tier smoke \ - --protocol full-v30 \ + --protocol full-v31 \ --output .benchmark-runs/locomo-smoke ``` -`--protocol` exists only on `prepare`. Canonical runs use `full-v30`; the -explicit `full-v30-gemma-vertex` and `full-v30-codex-subscription` choices are +`--protocol` exists only on `prepare`. Canonical runs use `full-v31`; the +explicit `full-v31-gemma-vertex` and `full-v31-codex-subscription` choices are separately fingerprinted provider variants. Ingest, answer, judge, and summarize read the frozen choice from the prepared run and expose no protocol override. diff --git a/src/rememberstack/profiles/selfhost.py b/src/rememberstack/profiles/selfhost.py index 447247bc7..cbcad1141 100644 --- a/src/rememberstack/profiles/selfhost.py +++ b/src/rememberstack/profiles/selfhost.py @@ -685,7 +685,7 @@ def __init__( raw_store: MinIOObjectStore, artifact_store: MinIOObjectStore, corpusfs_store: MinIOObjectStore, - model_provider: OpenRouterModelProvider, + model_provider: ModelProviderPort, error_telemetry: TelemetryPort | None = None, ) -> None: """Retain one dependency graph for an API, setup, or worker process.""" diff --git a/src/rememberstack/workers/e2.py b/src/rememberstack/workers/e2.py index 51ec673a0..8d8f30c71 100644 --- a/src/rememberstack/workers/e2.py +++ b/src/rememberstack/workers/e2.py @@ -241,17 +241,17 @@ The first label is the origin: a TARGET passage marked origin-eligible that contains the kept proposition. This means it overlaps a Selection keep. Further labels supply support from the target, permitted same-section - neighbours, or cited source-reference-card supporting passages. Cite all + neighbours, or quoted passages under EARLIER REFERENCES. Cite all required support, not just the origin. A larger passage may also contain dropped statements; citing it does not authorize extracting those statements. Never invent a label or character offset. - added_context: each substring added from outside the TARGET CHUNK. Text already in the target needs no entry. Each addition must occur verbatim in the DOCUMENT HEADER, permitted PREVIOUS/NEXT CHUNK, typed LOCATION elements, - or cited source-reference-card supporting passages, except resolved dates - under the rules below. Card names are orientation only and cannot ground an - addition. Mark its origin with header|neighbour|prefix; the tag is advisory - and does not establish support. + or quoted passages under EARLIER REFERENCES that this claim cites, except + resolved dates under the rules below. Reference names help you navigate; + only their quoted source text can support an addition. Mark its origin with + header|neighbour|prefix; the tag is advisory and does not establish support. - entailment_self_verdict: whether the source and permitted context actually support the whole claim, rather than merely containing the same words. - is_attributed: whether the claim records someone's statement or stance. @@ -358,9 +358,11 @@ {passages} -SOURCE REFERENCE CARDS (names are orientation only; never treat a generated -name as evidence. Cite the supporting SOURCE PASSAGES labels. A card cannot -resurrect a dropped proposition or replace the TARGET origin rule): +EARLIER REFERENCES: +Each entry names something discussed earlier in this document and quotes the +source passages that identify it. Use these passages only to clarify a KEPT +proposition. Cite their S labels when needed. Names above the quotes are navigation +hints, not evidence. The claim must still start from an eligible TARGET passage. {cards} KEPT PROPOSITIONS: diff --git a/src/rememberstack/workers/extraction_references.py b/src/rememberstack/workers/extraction_references.py index 96ceaa247..d3ff5b6ad 100644 --- a/src/rememberstack/workers/extraction_references.py +++ b/src/rememberstack/workers/extraction_references.py @@ -84,11 +84,6 @@ def collect_eligible_cards( return tuple(cards) -def card_passage_texts(*, cards: tuple[GroundedCard, ...]) -> tuple[str, ...]: - """Verbatim supporting passage text admitted into D32 layer-2 membership.""" - return tuple(passage.text for card in cards for passage in card.passages) - - def render_selection_passages(*, catalog: PassageCatalog, document_md: str) -> str: """Engine-built local labels Selection may cite; not Claimify origin rules.""" if not catalog.passages: From 9e38625de990d07e2c5b6a3d89eb76509d75d4f1 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 15:07:46 +0200 Subject: [PATCH 10/14] test(e2): drive EXTRACT_CLAIMS then GROUND_CLAIMS in worker tests Adapt existing worker tests to the D122 two-stage contract: Selection freezes on extract_claims, Claimify runs on ground_claims with the same handler, and normalize waits for ground completion. Catalog stubs expose selections and chunks_for_references. --- src/tests/workers/e2_test_doubles.py | 99 +++++++++++++++++++ .../workers/test_claimify_loss_ledger.py | 80 ++++++++++++--- src/tests/workers/test_d119_reuse.py | 67 +++++++------ src/tests/workers/test_e2_chain.py | 27 +++-- .../workers/test_e2_occurrence_provenance.py | 55 ++++++----- src/tests/workers/test_e3_chain.py | 7 ++ .../workers/test_lifecycle_reconciliation.py | 5 + src/tests/workers/test_reuse_lifecycle.py | 91 +++++++++++------ 8 files changed, 327 insertions(+), 104 deletions(-) create mode 100644 src/tests/workers/e2_test_doubles.py diff --git a/src/tests/workers/e2_test_doubles.py b/src/tests/workers/e2_test_doubles.py new file mode 100644 index 000000000..6ce6ecae8 --- /dev/null +++ b/src/tests/workers/e2_test_doubles.py @@ -0,0 +1,99 @@ +"""In-memory Selection freeze and chunk windows for E2 handler unit tests.""" + +from uuid import UUID + +from rememberstack.core.selection_references import CardDiagnostic +from rememberstack.core.selection_references import GroundedCard +from rememberstack.model import ChunkForEmbedding +from rememberstack.model import ChunkSource +from rememberstack.model import ClaimedWork +from rememberstack.model import PipelineStage +from rememberstack.model import SelectionResponse +from rememberstack.spine.selection_catalog import FrozenSelection + + +class SelectionMemory: + """The catalog.selections surface without PostgreSQL.""" + + def __init__(self, *, prior: FrozenSelection | None = None) -> None: + self._rows: dict[UUID, FrozenSelection] = {} + self._prior = prior + + def load(self, *, chunk_id: UUID, extractor_version: str) -> FrozenSelection | None: + del extractor_version + return self._rows.get(chunk_id) + + def preceding( + self, *, chunk_ids: tuple[UUID, ...], extractor_version: str + ) -> dict[UUID, FrozenSelection]: + del extractor_version + return { + chunk_id: self._rows[chunk_id] + for chunk_id in chunk_ids + if chunk_id in self._rows + } + + def prior(self, **_: object) -> FrozenSelection | None: + return self._prior + + def freeze( + self, + *, + deployment_id: UUID, + representation_id: UUID, + chunk_id: UUID, + extractor_version: str, + input_hash: str, + selection: SelectionResponse, + cards: tuple[GroundedCard, ...], + diagnostics: tuple[CardDiagnostic, ...], + truncated: bool, + reused_from: UUID | None = None, + ) -> FrozenSelection: + del deployment_id, representation_id, extractor_version, reused_from + frozen = FrozenSelection( + chunk_id=chunk_id, + input_hash=input_hash, + selection=selection, + cards=cards, + diagnostics=diagnostics, + truncated=truncated, + ) + self._rows[chunk_id] = frozen + return frozen + + +class SingleChunkCatalog: + """One source and one chunk for both extract and reference windows.""" + + def __init__(self, *, source: ChunkSource, chunk: ChunkForEmbedding) -> None: + self.source = source + self.chunk = chunk + + def chunk_source(self, *, representation_id: UUID) -> ChunkSource: + del representation_id + return self.source + + def representation_id_for_chunk(self, *, chunk_id: UUID) -> UUID | None: + del chunk_id + return self.source.representation_id + + def chunks_for_extract( + self, *, representation_id: UUID, chunker_version: str, chunk_id: UUID + ) -> tuple[ChunkForEmbedding, ...]: + del representation_id, chunker_version + return (self.chunk.model_copy(update={"chunk_id": chunk_id}),) + + def chunks_for_references( + self, *, representation_id: UUID, chunker_version: str, chunk_id: UUID + ) -> tuple[ChunkForEmbedding, ...]: + return self.chunks_for_extract( + representation_id=representation_id, + chunker_version=chunker_version, + chunk_id=chunk_id, + ) + + +def with_ground_claims(*, work: ClaimedWork) -> ClaimedWork: + """The same chunk job at GROUND_CLAIMS, after Selection has frozen.""" + return work.model_copy(update={"stage": PipelineStage.GROUND_CLAIMS}) diff --git a/src/tests/workers/test_claimify_loss_ledger.py b/src/tests/workers/test_claimify_loss_ledger.py index a0b14e53f..50e4824df 100644 --- a/src/tests/workers/test_claimify_loss_ledger.py +++ b/src/tests/workers/test_claimify_loss_ledger.py @@ -22,11 +22,15 @@ from rememberstack.model import CandidateClaim from rememberstack.model import ChunkForEmbedding from rememberstack.model import ChunkSource +from rememberstack.model import ClaimedWork from rememberstack.model import ClaimRecord from rememberstack.model import ClaimValidKind from rememberstack.model import ClaimValidPrecision from rememberstack.model import DecisionRecord from rememberstack.model import DecisionType +from rememberstack.model import PipelineStage +from rememberstack.model import ProcessingLane +from rememberstack.model import ProcessingTarget from rememberstack.model import SectionSpan from rememberstack.model import SelectionCandidate from rememberstack.model import SelectionOutcome @@ -38,6 +42,9 @@ from rememberstack.workers.e2 import ExtractClaimsHandler from rememberstack.workers.e2 import GroundingGate from rememberstack.workers.e2 import GroundingRejection +from tests.workers.e2_test_doubles import SelectionMemory +from tests.workers.e2_test_doubles import SingleChunkCatalog +from tests.workers.e2_test_doubles import with_ground_claims if TYPE_CHECKING: from rememberstack.ports.object_store import ObjectStorePort @@ -605,12 +612,36 @@ def test_claimify_omitted_row_for_keep_with_no_returned_claim() -> None: assert decision.protected_class == "date" +class _MemoryStore: + """In-memory artifact store that raises FileNotFoundError like the adapters.""" + + def __init__(self, *, objects: dict[str, bytes]) -> None: + self.objects = objects + + def read_bytes(self, *, key: object) -> bytes: + root = getattr(key, "root", key) + try: + return self.objects[str(root)] + except KeyError as error: + raise FileNotFoundError(str(root)) from error + + class _RecordingCatalog: """Captures record_extraction so handler accounting is directly assertable.""" def __init__(self) -> None: + self.selections = SelectionMemory() self.claims: tuple[ClaimRecord, ...] = () self.decisions: tuple[DecisionRecord, ...] = () + self.occurrences: object = None + + def chunk_already_extracted( + self, *, chunk_id: UUID, extractor_version: str + ) -> bool: + return False + + def prior_extracted_chunk(self, **_: object) -> UUID | None: + return None def record_extraction( self, @@ -618,7 +649,9 @@ def record_extraction( claims: tuple[ClaimRecord, ...], decisions: tuple[DecisionRecord, ...], occurrences: object = None, + claimify_input_hash: str | None = None, ) -> None: + del claimify_input_hash self.claims = claims self.decisions = decisions self.occurrences = occurrences @@ -639,17 +672,29 @@ def _run_extract( claimify: dict[str, object], document_md: str = _DOC_MD, ) -> _RecordingCatalog: - """Drive the REAL handler's per-chunk extraction with canned payloads. + """Drive Selection then Claimify through the real handler with canned payloads. This is the non-vacuous proof Codex asked for: the omission / - no-double-count rules are asserted on what ``_extract_chunk`` actually + no-double-count rules are asserted on what GROUND_CLAIMS actually records, not on hand-rolled reproductions of its loop. """ recorder = _RecordingCatalog() + source = _source() + chunk = _chunk(document_md=document_md) handler = ExtractClaimsHandler( catalog=cast("ClaimCatalog", recorder), - chunk_catalog=cast("ChunkCatalog", object()), - artifact_store=cast("ObjectStorePort", object()), + chunk_catalog=cast( + "ChunkCatalog", SingleChunkCatalog(source=source, chunk=chunk) + ), + artifact_store=cast( + "ObjectStorePort", + _MemoryStore( + objects={ + source.markdown_uri: document_md.encode("utf-8"), + source.blocks_uri: b'{"blockizer_version": "stale", "blocks": []}', + } + ), + ), model_provider=FakeModelProvider( generate_payloads={ "SelectionResponse": selection, @@ -659,15 +704,26 @@ def _run_extract( settings=E2Settings(), chunker_version="test-chunker", ) - chunk = _chunk(document_md=document_md) - handler._extract_chunk( - source=_source(), - chunks=(chunk,), - index=0, - document_md=document_md, - blocks=blockize(document_md=document_md), - meter=NoopCostMeter(), + work = ClaimedWork( + processing_id=chunk.chunk_id, + deployment_id=_DEPLOYMENT, + target_kind=ProcessingTarget.CHUNK, + target_id=chunk.chunk_id, + stage=PipelineStage.EXTRACT_CLAIMS, + component_version="e2-test", + content_hash="hash", + lane=ProcessingLane.STEADY, + attempt=1, + payload={ + "representation_id": str(_REPR), + "version_id": str(_VERSION), + "chunk_id": str(chunk.chunk_id), + }, ) + handler.handle(work=work, meter=NoopCostMeter()) + assert recorder.claims == () + assert recorder.decisions == () + handler.handle(work=with_ground_claims(work=work), meter=NoopCostMeter()) return recorder diff --git a/src/tests/workers/test_d119_reuse.py b/src/tests/workers/test_d119_reuse.py index 566e551e5..541d44595 100644 --- a/src/tests/workers/test_d119_reuse.py +++ b/src/tests/workers/test_d119_reuse.py @@ -18,13 +18,18 @@ from rememberstack.model import ProcessingLane from rememberstack.model import ProcessingTarget from rememberstack.model import SectionSpan +from rememberstack.model import SelectionResponse from rememberstack.model.occurrence_provenance import ReusedClaimAnchor from rememberstack.ports.object_store import ObjectStorePort from rememberstack.spine.chunk_catalog import ChunkCatalog from rememberstack.spine.claim_catalog import ClaimCatalog +from rememberstack.spine.selection_catalog import FrozenSelection from rememberstack.workers import E2Settings from rememberstack.workers.e1 import E2_EXTRACTOR_VERSION from rememberstack.workers.e2 import ExtractClaimsHandler +from tests.workers.e2_test_doubles import SelectionMemory +from tests.workers.e2_test_doubles import SingleChunkCatalog +from tests.workers.e2_test_doubles import with_ground_claims _DEPLOYMENT = UUID("11910000-0000-0000-0000-000000000001") _DOC = UUID("11910000-0000-0000-0000-000000000002") @@ -70,6 +75,16 @@ def __init__(self) -> None: self.attached = 0 self.record_calls = 0 self.reuse_spans: object = None + self.selections = SelectionMemory( + prior=FrozenSelection( + chunk_id=_PRIOR, + input_hash="sha256:same-inputs", + selection=SelectionResponse(candidates=()), + cards=(), + diagnostics=(), + truncated=False, + ) + ) def chunk_already_extracted( self, *, chunk_id: UUID, extractor_version: str @@ -92,7 +107,9 @@ def attach_reused_claims( prior_chunk_id: UUID, occurrences: object = None, evidence_spans: object = None, + claimify_input_hash: str | None = None, ) -> int: + del deployment_id, occurrences, claimify_input_hash self.attached += 1 self.reuse_spans = evidence_spans return len(self.anchors) @@ -106,27 +123,12 @@ def record_extraction( claims: tuple[ClaimRecord, ...], decisions: tuple[DecisionRecord, ...], occurrences: object = None, + claimify_input_hash: str | None = None, ) -> None: + del claims, decisions, occurrences, claimify_input_hash self.record_calls += 1 -class _ChunkCatalogStub: - def __init__(self, *, source: ChunkSource, chunk: ChunkForEmbedding) -> None: - self.source = source - self.chunk = chunk - - def chunk_source(self, *, representation_id: UUID) -> ChunkSource: - return self.source - - def representation_id_for_chunk(self, *, chunk_id: UUID) -> UUID | None: - return self.source.representation_id - - def chunks_for_extract( - self, *, representation_id: UUID, chunker_version: str, chunk_id: UUID - ) -> tuple[ChunkForEmbedding, ...]: - return (self.chunk.model_copy(update={"chunk_id": chunk_id}),) - - def test_reuse_hit_does_not_call_extractor() -> None: """A matching extraction_input_hash remaps spans and never calls the model.""" source = ChunkSource( @@ -170,7 +172,7 @@ def test_reuse_hit_does_not_call_extractor() -> None: handler = ExtractClaimsHandler( catalog=cast("ClaimCatalog", catalog), chunk_catalog=cast( - "ChunkCatalog", _ChunkCatalogStub(source=source, chunk=chunk) + "ChunkCatalog", SingleChunkCatalog(source=source, chunk=chunk) ), artifact_store=cast( "ObjectStorePort", @@ -185,21 +187,22 @@ def test_reuse_hit_does_not_call_extractor() -> None: settings=E2Settings(), chunker_version="test-chunker", ) - handler.handle( - work=ClaimedWork( - processing_id=uuid4(), - deployment_id=_DEPLOYMENT, - target_kind=ProcessingTarget.CHUNK, - target_id=_CHUNK, - stage=PipelineStage.EXTRACT_CLAIMS, - component_version=E2_EXTRACTOR_VERSION, - content_hash="hash", - lane=ProcessingLane.STEADY, - attempt=1, - payload={"representation_id": str(_REPR), "version_id": str(_VERSION)}, - ), - meter=NoopCostMeter(), + work = ClaimedWork( + processing_id=uuid4(), + deployment_id=_DEPLOYMENT, + target_kind=ProcessingTarget.CHUNK, + target_id=_CHUNK, + stage=PipelineStage.EXTRACT_CLAIMS, + component_version=E2_EXTRACTOR_VERSION, + content_hash="hash", + lane=ProcessingLane.STEADY, + attempt=1, + payload={"representation_id": str(_REPR), "version_id": str(_VERSION)}, ) + handler.handle(work=work, meter=NoopCostMeter()) + assert catalog.record_calls == 0 + assert catalog.attached == 0 + handler.handle(work=with_ground_claims(work=work), meter=NoopCostMeter()) assert catalog.record_calls == 0 assert catalog.attached == 1 spans = catalog.reuse_spans diff --git a/src/tests/workers/test_e2_chain.py b/src/tests/workers/test_e2_chain.py index d5b28246e..c8f8936dd 100644 --- a/src/tests/workers/test_e2_chain.py +++ b/src/tests/workers/test_e2_chain.py @@ -257,16 +257,20 @@ def __init__(self, *, engine: Engine, root: Path) -> None: registry.register( stage=PipelineStage.EXTRACT_CLAIMS, handler=self.extract_handler ) + registry.register( + stage=PipelineStage.GROUND_CLAIMS, handler=self.extract_handler + ) self.worker = Worker(ledger=ledger, registry=registry) def run_chain(self) -> None: - """Drive one document through the full chain including extraction.""" + """Drive one document through Selection freeze and Claimify grounding.""" for stage in ( PipelineStage.CONVERT, PipelineStage.STRUCTURE, PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, ): outcome = self.worker.run_one( deployment_id=_DEPLOYMENT_ID, stage=stage, lane=ProcessingLane.STEADY @@ -327,8 +331,9 @@ def test_claims_land_grounded_with_drops_ledgered_and_stance_kept(rig: _E2Rig) - metered_calls = ( connection.execute( text( - "SELECT call_key, model_name, tier, tokens_in, cost_usd" - " FROM cost_ledger WHERE stage = 'extract_claims'" + "SELECT call_key, model_name, tier, tokens_in, cost_usd, stage" + " FROM cost_ledger" + " WHERE stage IN ('extract_claims', 'ground_claims')" " ORDER BY call_key" ) ) @@ -362,7 +367,7 @@ def test_claims_land_grounded_with_drops_ledgered_and_stance_kept(rig: _E2Rig) - assert stance["is_attributed"] # drops, flags, edits, and Claimify-stage rejections are ledgered (D33/#161); - # Selection is enforced — the fused call's attempt to resurrect the dropped + # Selection is enforced — Claimify's attempt to resurrect the dropped # advice span never landed (it becomes grounding_rejected, not a claims row): by_kind = {decision["decision_type"]: decision for decision in decisions} assert set(by_kind) == { @@ -416,6 +421,9 @@ def test_claims_land_grounded_with_drops_ledgered_and_stance_kept(rig: _E2Rig) - ] assert all(call["model_name"] and call["tokens_in"] > 0 for call in metered_calls) assert {call["tier"] for call in metered_calls} == {"decontextualize", "selection"} + by_tier = {call["tier"]: call["stage"] for call in metered_calls} + assert by_tier["selection"] == "extract_claims" + assert by_tier["decontextualize"] == "ground_claims" # Extraction is a measurement surface (#154): selection + claimify must pin # temperature=0.0 so identical bindings do not wander (gold-span coverage # previously varied 7/8 → 4/8 across runs at the provider default). @@ -490,8 +498,9 @@ def test_empty_extraction_is_terminal_and_replays_without_calls( no_info marker makes the replay check hold without re-calling the model. D84: extract_claims is chunk-grain. A document/version-targeted handle only - fans out; Claimify runs on the CHUNK job. This proof drives the chunk grain - directly so the empty-Selection terminal marker and replay stay covered. + fans out; Selection freezes on EXTRACT_CLAIMS and Claimify runs on + GROUND_CLAIMS. This proof drives both chunk jobs so the empty-Selection + terminal marker and replay stay covered. """ rig.ingestor.ingest( deployment_id=_DEPLOYMENT_ID, @@ -557,8 +566,11 @@ def test_empty_extraction_is_terminal_and_replays_without_calls( }, ) handler.handle(work=work, meter=NoopCostMeter()) + assert len(empty_provider.generated_prompts) == 1 # Selection freeze only + ground = work.model_copy(update={"stage": PipelineStage.GROUND_CLAIMS}) + handler.handle(work=ground, meter=NoopCostMeter()) calls_after_first = len(empty_provider.generated_prompts) - assert calls_after_first == 1 # one Selection call, no fused call + assert calls_after_first == 1 # empty keeps skip Claimify with rig.engine.connect() as connection: marker = ( @@ -574,4 +586,5 @@ def test_empty_extraction_is_terminal_and_replays_without_calls( assert marker["decision_type"] == "selection_drop" handler.handle(work=work.model_copy(update={"attempt": 2}), meter=NoopCostMeter()) + handler.handle(work=ground.model_copy(update={"attempt": 2}), meter=NoopCostMeter()) assert len(empty_provider.generated_prompts) == calls_after_first diff --git a/src/tests/workers/test_e2_occurrence_provenance.py b/src/tests/workers/test_e2_occurrence_provenance.py index 211772fd7..d82ab1f92 100644 --- a/src/tests/workers/test_e2_occurrence_provenance.py +++ b/src/tests/workers/test_e2_occurrence_provenance.py @@ -35,6 +35,9 @@ from rememberstack.spine.claim_catalog import ClaimCatalog from rememberstack.workers import E2Settings from rememberstack.workers.e2 import ExtractClaimsHandler +from tests.workers.e2_test_doubles import SelectionMemory +from tests.workers.e2_test_doubles import SingleChunkCatalog +from tests.workers.e2_test_doubles import with_ground_claims _DEPLOYMENT = UUID("84000000-0000-0000-0000-000000000001") _DOC = UUID("84000000-0000-0000-0000-000000000002") @@ -81,6 +84,7 @@ class _RecordingCatalog: """Captures extraction and reuse writes without a database.""" def __init__(self) -> None: + self.selections = SelectionMemory() self.claims: tuple[ClaimRecord, ...] = () self.decisions: tuple[DecisionRecord, ...] = () self.occurrences: dict[UUID, OccurrenceProvenance] | None = None @@ -102,7 +106,10 @@ def prior_extracted_chunk( doc_id: UUID, version_id: UUID, extraction_input_hash: str, + claimify_input_hash: str | None = None, ) -> UUID | None: + del deployment_id, doc_id, version_id, extraction_input_hash + del claimify_input_hash return self.prior def claims_for_occurrence_reuse( @@ -118,7 +125,9 @@ def attach_reused_claims( prior_chunk_id: UUID, occurrences: dict[UUID, OccurrenceProvenance] | None = None, evidence_spans: object = None, + claimify_input_hash: str | None = None, ) -> int: + del deployment_id, evidence_spans, claimify_input_hash self.attached = (chunk_id, prior_chunk_id) self.reuse_occurrences = occurrences return 0 if not self.anchors else len(self.anchors) @@ -132,32 +141,15 @@ def record_extraction( claims: tuple[ClaimRecord, ...], decisions: tuple[DecisionRecord, ...], occurrences: dict[UUID, OccurrenceProvenance] | None = None, + claimify_input_hash: str | None = None, ) -> None: + del claimify_input_hash self.record_calls += 1 self.claims = claims self.decisions = decisions self.occurrences = occurrences -class _ChunkCatalogStub: - """Returns a fixed source and the target chunk window.""" - - def __init__(self, *, source: ChunkSource, chunk: ChunkForEmbedding) -> None: - self.source = source - self.chunk = chunk - - def chunk_source(self, *, representation_id: UUID) -> ChunkSource: - return self.source - - def representation_id_for_chunk(self, *, chunk_id: UUID) -> UUID | None: - return self.source.representation_id - - def chunks_for_extract( - self, *, representation_id: UUID, chunker_version: str, chunk_id: UUID - ) -> tuple[ChunkForEmbedding, ...]: - return (self.chunk.model_copy(update={"chunk_id": chunk_id}),) - - def _source(*, conversion_uri: str | None = _CONVERSION_URI) -> ChunkSource: return ChunkSource( deployment_id=_DEPLOYMENT, @@ -301,7 +293,7 @@ def _handler( return ExtractClaimsHandler( catalog=cast("ClaimCatalog", catalog), chunk_catalog=cast( - "ChunkCatalog", _ChunkCatalogStub(source=source, chunk=chunk) + "ChunkCatalog", SingleChunkCatalog(source=source, chunk=chunk) ), artifact_store=cast("ObjectStorePort", store), model_provider=FakeModelProvider(generate_router=_payloads), @@ -325,7 +317,10 @@ def test_fresh_extract_stamps_ocr_and_description_separately() -> None: ) catalog = _RecordingCatalog() handler = _handler(catalog=catalog, store=store, source=_source()) - handler.handle(work=_work(), meter=NoopCostMeter()) + work = _work() + handler.handle(work=work, meter=NoopCostMeter()) + assert catalog.record_calls == 0 + handler.handle(work=with_ground_claims(work=work), meter=NoopCostMeter()) assert catalog.record_calls == 1 assert catalog.occurrences is not None by_span = { @@ -355,8 +350,10 @@ def test_missing_conversion_manifest_does_not_persist_claims() -> None: objects=_with_blocks({_MARKDOWN_URI: _DOCUMENT.encode("utf-8")}) ) handler = _handler(catalog=catalog, store=store, source=_source()) + work = _work() + handler.handle(work=work, meter=NoopCostMeter()) with pytest.raises(ProvenanceMetadataMissingError, match="conversion manifest"): - handler.handle(work=_work(), meter=NoopCostMeter()) + handler.handle(work=with_ground_claims(work=work), meter=NoopCostMeter()) assert catalog.record_calls == 0 assert catalog.claims == () @@ -370,8 +367,10 @@ def test_corrupt_conversion_manifest_is_terminal_and_persists_nothing() -> None: ) ) handler = _handler(catalog=catalog, store=store, source=_source()) + work = _work() + handler.handle(work=work, meter=NoopCostMeter()) with pytest.raises(NonRetryableHandlerError, match="corrupt"): - handler.handle(work=_work(), meter=NoopCostMeter()) + handler.handle(work=with_ground_claims(work=work), meter=NoopCostMeter()) assert catalog.record_calls == 0 @@ -387,8 +386,10 @@ def test_missing_referenced_source_map_does_not_persist_claims() -> None: ) ) handler = _handler(catalog=catalog, store=store, source=_source()) + work = _work() + handler.handle(work=work, meter=NoopCostMeter()) with pytest.raises(ProvenanceMetadataMissingError, match="source map"): - handler.handle(work=_work(), meter=NoopCostMeter()) + handler.handle(work=with_ground_claims(work=work), meter=NoopCostMeter()) assert catalog.record_calls == 0 @@ -419,7 +420,11 @@ def test_reuse_resolves_against_target_chunk_not_prior_coordinates() -> None: ), ) handler = _handler(catalog=catalog, store=store, source=_source()) - handler.handle(work=_work(), meter=NoopCostMeter()) + work = _work() + handler.handle(work=work, meter=NoopCostMeter()) + assert catalog.record_calls == 0 + assert catalog.attached is None + handler.handle(work=with_ground_claims(work=work), meter=NoopCostMeter()) assert catalog.record_calls == 0 assert catalog.attached == (_CHUNK, _PRIOR) assert catalog.reuse_occurrences is not None diff --git a/src/tests/workers/test_e3_chain.py b/src/tests/workers/test_e3_chain.py index 334a9167b..1d9ea2337 100644 --- a/src/tests/workers/test_e3_chain.py +++ b/src/tests/workers/test_e3_chain.py @@ -306,6 +306,10 @@ def route(prompt: str, type_name: str) -> dict[str, object]: chunker_version=chunker_version(params=_PARAMS), ), ) + registry.register( + stage=PipelineStage.GROUND_CLAIMS, + handler=registry.handler_for(stage=PipelineStage.EXTRACT_CLAIMS), + ) registry.register( stage=PipelineStage.NORMALIZE_RELATIONS, handler=self.normalize_handler ) @@ -381,6 +385,7 @@ def run_chain(self) -> None: PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, PipelineStage.NORMALIZE_RELATIONS, PipelineStage.ADJUDICATE_OBSERVATIONS, PipelineStage.ADJUDICATE_SUPERSESSION, @@ -528,6 +533,7 @@ def test_empty_document_completes_the_same_terminal_pipeline_without_model_calls PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, PipelineStage.NORMALIZE_RELATIONS, PipelineStage.ADJUDICATE_OBSERVATIONS, PipelineStage.ADJUDICATE_SUPERSESSION, @@ -540,6 +546,7 @@ def test_empty_document_completes_the_same_terminal_pipeline_without_model_calls ).outcome if stage in ( PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, PipelineStage.NORMALIZE_RELATIONS, # D90: empty path is durable empty_complete — no document_version # adjudicate_observations work row at the entity-fanout generation. diff --git a/src/tests/workers/test_lifecycle_reconciliation.py b/src/tests/workers/test_lifecycle_reconciliation.py index f7ebf0ee9..3f5bd0f20 100644 --- a/src/tests/workers/test_lifecycle_reconciliation.py +++ b/src/tests/workers/test_lifecycle_reconciliation.py @@ -104,6 +104,7 @@ PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, PipelineStage.NORMALIZE_RELATIONS, PipelineStage.ADJUDICATE_OBSERVATIONS, PipelineStage.ADJUDICATE_SUPERSESSION, @@ -304,6 +305,10 @@ def __init__(self, *, engine: Engine, root: Path) -> None: chunker_version=chunker_version(params=_PARAMS), ), ) + registry.register( + stage=PipelineStage.GROUND_CLAIMS, + handler=registry.handler_for(stage=PipelineStage.EXTRACT_CLAIMS), + ) facts = FactCatalog(engine=engine) obs_adjudicator = FactAdjudicator( engine=engine, diff --git a/src/tests/workers/test_reuse_lifecycle.py b/src/tests/workers/test_reuse_lifecycle.py index 099fe6795..c37845f06 100644 --- a/src/tests/workers/test_reuse_lifecycle.py +++ b/src/tests/workers/test_reuse_lifecycle.py @@ -76,6 +76,7 @@ PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, ) _TARGET_PATTERN = re.compile(r"TARGET CHUNK:\n(.+)") @@ -235,6 +236,10 @@ def __init__(self, *, engine: Engine, root: Path) -> None: chunker_version=chunker_version(params=_PARAMS), ), ) + registry.register( + stage=PipelineStage.GROUND_CLAIMS, + handler=registry.handler_for(stage=PipelineStage.EXTRACT_CLAIMS), + ) self.worker = Worker( ledger=WorkLedger( engine=engine, @@ -400,37 +405,58 @@ def test_summary_change_keeps_hash_and_reuses_unchanged_chunks(rig: _ReuseRig) - text("SELECT count(*) FROM chunks WHERE version_id = :version_id"), {"version_id": second.version_id}, ).scalar_one() - reused = ( - connection.execute( - text( - "SELECT c2.extraction_input_hash AS second_hash," - " c1.extraction_input_hash AS first_hash" - " FROM chunks c2" - " JOIN chunks c1" - " ON c1.doc_id = c2.doc_id" - " AND c1.extraction_input_hash = c2.extraction_input_hash" - " WHERE c1.version_id = :first_version" - " AND c2.version_id = :second_version" - " AND EXISTS (SELECT 1 FROM chunk_claims cc" - " WHERE cc.chunk_id = c2.chunk_id)" - " AND NOT EXISTS (SELECT 1 FROM claims cl" - " WHERE cl.chunk_id = c2.chunk_id)" - ), - { - "first_version": first.version_id, - "second_version": second.version_id, - }, - ) - .mappings() - .all() - ) + versions = { + "first_version": first.version_id, + "second_version": second.version_id, + } + hash_new = connection.execute( + text( + "SELECT count(*) FROM chunks c2 WHERE c2.version_id = :second_version" + " AND NOT EXISTS (" + " SELECT 1 FROM chunks c1 WHERE c1.doc_id = c2.doc_id" + " AND c1.version_id = :first_version" + " AND c1.extraction_input_hash = c2.extraction_input_hash)" + ), + versions, + ).scalar_one() + claimify_reused = connection.execute( + text( + "SELECT count(*) FROM chunks c2" + " JOIN chunks c1 ON c1.doc_id = c2.doc_id" + " AND c1.extraction_input_hash = c2.extraction_input_hash" + " WHERE c1.version_id = :first_version" + " AND c2.version_id = :second_version" + " AND EXISTS (SELECT 1 FROM chunk_claims cc" + " WHERE cc.chunk_id = c2.chunk_id)" + " AND NOT EXISTS (SELECT 1 FROM claims cl" + " WHERE cl.chunk_id = c2.chunk_id)" + ), + versions, + ).scalar_one() + claimify_rerun = connection.execute( + text( + "SELECT count(*) FROM chunks c2" + " JOIN chunks c1 ON c1.doc_id = c2.doc_id" + " AND c1.extraction_input_hash = c2.extraction_input_hash" + " WHERE c1.version_id = :first_version" + " AND c2.version_id = :second_version" + " AND EXISTS (SELECT 1 FROM claims cl" + " WHERE cl.chunk_id = c2.chunk_id)" + ), + versions, + ).scalar_one() assert first_summary == "The original reuse-spike document." assert second_summary == "The edited reuse-spike document." - # Reuse breadth, not a tautology (review): every v2 chunk either reused a - # v1 extraction (rows here) or was freshly selected (selection_v2). - assert len(reused) == v2_chunk_count - selection_v2 + # D122 splits reuse: Selection follows extraction_input_hash, Claimify also + # hashes the previous-eight Selection producers. Every v2 chunk is one of + # freshly selected, Selection-reused+Claimify-reused, or Selection-reused + # with Claimify re-run because a preceding producer changed. + assert hash_new + claimify_reused + claimify_rerun == v2_chunk_count + assert hash_new == selection_v2 assert 0 < selection_v2 < v2_chunk_count + assert claimify_reused > 0 + assert claimify_rerun > 0 def test_reused_chunks_carry_identical_claims_and_prefixes(rig: _ReuseRig) -> None: @@ -460,6 +486,7 @@ def test_reused_chunks_carry_identical_claims_and_prefixes(rig: _ReuseRig) -> No .all() ) assert pairs, "the edit must leave unchanged chunks to pair up" + claimify_reused = 0 for pair in pairs: assert pair["new_prefix"] == pair["old_prefix"] # byte-identical old_claims = set( @@ -474,7 +501,15 @@ def test_reused_chunks_carry_identical_claims_and_prefixes(rig: _ReuseRig) -> No {"c": pair["new_chunk"]}, ).scalars() ) - assert new_claims == old_claims # same immutable claims, re-attached + minted = connection.execute( + text("SELECT count(*) FROM claims WHERE chunk_id = :c"), + {"c": pair["new_chunk"]}, + ).scalar_one() + if minted == 0: + assert new_claims == old_claims # Claimify reuse: same ids + assert new_claims + claimify_reused += 1 + assert claimify_reused > 0 def test_reuse_never_crosses_into_the_same_version(rig: _ReuseRig) -> None: From e7553a1ac3de0db03d02237e2988c0923bcd6fb6 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 15:11:05 +0200 Subject: [PATCH 11/14] fix(processing): satisfy review checks and prove late-forget protection --- .../d122_d123_agy_review_2c547937.md | 183 ++++++++++++++++++ ...123_document_reference_context_20260914.md | 32 +++ .../core/concise_adjudication.py | 2 +- src/tests/database_reset.py | 7 +- .../spine/test_d123_context_nomination.py | 3 +- src/tests/spine/test_forget_catalog.py | 109 +++++++++++ src/tests/workers/e3_test_doubles.py | 3 +- 7 files changed, 330 insertions(+), 9 deletions(-) create mode 100644 plan/implementation_evals/d122_d123_agy_review_2c547937.md diff --git a/plan/implementation_evals/d122_d123_agy_review_2c547937.md b/plan/implementation_evals/d122_d123_agy_review_2c547937.md new file mode 100644 index 000000000..727d350ce --- /dev/null +++ b/plan/implementation_evals/d122_d123_agy_review_2c547937.md @@ -0,0 +1,183 @@ +# Antigravity Runtime Review: Checkpoint 2c547937 + +- **Target Repository:** `/Users/jpuc/code/moje/ultimate_memory/ugm-document-context` +- **Reviewed Checkpoint SHA:** `2c547937dabe1025254be077431f0a963b1ef700` (`2c547937`) +- **Diff Baseline:** `b575c5567ab87f7225b43fe271ba9b36019ce08f..2c547937dabe1025254be077431f0a963b1ef700` +- **PR:** #403 +- **Binding Specifications:** + - [D122: Stable source references shared during document extraction](../../plan/designs/document_reference_context_design.md) + - [D123: Source-backed entity context for fact nomination](../../plan/designs/contextual_fact_nomination_design.md) +- **Review Date:** 2026-09-14 +- **Verdict:** **Approved with material typecheck fixes required** (Runtime implementation and core mechanics are correct, robust, and adhere to D122/D123 design invariants; two Pyright static typing failures must be resolved prior to final PR merge). + +--- + +## Executive Summary + +The runtime diff `b575c556..2c547937` implements the complete two-phase extraction architecture (D122) and contextual fact nomination (D123) without introducing speculative machinery, third model calls, new event tables, per-fact event columns, or date windows. + +The implementation cleanly splits E2 across existing pipeline stages: +1. `EXTRACT_CLAIMS` executes Selection only: identifies propositions and source-backed referents, saves the full validated response once into `selection_results`, and fences publication against concurrent hard-forget. +2. `GROUND_CLAIMS` runs Claimify after a transactional representation barrier confirms that all chunk Selection results exist. It bounds preceding referents to whole cards within the previous 8 chunks, caps formatted card text at 4,096 characters, and completes zero-keep chunks deterministically with zero model calls. +3. Version reuse enforces negative dependencies by including the ordered Selection input hashes of all preceding 8 chunk producers (including zero-card producers) in `claimify_input_hash`. +4. Contextual fact nomination (D123) preserves the existing same-subject 20-fact baseline, adds up to 8 extra facts sharing current positive testimony context, excludes canonical subject closures, and includes all bindings, memberships, and reverse closures in the full internal snapshot fingerprint. +5. Lifecycle cycle finalization and pipeline readiness derive status from both `EXTRACT_CLAIMS` and `GROUND_CLAIMS`, preventing premature pipeline completion. + +--- + +## Verification of Parent Review Items + +Parent previously identified five integration requirements. All five were verified in `2c547937`: + +1. **Removed Own-Target Cards:** + - In [`collect_eligible_cards`](../../src/rememberstack/workers/extraction_references.py#L77-L85) and [`preceding_producer_ids`](../../src/rememberstack/workers/extraction_references.py#L54-L62), producer selection strictly enforces `target.ordinal - 8 <= chunk.ordinal < target.ordinal`. + - The target chunk's own cards are excluded from the reference set supplied to Claimify, as the target chunk already supplies local text directly. + - **Status:** Verified. + +2. **Duplicate Evidence Render Prevented:** + - In [`ExtractClaimsHandler._claimify_chunk`](../../src/rememberstack/workers/e2.py#L820-L840), the prompt formats `passages` using `local_catalog` (target and local neighbor passages only), and `cards` using `render_cards_for_claimify(cards=fitted)`. + - Card passages are not rendered in the `SOURCE PASSAGES` block and then duplicated under `SOURCE REFERENCE CARDS`. + - **Status:** Verified. + +3. **Assigned Final Labels Before 4,096-Character Cap:** + - In [`ExtractClaimsHandler._claimify_chunk`](../../src/rememberstack/workers/e2.py#L798-L815), [`attach_card_passages`](../../src/rememberstack/workers/extraction_references.py#L106-L150) generates request-unique labels `S{next_index}` *before* [`rank_and_fit_cards`](../../src/rememberstack/core/selection_references.py#L273-L300) measures rendered character length. + - `rank_and_fit_cards` evaluates `len(render_cards_for_claimify(cards=candidate)) > max_chars` against the actual formatted string containing those final labels. + - **Status:** Verified. + +4. **Requires Cited Reference Support for `added_context`:** + - In [`ExtractClaimsHandler._claimify_chunk`](../../src/rememberstack/workers/e2.py#L870-L878), `card_passage_texts` is populated *only* for card passages whose label appears in `candidate.source_refs`: + ```python + card_passage_texts=tuple( + passage.text + for card in fitted + for passage in card.passages + if passage.label in candidate.source_refs + ) + ``` + - Uncited card passages cannot contribute to `_source_grounding_elements`, and any unanchored addition triggers `GroundingGate.ADDED_CONTEXT_UNVERIFIED`. + - **Status:** Verified. + +5. **Fixed Readiness and Lifecycle to Include `GROUND_CLAIMS`:** + - In [`PipelineReadinessCatalog`](../../src/rememberstack/spine/readiness.py#L109-L135), `_EXTRACT_CHUNK_STATUS` queries both `PipelineStage.EXTRACT_CLAIMS` and `PipelineStage.GROUND_CLAIMS`. + - In [`lifecycle.py`](../../src/rememberstack/spine/lifecycle.py#L1092-L1096), `_SELECT_READY_CYCLES` requires `w.stage IN ('extract_claims', 'ground_claims')`. + - Selection completion alone cannot finalize a sync cycle or mark the pipeline ready. + - **Status:** Verified. + +--- + +## Detailed Findings + +### [High / Material] Pyright Typecheck Failures in `concise_adjudication.py` +- **Path:** [`src/rememberstack/core/concise_adjudication.py`](../../src/rememberstack/core/concise_adjudication.py#L248-L250) (lines 248, 432) +- **Impact:** Static type check failure; will fail CI `pyright` checks. +- **Root Cause:** + In [`project_concise_inputs`](../../src/rememberstack/core/concise_adjudication.py#L188): + ```python + assertion_rows = list(snapshot.get("assertions", ())) + ``` + Because `snapshot` is typed as `Mapping[str, Any]` and the default value is `()`, Pyright infers `assertion_rows` as `list[Never]`. Consequently: + - Line 248: `for context in row.get("context_entities", ()):` triggers `error: "Never" is not iterable (reportGeneralTypeIssues)`. + - Line 432: `for context in row["context_entities"]` triggers `error: "Never" is not iterable (reportGeneralTypeIssues)`. +- **Recommendation:** + Explicitly annotate or cast `assertion_rows`, or default with a typed list: + ```python + assertion_rows: list[dict[str, Any]] = list(snapshot.get("assertions", [])) + ``` + +### [Medium] Pyright Typecheck Failures in `test_d123_context_nomination.py` +- **Path:** [`src/tests/spine/test_d123_context_nomination.py`](../../src/tests/spine/test_d123_context_nomination.py#L58) (lines 172, 184, 213, 214, 253) +- **Impact:** Test file typecheck failure. +- **Root Cause:** + Helper function `_snapshot` is annotated as: + ```python + def _snapshot(*, engine: Engine, case: WriterCase, app: UUID) -> dict[str, object]: + ``` + Because the return value is typed as `dict[str, object]`, accessing `snapshot["facts"]` or `snapshot["limits"]` produces `object`, which Pyright flags with: + - `"object" is not iterable` + - `"__getitem__" method not defined on type "object"` + - `Operator "in" not supported for types "str" and "object"` +- **Recommendation:** + Change the return annotation of `_snapshot` to `dict[str, Any]`, matching the return signature of [`application_snapshot`](../../src/rememberstack/spine/fact_application_inputs.py). + +### [Low / Integration Note] Component Version Suffix Alignment with Benchmark Protocol +- **Path:** [`benchmarks/locomo/protocol.py`](../../benchmarks/locomo/protocol.py#L79-L90) vs [`src/rememberstack/spine/fact_adjudication.py`](../../src/rememberstack/spine/fact_adjudication.py#L33-L45) +- **Context:** + In `fact_adjudication.py`, `FACT_NORMALIZER_VERSION` and `RELATION_APPLICATION_VERSION` were bumped to `:d123-context-refs-2` and `:d123-context-nom-2`. In `protocol.py`, these entries currently carry `:d123-context-refs-1` and `:d123-context-nom-1`. +- **Note:** + As noted in `/tmp/ugm-d122-d123-grok-20260914/protocol-task.txt`, the concurrent protocol update task is already designated to regenerate Full-v31 pins from these runtime constants. No action is required in runtime code. + +--- + +## Architectural & Invariant Analysis + +### 1. Frozen Selection & Representation Barrier +- Selection results are stored in `selection_results` via [`SelectionCatalog.freeze`](../../src/rememberstack/spine/selection_catalog.py#L146-L208). +- First-writer-wins is guaranteed via PostgreSQL `ON CONFLICT (deployment_id, chunk_id, extractor_version) DO NOTHING`, followed by re-reading the committed row and asserting identical `selection_input_hash`. +- Zero-keep Selection results successfully publish their cards for use by other chunks and complete Claimify with 0 model calls. +- In [`WorkLedger.complete_chunk_selection`](../../src/rememberstack/spine/work_ledger.py#L255-L330), representation advisory locks ensure that `_SELECTION_BARRIER_MISSING` evaluates atomically, transitioning chunks to `PipelineStage.GROUND_CLAIMS` only once all representations' chunk selections are frozen. + +### 2. Multi-Span Version Reuse & Negative Dependencies +- [`claimify_input_hash`](../../src/rememberstack/core/selection_references.py#L66-L84) hashes: + 1. `target_selection_input_hash` + 2. All preceding Selection input hashes (ordered by chunk ordinal) across the 8-chunk window, including chunks that yielded zero cards + 3. `policy_version` +- This ensures that editing an earlier chunk—even one that previously emitted no cards—changes the input hash and correctly invalidates Claimify reuse. +- Offset remapping for reused occurrence evidence ranges uses fixed relative slots `target - 9 .. target + 1` ([`reference_windows`](../../src/rememberstack/workers/extraction_references.py#L38-L52)), ensuring that preceding cards that cited their previous neighbor remain unambiguously mappable. + +### 3. Privacy, Hard-Forget, and Replay Guards +- All publication paths ([`SelectionCatalog.freeze`](../../src/rememberstack/spine/selection_catalog.py#L169), [`ClaimCatalog.record_extraction`](../../src/rememberstack/spine/claim_catalog.py#L318), [`ClaimCatalog.attach_reused_claims`](../../src/rememberstack/spine/claim_catalog.py#L140), and [`WorkLedger.complete_chunk_selection`](../../src/rememberstack/spine/work_ledger.py#L274)) invoke [`require_extraction_sources_on`](../../src/rememberstack/spine/selection_catalog.py#L33-L62). +- This acquires `pg_advisory_xact_lock_shared` on `hard-forget:{deployment_id}`, checks for active forget operations, and locks documents and representations `FOR SHARE`. +- `_POSTGRES_SCRUB` in [`forget.py`](../../src/rememberstack/spine/forget.py#L1188) deletes from `selection_results` and cascades `application_context_bindings`. +- `_VERIFY_POSTGRES_SCRUB` validates that neither `selection_results` nor `application_context_bindings` retain rows for forgotten sources. + +### 4. Contextual Fact Nomination Semantics (D123) +- Normalizer captures up to 4 context references per assertion ([`attempted_context_refs`](../../src/rememberstack/core/context_references.py#L20-L33)). Extra references are recorded as truncated on the frozen output and do not fail the assertion. +- Context references are resolved through the standard resolver and staged atomically with the application and version rows in [`FactApplicationCatalog.stage`](../../src/rememberstack/spine/fact_applications.py#L254-L352). +- Staging verifies a live resolver decision for the claim and entity (`superseded_by IS NULL` and mention matches claim). +- Candidate nomination in [`application_snapshot`](../../src/rememberstack/spine/fact_application_inputs.py#L175-L235): + - Retains the exact 20-fact baseline. + - Queries up to 8 additional candidates whose supporting applications share context, explicitly filtering `NOT f.{id_column} = ANY(baseline_ids)`. + - Enforces positive current testimony (`support_stance = 'supports'` and `is_current_testimony = true`). + - Excludes the canonical subject closure from matching context. + - Merges into at most 28 candidates, ordering shared-context candidates first for concise model presentation. +- Snapshot validation recalculates candidate nomination under row locks; changes raise `ApplicationInputChanged`. + +--- + +## Checks Executed + +The following checks were executed directly against checkpoint `2c547937` without modifying repository files and without touching PostgreSQL instances (ports 55441 and 55442 preserved for concurrent runs): + +1. **Ruff Linter:** + ```bash + uv run ruff check src/rememberstack/core/selection_references.py src/rememberstack/core/context_references.py src/rememberstack/core/concise_adjudication.py src/rememberstack/spine/selection_catalog.py src/rememberstack/spine/fact_application_inputs.py src/rememberstack/spine/fact_applications.py src/rememberstack/spine/fact_adjudication.py src/rememberstack/spine/work_ledger.py src/rememberstack/spine/chunk_catalog.py src/rememberstack/spine/claim_catalog.py src/rememberstack/spine/readiness.py src/rememberstack/spine/lifecycle.py src/rememberstack/spine/forget.py src/rememberstack/workers/e2.py src/rememberstack/workers/e3.py src/rememberstack/workers/extraction_references.py + ``` + **Result:** `All checks passed!` + +2. **Pyright Typechecker (Runtime Files):** + - Ran across all 16 changed runtime files. + - 15 files passed with **0 errors, 0 warnings**. + - `src/rememberstack/core/concise_adjudication.py` reported 2 errors (detailed in Findings). + +3. **Pyright Typechecker (Unit Tests):** + - `src/tests/core/test_selection_references.py`, `test_context_references.py`, `test_concise_adjudication.py`, `src/tests/workers/test_e3_context_references.py`: **0 errors, 0 warnings**. + - `src/tests/spine/test_d123_context_nomination.py`: 5 errors due to `dict[str, object]` annotation (detailed in Findings). + +4. **Pytest (Unit Test Suites):** + ```bash + uv run pytest src/tests/core/test_selection_references.py src/tests/core/test_context_references.py src/tests/core/test_concise_adjudication.py src/tests/workers/test_e3_context_references.py + ``` + **Result:** **35 passed in 8.78s**. + + ```bash + uv run pytest src/tests/workers/test_e3_bare_head_noun.py src/tests/workers/test_e3_claim_normalize_fanout.py src/tests/benchmarks/test_locomo_protocol.py + ``` + **Result:** **70 passed in 16.98s**. + +--- + +## Conclusion + +The runtime diff `b575c556..2c547937` fulfills the functional, structural, and privacy requirements of D122 and D123. The design is lean, avoids speculative architecture, correctly coordinates the E2 split across the work ledger and readiness catalogs, and strictly enforces source grounding and negative version dependencies. + +Addressing the two Pyright type annotations in [`src/rememberstack/core/concise_adjudication.py`](../../src/rememberstack/core/concise_adjudication.py#L188) and [`src/tests/spine/test_d123_context_nomination.py`](../../src/tests/spine/test_d123_context_nomination.py#L58) will leave the codebase ready for final-head integration and main rebase. diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md index fa2225181..0289c37b4 100644 --- a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -185,3 +185,35 @@ Existing worker fixtures and Full-v31 benchmark pins are being updated in bounded Grok tasks. Final Antigravity review, exact-head CI, main rebase and parent merge review remain outstanding. No live processing quality/cost result is claimed before the authorized Gemma/Vertex conv-42 run. + +## Final integration checks before main rebase + +Grok completed and pushed the worker fixtures (`93f3acfc`) and Full-v31 pins +(`c275d724`). The worker lane passed46 PostgreSQL-free tests and30 PostgreSQL +chain/reuse cases (28 initially, the remaining2 after updating the explicit +Selection-reuse versus full-Claimify-reuse expectations). The protocol lane +passed184 benchmark unit tests, Ruff and Pyright. Its serialized synthetic +prepare fingerprint is +`ee7d277f10e9b7d486f75f5221a7a174386248c3b5fc79c60815bcb7be1700b3`. +This fingerprint is not a live processing run. + +[Antigravity's runtime review](d122_d123_agy_review_2c547937.md) found no runtime +or design blocker, but required two type annotation fixes. Parent applied +explicit assertion-row typing and aligned the test snapshot annotation with +the existing dynamic snapshot API. The full type pass additionally identified +an overly broad UUID annotation in an E3 test double; that was narrowed to UUID. +The remaining protocol suffix note is resolved by the Full31 pin commit. + +Parent's further PostgreSQL context and hard-forget suite passed15 tests +(54.52 seconds). It proves both new source stores are scrubbed while independent +control data survives, repeated scrubs remain idempotent, and the actual +Selection and Claimify publication APIs reject a late response after forget +starts. The59 core/profile unit tests passed (34.58 seconds). Repository test +inventory and all five import-boundary contracts pass. + +The final wording names the earlier evidence block “EARLIER REFERENCES” and +explains what its names, quotes and citations mean. SelfHostProfile's injectable +provider is typed as its existing ModelProviderPort; its convenience constructor +and production defaults are unchanged. This lets an isolated experiment compose +existing providers honestly without pretending a reader-only Gemma variant +configures processing. diff --git a/src/rememberstack/core/concise_adjudication.py b/src/rememberstack/core/concise_adjudication.py index 89644ff00..075f45bdb 100644 --- a/src/rememberstack/core/concise_adjudication.py +++ b/src/rememberstack/core/concise_adjudication.py @@ -185,7 +185,7 @@ def project_concise_inputs( """ fact_rows = list(snapshot.get("facts", ())) claim_rows = list(snapshot.get("claims", ())) - assertion_rows = list(snapshot.get("assertions", ())) + assertion_rows: list[dict[str, Any]] = list(snapshot.get("assertions", ())) facts = { _handle("F", index): _as_id(row["fact_id"]) for index, row in enumerate(fact_rows) diff --git a/src/tests/database_reset.py b/src/tests/database_reset.py index 1a24ff442..d2125c983 100644 --- a/src/tests/database_reset.py +++ b/src/tests/database_reset.py @@ -34,12 +34,7 @@ def reset_database(*, config: Config) -> None: text("SELECT version_num FROM alembic_version") ).scalar_one_or_none() if ( - revision - in { - "p9_30_0051", - "p9_31_0052", - "p9_32_0053", - } + revision in {"p9_30_0051", "p9_31_0052", "p9_32_0053"} or connection.execute( text("SELECT to_regclass('public.fact_applications') IS NOT NULL") ).scalar_one() diff --git a/src/tests/spine/test_d123_context_nomination.py b/src/tests/spine/test_d123_context_nomination.py index e7647b3f8..3c5784515 100644 --- a/src/tests/spine/test_d123_context_nomination.py +++ b/src/tests/spine/test_d123_context_nomination.py @@ -2,6 +2,7 @@ from collections.abc import Iterator from pathlib import Path +from typing import Any from uuid import UUID from uuid import uuid4 @@ -55,7 +56,7 @@ def _tournament(*, engine: Engine, case: WriterCase) -> UUID: return entity_id -def _snapshot(*, engine: Engine, case: WriterCase, app: UUID) -> dict[str, object]: +def _snapshot(*, engine: Engine, case: WriterCase, app: UUID) -> dict[str, Any]: """Re-read nomination inputs under the ordinary application lock.""" with engine.begin() as connection: with application_block( diff --git a/src/tests/spine/test_forget_catalog.py b/src/tests/spine/test_forget_catalog.py index 7e6cc5512..a755e4ab2 100644 --- a/src/tests/spine/test_forget_catalog.py +++ b/src/tests/spine/test_forget_catalog.py @@ -18,13 +18,19 @@ from rememberstack.adapters.testing import FakeModelProvider from rememberstack.core.embedding_input_policy import embedding_text_hash +from rememberstack.model import DecisionRecord +from rememberstack.model import DecisionType from rememberstack.model import DeploymentBootstrapInput +from rememberstack.model import ForgetInProgressError from rememberstack.model import ForgetManifest from rememberstack.model import ForgetManifestStatus +from rememberstack.model import SelectionResponse from rememberstack.ports import ForgetManifestPort +from rememberstack.spine import ClaimCatalog from rememberstack.spine import DeploymentBootstrapper from rememberstack.spine import EntityProfileRefresher from rememberstack.spine import ForgetCatalog +from rememberstack.spine.selection_catalog import SelectionCatalog from rememberstack.spine.settings import load_database_settings from rememberstack.workers import HardForgetHandler from rememberstack.workers import HardForgetReadiness @@ -1447,6 +1453,40 @@ def test_mutable_fact_payloads_and_date_witnesses_are_erased( "phrase": _TOKEN, }, ) + for chunk, representation, phrase, app in ( + (_TARGET_CHUNK_ID, _TARGET_REPRESENTATION_ID, _TOKEN, own), + ( + _CONTROL_CHUNK_ID, + _CONTROL_REPRESENTATION_ID, + "independent reference", + surviving, + ), + ): + connection.execute( + text("""INSERT INTO selection_results + (deployment_id,chunk_id,representation_id,extractor_version, + selection_input_hash,output,cards) + VALUES (:dep,:chunk,:rep,'forget-test','hash', + jsonb_build_object('source',CAST(:phrase AS text)), + jsonb_build_array(jsonb_build_object('quote',CAST(:phrase AS text))))"""), + { + "dep": _DEPLOYMENT_ID, + "chunk": chunk, + "rep": representation, + "phrase": phrase, + }, + ) + connection.execute( + text("""INSERT INTO application_context_bindings + (deployment_id,application_id,ordinal,entity_id,resolver_decision_id) + VALUES (:dep,:app,0,:entity,:decision)"""), + { + "dep": _DEPLOYMENT_ID, + "app": app, + "entity": _SHARED_ENTITY_ID, + "decision": uuid4(), + }, + ) connection.execute( text("""UPDATE observations SET valid_from='2022-01-01Z', valid_until='2023-01-01Z',valid_precision='year',window_claim_ids=CAST(:claims AS uuid[]) @@ -1465,6 +1505,16 @@ def test_mutable_fact_payloads_and_date_witnesses_are_erased( ).scalar_one() == 0 ) + assert connection.execute( + text("SELECT chunk_id FROM selection_results WHERE deployment_id=:dep"), + {"dep": _DEPLOYMENT_ID}, + ).scalars().all() == [_CONTROL_CHUNK_ID] + assert connection.execute( + text( + "SELECT application_id FROM application_context_bindings WHERE deployment_id=:dep" + ), + {"dep": _DEPLOYMENT_ID}, + ).scalars().all() == [surviving] row = connection.execute( text( "SELECT attempt_id,prepared,decision,input_claim_ids FROM fact_applications WHERE application_id=:id" @@ -1480,3 +1530,62 @@ def test_mutable_fact_payloads_and_date_witnesses_are_erased( ).one() assert tuple(row[:4]) == (None, None, "unknown", []) assert _TOKEN not in row[4] + + +@pytest.mark.parametrize("phase", ("selection", "claimify")) +def test_late_extraction_response_cannot_publish_after_forget_starts( + seeded_engine: Engine, phase: str +) -> None: + """Both actual publication APIs reject a response after forget was prepared.""" + catalog = ForgetCatalog(engine=seeded_engine) + catalog.prepare( + deployment_id=_DEPLOYMENT_ID, doc_id=_TARGET_DOC_ID, forget_id=_FORGET_ID + ) + with pytest.raises(ForgetInProgressError): + if phase == "selection": + SelectionCatalog(engine=seeded_engine).freeze( + deployment_id=_DEPLOYMENT_ID, + representation_id=_TARGET_REPRESENTATION_ID, + chunk_id=_TARGET_CHUNK_ID, + extractor_version="forget-test", + input_hash="hash", + selection=SelectionResponse(candidates=()), + cards=(), + diagnostics=(), + truncated=False, + ) + else: + ClaimCatalog(engine=seeded_engine).record_extraction( + claims=(), + decisions=( + DecisionRecord( + decision_id=_FORGET_ID, + deployment_id=_DEPLOYMENT_ID, + doc_id=_TARGET_DOC_ID, + chunk_id=_TARGET_CHUNK_ID, + claim_id=None, + decision_type=DecisionType.CLAIMIFY_OMITTED, + source_span=_TOKEN, + reason=None, + edit_detail=None, + protected_class=None, + extractor_version="forget-test", + ), + ), + claimify_input_hash="hash", + ) + with seeded_engine.connect() as connection: + assert ( + connection.execute( + text("SELECT count(*) FROM selection_results") + ).scalar_one() + == 0 + ) + assert ( + connection.execute( + text( + "SELECT count(*) FROM claim_extraction_decisions WHERE extractor_version='forget-test'" + ) + ).scalar_one() + == 0 + ) diff --git a/src/tests/workers/e3_test_doubles.py b/src/tests/workers/e3_test_doubles.py index 55185b382..0b58942b1 100644 --- a/src/tests/workers/e3_test_doubles.py +++ b/src/tests/workers/e3_test_doubles.py @@ -4,6 +4,7 @@ import json from typing import Any +from uuid import UUID from uuid import uuid4 from rememberstack.adapters.testing import FakeModelProvider @@ -40,7 +41,7 @@ def record( class RecordingResolver: """Resolver that records resolve calls.""" - def __init__(self, *, identities: dict[str, object] | None = None) -> None: + def __init__(self, *, identities: dict[str, UUID] | None = None) -> None: """Start with an empty call log and optional exact-name identities.""" self.calls: list[EntityRef] = [] self.identities = dict(identities or {}) From 1554e6e6f921e53969c77b7dd024cf46419ed62f Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 15:19:28 +0200 Subject: [PATCH 12/14] test(extraction): supply reference context in temporal prompt fixtures --- ...22_d123_document_reference_context_20260914.md | 15 +++++++++++++++ src/tests/workers/test_claim_valid_time.py | 3 +++ 2 files changed, 18 insertions(+) diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md index 0289c37b4..f7fcf6074 100644 --- a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -217,3 +217,18 @@ provider is typed as its existing ModelProviderPort; its convenience constructor and production defaults are unchanged. This lets an isolated experiment compose existing providers honestly without pretending a reader-only Gemma variant configures processing. + +The integrated actual500-version proof completed successfully in1,258.64 seconds +(20m58s). It retained the same two-span claim identity across the500 occurrences, +avoided repeated target extraction calls, and verified the actual fact evidence +recount remained one source lineage. No model-quality inference follows from +these canned responses. + +Final rebase onto main `6205fe09` retained the upstream source-passage wording; +the two conflicts were generation pins, resolved to the combined Full31 values. +CI on runtime head `e7553a1a` passed Quality (including the full type checker), +docs build, adapters, Compose quickstart and contract smoke. Its unit lane had +1,666 passes and two old temporal-prompt fixtures missing the new `cards` format +argument. Parent supplied an empty reference block; all19 temporal tests then +passed. This is a fixture update, not a runtime change. Final integration lanes +and Antigravity final review are being collected before merge. diff --git a/src/tests/workers/test_claim_valid_time.py b/src/tests/workers/test_claim_valid_time.py index 41abf0372..70cf298d3 100644 --- a/src/tests/workers/test_claim_valid_time.py +++ b/src/tests/workers/test_claim_valid_time.py @@ -54,6 +54,7 @@ def test_document_header_keeps_absent_source_time_unknown() -> None: def test_rendered_claimify_prompt_requires_anchored_temporal_resolution() -> None: """The extraction request resolves relative time into both text and fields.""" rendered = _CLAIMIFY_PROMPT.format( + cards="(none)", keeps="- Melanie painted a lake sunrise last year.", passages="[S1] TARGET (origin-eligible):\nMelanie painted a lake sunrise last year.", bundle=( @@ -314,11 +315,13 @@ def test_two_same_day_sources_keep_distinct_temporal_anchors() -> None: update={"source_modified_at": datetime(2023, 5, 8, 22, tzinfo=UTC)} ) first_prompt = _CLAIMIFY_PROMPT.format( + cards="(none)", keeps="the final ended three hours ago", passages="", bundle=_header_text(source=source), ) later_prompt = _CLAIMIFY_PROMPT.format( + cards="(none)", keeps="the final ended three hours ago", passages="", bundle=_header_text(source=later), From 624ecf4b8e4dab725cf5a31ae8c6cb22a7ae2036 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 15:41:02 +0200 Subject: [PATCH 13/14] test(surfaces): run claim grounding in retrieval corpus fixture --- ...123_document_reference_context_20260914.md | 29 +++++++++++++------ src/tests/surfaces/test_retrieval_api.py | 20 ++++++------- 2 files changed, 30 insertions(+), 19 deletions(-) diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md index f7fcf6074..57b7c6a97 100644 --- a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -137,7 +137,7 @@ eight contextual nomination PostgreSQL tests passed. A ninth test initially failed because its call used the wrong keyword for the existing snapshot-hash helper; the test was corrected and its final result is recorded subsequently. Changed storage, ledger and profile modules passed Pyright. Grok replaced the -temporary passage type with D119's actual SourcePassage and passed15 core tests, +temporary passage type with D119's actual SourcePassage and passed 15 core tests, ruff and Pyright. Both minor earlier review nits are now addressed. The handler split and complete source-reference/reuse wiring are still being @@ -189,10 +189,10 @@ is claimed before the authorized Gemma/Vertex conv-42 run. ## Final integration checks before main rebase Grok completed and pushed the worker fixtures (`93f3acfc`) and Full-v31 pins -(`c275d724`). The worker lane passed46 PostgreSQL-free tests and30 PostgreSQL -chain/reuse cases (28 initially, the remaining2 after updating the explicit +(`c275d724`). The worker lane passed 46 PostgreSQL-free tests and 30 PostgreSQL +chain/reuse cases (28 initially, the remaining 2 after updating the explicit Selection-reuse versus full-Claimify-reuse expectations). The protocol lane -passed184 benchmark unit tests, Ruff and Pyright. Its serialized synthetic +passed 184 benchmark unit tests, Ruff and Pyright. Its serialized synthetic prepare fingerprint is `ee7d277f10e9b7d486f75f5221a7a174386248c3b5fc79c60815bcb7be1700b3`. This fingerprint is not a live processing run. @@ -204,11 +204,11 @@ the existing dynamic snapshot API. The full type pass additionally identified an overly broad UUID annotation in an E3 test double; that was narrowed to UUID. The remaining protocol suffix note is resolved by the Full31 pin commit. -Parent's further PostgreSQL context and hard-forget suite passed15 tests +Parent's further PostgreSQL context and hard-forget suite passed 15 tests (54.52 seconds). It proves both new source stores are scrubbed while independent control data survives, repeated scrubs remain idempotent, and the actual Selection and Claimify publication APIs reject a late response after forget -starts. The59 core/profile unit tests passed (34.58 seconds). Repository test +starts. The 59 core/profile unit tests passed (34.58 seconds). Repository test inventory and all five import-boundary contracts pass. The final wording names the earlier evidence block “EARLIER REFERENCES” and @@ -218,8 +218,8 @@ and production defaults are unchanged. This lets an isolated experiment compose existing providers honestly without pretending a reader-only Gemma variant configures processing. -The integrated actual500-version proof completed successfully in1,258.64 seconds -(20m58s). It retained the same two-span claim identity across the500 occurrences, +The integrated actual 500-version proof completed successfully in 1,258.64 seconds +(20m58s). It retained the same two-span claim identity across the 500 occurrences, avoided repeated target extraction calls, and verified the actual fact evidence recount remained one source lineage. No model-quality inference follows from these canned responses. @@ -229,6 +229,17 @@ the two conflicts were generation pins, resolved to the combined Full31 values. CI on runtime head `e7553a1a` passed Quality (including the full type checker), docs build, adapters, Compose quickstart and contract smoke. Its unit lane had 1,666 passes and two old temporal-prompt fixtures missing the new `cards` format -argument. Parent supplied an empty reference block; all19 temporal tests then +argument. Parent supplied an empty reference block; all 19 temporal tests then passed. This is a fixture update, not a runtime change. Final integration lanes and Antigravity final review are being collected before merge. + + +## CI retrieval fixture correction + +CI on `1554e6e6` passed unit, worker integration, adapter integration, Quality, +contract smoke and Compose quickstart. The surfaces lane exposed one stale +shared retrieval fixture: it registered and drained Selection but omitted the +new GROUND_CLAIMS stage, so its corpus never reached Claimify or normalization. +Parent added the same extraction handler for GROUND_CLAIMS and included that +stage in its drain loop. The direct retrieval suite is being rerun against +PostgreSQL; this change does not alter runtime retrieval behavior. diff --git a/src/tests/surfaces/test_retrieval_api.py b/src/tests/surfaces/test_retrieval_api.py index 9dd780048..63f1b9a22 100644 --- a/src/tests/surfaces/test_retrieval_api.py +++ b/src/tests/surfaces/test_retrieval_api.py @@ -288,17 +288,16 @@ def __init__(self, *, engine: Engine, root: Path) -> None: params=_PARAMS, ), ) - registry.register( - stage=PipelineStage.EXTRACT_CLAIMS, - handler=ExtractClaimsHandler( - catalog=claim_catalog, - chunk_catalog=chunk_catalog, - artifact_store=artifact_store, - model_provider=self.provider, - settings=E2Settings(), - chunker_version=generation, - ), + extraction = ExtractClaimsHandler( + catalog=claim_catalog, + chunk_catalog=chunk_catalog, + artifact_store=artifact_store, + model_provider=self.provider, + settings=E2Settings(), + chunker_version=generation, ) + registry.register(stage=PipelineStage.EXTRACT_CLAIMS, handler=extraction) + registry.register(stage=PipelineStage.GROUND_CLAIMS, handler=extraction) facts = FactCatalog(engine=engine) profile_refresher = EntityProfileRefresher( engine=engine, @@ -417,6 +416,7 @@ def build_corpus(self) -> None: PipelineStage.CHUNK, PipelineStage.EMBED_CHUNK, PipelineStage.EXTRACT_CLAIMS, + PipelineStage.GROUND_CLAIMS, PipelineStage.NORMALIZE_RELATIONS, PipelineStage.ADJUDICATE_OBSERVATIONS, PipelineStage.ADJUDICATE_SUPERSESSION, From 7e64bed36b9557f48d43ae41e06bf700b0a67353 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Mon, 14 Sep 2026 15:43:40 +0200 Subject: [PATCH 14/14] docs: record final D122 D123 review and retrieval proof --- .../d122_d123_agy_review_e7553a1a.md | 263 ++++++++++++++++++ ...123_document_reference_context_20260914.md | 7 + 2 files changed, 270 insertions(+) create mode 100644 plan/implementation_evals/d122_d123_agy_review_e7553a1a.md diff --git a/plan/implementation_evals/d122_d123_agy_review_e7553a1a.md b/plan/implementation_evals/d122_d123_agy_review_e7553a1a.md new file mode 100644 index 000000000..292ba0da7 --- /dev/null +++ b/plan/implementation_evals/d122_d123_agy_review_e7553a1a.md @@ -0,0 +1,263 @@ +# Antigravity Final Exact-Head Review: PR #403 (e7553a1a) + +- **Target Repository:** `/Users/jpuc/code/moje/ultimate_memory/ugm-document-context` +- **Reviewed Head SHA:** `e7553a1ac3de0db03d02237e2988c0923bcd6fb6` (`e7553a1a`) +- **Base Commit:** `6205fe0968d3a36f783396cec31ee98a09aa7338` (`origin/main`) +- **PR:** [#403](https://github.com/writeitai/remember-stack/pull/403) +- **Binding Specifications:** + - [D122: Stable source references shared during document extraction](../designs/document_reference_context_design.md) + - [D123: Source-backed entity context for fact nomination](../designs/contextual_fact_nomination_design.md) + - D119: Source-anchored multi-span extraction and evidence reuse +- **Review Date:** 2026-09-14 +- **Verdict:** **APPROVED** (No material findings in the review scope; the listed type, unit and PostgreSQL checks passed. Parent CI gates remain separate.) + +--- + +## 1. Executive Summary + +PR #403 introduces the complete two-phase extraction architecture (D122) and contextual fact nomination (D123) rebased onto `main` (`6205fe09`). + +The implementation strictly maintains the architecture established in prior designs and reviews: +1. **D122 (Two-Phase E2 Extraction Split):** + - `EXTRACT_CLAIMS` executes Selection only: identifies propositions and source-backed referents, persisting the frozen result once to `selection_results`. + - `SelectionChunkBarrier` evaluated atomically in `WorkLedger.complete_chunk_selection` under representation advisory lock transitions chunks to `GROUND_CLAIMS` only once all chunk selections for the representation exist. + - `GROUND_CLAIMS` runs Claimify after the barrier opens. Preceding referents are bounded to whole cards within the preceding 8 chunks, formatted text capped at 4,096 characters, with citation labels (`S{next_index}`) assigned before length measurement. + - Zero-keep chunks complete deterministically with 0 model calls. + - Negative dependency version reuse: `claimify_input_hash` hashes the target Selection input hash, ordered Selection input hashes of all preceding 8 chunk producers (including zero-card producers), and reference policy version, stamped onto the existing `chunks` row without a separate receipt table. + - Source grounding enforcement: only card passages cited in candidate `source_refs` enter grounding token elements; uncited card passages cannot ground tokens (`ADDED_CONTEXT_UNVERIFIED`). + - Prompt fidelity: the reference section is plainly titled `EARLIER REFERENCES:`, and upstream source-passage wording is fully preserved. + - Pipeline readiness and sync-cycle completion derive from both `EXTRACT_CLAIMS` and `GROUND_CLAIMS`. +2. **D123 (Contextual Fact Nomination):** + - Assertion normalizer captures up to 4 generic context references per assertion (`MAX_CONTEXT_REFS = 4`), truncating extra items on the frozen response without rejecting the assertion. + - Standard entity resolver resolves context entities with live decision validation (`superseded_by IS NULL` and claim mention match). + - Atomic staging in `FactApplicationCatalog.stage` writes `application_context_bindings` with stable original ordinals and deduplicates aliases to the first ordinal. + - Nomination preserves the same-subject 20-fact baseline (`_FACT_LIMIT = 20`) and nominates up to 8 extra facts (`_CONTEXT_FACT_LIMIT = 8`, total <= 28) sharing current positive testimony context, ordered first for model presentation. + - Canonical subject closures are strictly excluded from context matching. + - Internal snapshot fingerprints include all context bindings and canonical reverse-closure memberships (`context_hash`), and row lock verification detects concurrent changes (`ApplicationInputChanged`). + - Hard-forget scrubs `selection_results` and cascades `application_context_bindings`; late publication after forget starts is rejected. +3. **LoCoMo Full-v31 Protocol Alignment:** + - Protocol identity updated to `RS-LoCoMo-Full-v31` (`locomo-full-adapter-2026.09-document-context-v31`). + - Pinned `EXPECTED_PROMPT_RENDERER_VERSION = "concise-handles-2"`. + - `EXPECTED_PIPELINE_STAGES` includes `ground_claims`. + - All extractor and normalizer generation strings match runtime constants. + +--- + +## 2. Verification of Prior Review Findings + +All findings and notes recorded in `plan/implementation_evals/d122_d123_agy_review_2c547937.md` have been addressed and verified on HEAD (`e7553a1a`): + +1. **`assertion_rows` Typing in `concise_adjudication.py`:** + - In `src/rememberstack/core/concise_adjudication.py` (line 188), `assertion_rows` is explicitly annotated: + ```python + assertion_rows: list[dict[str, Any]] = list(snapshot.get("assertions", ())) + ``` + - Eliminated `list[Never]` inference; Pyright reports 0 errors in `concise_adjudication.py`. + - **Status:** Verified. + +2. **`_snapshot` Return Type in `test_d123_context_nomination.py`:** + - In `src/tests/spine/test_d123_context_nomination.py` (line 59), `_snapshot` is annotated to return `dict[str, Any]`: + ```python + def _snapshot(*, engine: Engine, case: WriterCase, app: UUID) -> dict[str, Any]: + ``` + - Eliminated all 5 Pyright indexing/membership errors. + - **Status:** Verified. + +3. **Narrowed UUID Annotation in `e3_test_doubles.py`:** + - In `src/tests/workers/e3_test_doubles.py` (line 44), `RecordingResolver.__init__` narrowed `identities` parameter from `dict[str, object] | None` to `dict[str, UUID] | None`. + - **Status:** Verified. + +4. **Stale `_extract_chunk` Error in `test_claimify_loss_ledger.py`:** + - In `src/tests/workers/test_claimify_loss_ledger.py`, tests drive the handler through public pipeline stages (`PipelineStage.EXTRACT_CLAIMS` then `PipelineStage.GROUND_CLAIMS`) via `handler.handle(work=work, meter=...)`. + - No private `_extract_chunk` call remains. + - **Status:** Verified. + +5. **Full-v31 Protocol Pins Rebased & Aligned:** + - `benchmarks/locomo/protocol.py` correctly defines `PROTOCOL_NAME = "RS-LoCoMo-Full-v31"`, pins `ground_claims`, and incorporates `:d122-source-references-1` and `:d123-context-refs-2:...:d123-context-nom-2`. + - All 52 protocol tests in `src/tests/benchmarks/test_locomo_protocol.py` pass. + - **Status:** Verified. + +6. **Hard-Forget Scrubbing & Late-Publication Rejection:** + - In `src/tests/spine/test_forget_catalog.py`, `test_mutable_fact_payloads_and_date_witnesses_are_erased` proves `selection_results` and `application_context_bindings` are scrubbed while control data survives. + - `test_late_extraction_response_cannot_publish_after_forget_starts` proves both `SelectionCatalog.freeze` and `ClaimCatalog.record_extraction` reject late publication with `ForgetInProgressError`. + - **Status:** Verified. + +--- + +## 3. Architecture & Invariant Inspection + +### 3.1 D122: Two-Phase Extraction Split & Version Reuse +- **First-Writer Wins & Atomic Publication:** `SelectionCatalog.freeze` uses `INSERT INTO selection_results ... ON CONFLICT (deployment_id, chunk_id, extractor_version) DO NOTHING`, re-reads the committed row, and asserts input hash equality. +- **Zero-Keep Determinism:** Chunks with zero kept propositions publish their cards (if any) and complete Claimify with zero LLM calls, avoiding wasted model invocations. +- **Representation Barrier:** `WorkLedger.complete_chunk_selection` uses advisory locks on `representation_id` and checks `_SELECTION_BARRIER_MISSING` to enqueue all representation chunks into `PipelineStage.GROUND_CLAIMS` only after all chunk selections exist. +- **Occurrence Remapping:** Cards are remapped using fixed relative slots `target - 9 .. target + 1` via `reference_windows` in `extraction_references.py`, correctly preserving relative neighbor identity. +- **Negative Dependency Reuse:** `claimify_input_hash` hashes the target Selection input hash, ordered Selection input hashes of all preceding 8 chunks, and the reference policy version string. Changing or invalidating any preceding chunk (even one with 0 cards) cleanly invalidates Claimify reuse while allowing Selection reuse. +- **Single Receipt Storage:** Claimify input hash is stamped directly onto `chunks.claimify_input_hash`, avoiding redundant receipt tables while guaranteeing concurrency safety under `FOR UPDATE`. + +### 3.2 D123: Contextual Fact Nomination Semantics +- **Context Binding Invariants:** `FactApplicationCatalog.stage` validates a live resolver decision (`superseded_by IS NULL` and claim mention match) for each context entity, rejects duplicate ordinals, and deduplicates aliases to the first ordinal. +- **Nomination Boundaries:** `application_snapshot` nominates up to 20 baseline same-subject facts, plus up to 8 extra facts sharing current positive testimony context (`support_stance = 'supports'` and `is_current_testimony = true`), bounding total nominated facts to <= 28. Shared context facts are ordered first. +- **Snapshot Fingerprinting & Invalidation:** Fingerprint includes `context_hash` (digest of all context bindings + canonical membership hash). Any changes to context entities, memberships, or reverse closures trigger `ApplicationInputChanged`. + +### 3.3 Clarity & YAGNI +- No speculative abstractions, third model calls, new event tables, per-fact event columns, or date windows. +- Database reset fixture (`src/tests/database_reset.py`) cleanly detects schema `p9_32_0053` and resets test schemas safely without weakening migration invariants. +- `SelfHostProfile` accepts `model_provider: ModelProviderPort`, enabling clean dependency injection for test doubles while keeping production defaults unchanged. + +--- + +## 4. Checks Actually Performed + +All checks were executed directly against checkout `e7553a1ac3de0db03d02237e2988c0923bcd6fb6` in `/Users/jpuc/code/moje/ultimate_memory/ugm-document-context`. Disposable PostgreSQL tests used exclusive database port 55440 (`REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test"`). Ports 55439, 55441, and 55442 were untouched. No repository edits were made. + +### 4.1 CI Fast-Gate Quality Suite +1. **Test Inventory Drift Check:** + ```bash + python3 .github/ci/check_test_inventory.py + ``` + **Result:** `test inventory OK: unit=111 integration=63 discovered=174` (Exit 0) + +2. **Architecture Import Boundary Linter:** + ```bash + uv run lint-imports + ``` + **Result:** Analyzed 300 files, 805 dependencies. `Contracts: 5 kept, 0 broken` (Exit 0) + +3. **Ruff Linter:** + ```bash + uv run ruff check src/ benchmarks/ + ``` + **Result:** `All checks passed!` (Exit 0) + +4. **Ruff Format Check:** + ```bash + uv run ruff format --check src/ benchmarks/ + ``` + **Result:** `515 files already formatted` (Exit 0) + +5. **Whole-Tree Pyright Typecheck:** + ```bash + uv run pyright src/ benchmarks/ --pythonversion 3.13 + ``` + **Result:** `0 errors, 0 warnings, 0 informations` across entire codebase (Exit 0) + +### 4.2 Unit Test Suites (No Postgres) +1. **Core & Worker PR Unit Pack (231 tests):** + ```bash + uv run pytest \ + src/tests/core/test_selection_references.py \ + src/tests/core/test_context_references.py \ + src/tests/core/test_concise_adjudication.py \ + src/tests/workers/test_e3_context_references.py \ + src/tests/benchmarks/test_locomo_protocol.py \ + src/tests/benchmarks/test_locomo_runner.py \ + src/tests/benchmarks/test_locomo_store_backup.py \ + src/tests/workers/test_claimify_loss_ledger.py \ + src/tests/workers/test_d119_reuse.py \ + src/tests/workers/test_d119_versions.py \ + src/tests/workers/test_e2_occurrence_provenance.py -q + ``` + **Result:** `231 passed, 2 skipped in 10.19s` (Exit 0) + +2. **LoCoMo Protocol Suite (52 tests):** + ```bash + uv run pytest src/tests/benchmarks/test_locomo_protocol.py -v + ``` + **Result:** `52 passed in 4.89s` (Exit 0) + +3. **Claimify Loss Ledger & Accounting Suite (35 tests):** + ```bash + uv run pytest src/tests/workers/test_claimify_loss_ledger.py -v + ``` + **Result:** `35 passed in 2.75s` (Exit 0) + +4. **D119 Versions & Reuse Suite:** + ```bash + uv run pytest src/tests/workers/test_d119_versions.py src/tests/workers/test_d119_reuse.py -v + ``` + **Result:** `3 passed, 2 skipped in 3.52s` (Exit 0) + +### 4.3 Real-PostgreSQL Integration Suites (Port 55440) +1. **D123 Context Nomination Suite (9 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/spine/test_d123_context_nomination.py -v + ``` + **Result:** `9 passed in 23.31s` (Exit 0) + +2. **Hard-Forget Catalog & Scrubbing Suite (6 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/spine/test_forget_catalog.py -q + ``` + **Result:** `6 passed in 16.12s` (Exit 0) + *(Combined: 15 real PG context + forget proofs passed)* + +3. **D122 Selection Storage & Barrier Suite (4 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/spine/test_d122_selection.py -q + ``` + **Result:** `4 passed in 55.91s` (Exit 0) + +4. **D122 Cross-Section E2 Integration Suite (3 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/spine/test_d122_e2.py -q + ``` + **Result:** `3 passed in 66.30s` (Exit 0) + +5. **Pipeline Readiness Catalog Suite (16 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/spine/test_pipeline_readiness.py -q + ``` + **Result:** `16 passed in 29.66s` (Exit 0) + +6. **Spine Migration Chain & Refusal Suite (13 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/spine/test_migrations.py -q + ``` + **Result:** `13 passed in 243.04s` (Exit 0) + +7. **Worker E2 Chain Suite (4 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/workers/test_e2_chain.py -q + ``` + **Result:** `4 passed in 30.66s` (Exit 0) + +8. **Worker Reuse Lifecycle Suite (6 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/workers/test_reuse_lifecycle.py -q + ``` + **Result:** `6 passed in 100.90s` (Exit 0) + +9. **Worker E3 Chain Suite (6 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/workers/test_e3_chain.py -q + ``` + **Result:** `6 passed in 42.50s` (Exit 0) + +10. **Worker Lifecycle Reconciliation Suite (14 tests):** + ```bash + REMEMBERSTACK_DATABASE_URL="postgresql+psycopg://rememberstack:rememberstack_test@127.0.0.1:55440/ugm_d119_test" \ + uv run pytest src/tests/workers/test_lifecycle_reconciliation.py -q + ``` + **Result:** `14 passed in 604.21s` (Exit 0) + +--- + +## 5. Findings and Merge Recommendation + +- **Material Findings:** None (0 blockers, 0 material defects). +- **Static Typing:** Clean across the entire repository (`0 errors, 0 warnings`). +- **Linter & Formatting:** Fully compliant with Ruff rules and formatting standards. +- **Specification Conformance:** Full compliance with D122, D123, and Full-v31 contracts. +- **Verdict:** **APPROVED**. PR #403 at SHA `e7553a1ac3de0db03d02237e2988c0923bcd6fb6` is structurally sound, comprehensively tested, and ready for parent merge upon CI completion. + + +Parent note: the review inspected runtime `e7553a1a`. Later commits correct only temporal-prompt and retrieval-chain test fixtures and update this evidence record. The review did not run every repository integration suite; its exact commands and results are listed above. diff --git a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md index 57b7c6a97..620a999a6 100644 --- a/plan/implementation_evals/d122_d123_document_reference_context_20260914.md +++ b/plan/implementation_evals/d122_d123_document_reference_context_20260914.md @@ -243,3 +243,10 @@ new GROUND_CLAIMS stage, so its corpus never reached Claimify or normalization. Parent added the same extraction handler for GROUND_CLAIMS and included that stage in its drain loop. The direct retrieval suite is being rerun against PostgreSQL; this change does not alter runtime retrieval behavior. + +The corrected retrieval suite passed all 14 tests against PostgreSQL in 622.06 +seconds. [Final Antigravity review](d122_d123_agy_review_e7553a1a.md) approved +the runtime without material findings and independently passed 81 PostgreSQL +tests across context, deletion, Selection, E2, readiness, migration, reuse, E3 +and lifecycle suites. The later fixture corrections do not change the reviewed +runtime. Final exact-head CI is the remaining merge gate.