From 5c3c17853ed62b8197c2024aa333e1ca36541852 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 4 Sep 2026 17:37:05 +0200 Subject: [PATCH 1/6] feat(temporal): expose canonical bounds in the query space (D107 WP-T.0b) Publish memory_v1.canonical_bounds and claims_canonical so open SQL uses the same half-open D41 windows as the engine. Rewrite examples.claims_as_of over the view, counting unknown precision by precision alone, and roll the query space, surface manifest, and LoCoMo protocol to Full-v23. --- .github/workflows/ci.yml | 2 +- benchmarks/locomo/README.md | 12 +- benchmarks/locomo/__init__.py | 2 +- benchmarks/locomo/cli.py | 2 +- benchmarks/locomo/model.py | 10 +- benchmarks/locomo/protocol.py | 22 +- benchmarks/locomo/runner.py | 10 +- benchmarks/locomo/sharding/README.md | 2 +- plan/designs/locomo_benchmark_design.md | 19 +- src/rememberstack/core/open_query_prose.py | 28 + ...p9_27_0048_query_space_canonical_bounds.py | 178 ++++ .../spine/query_space/catalog.py | 86 ++ .../query_space/d48_deletion_matrix.json | 82 +- .../spine/query_space/deletion_matrix.py | 4 + .../spine/query_space/manifest.py | 21 + .../spine/query_space/memory_v1_manifest.json | 966 +++++++++++++++++- .../spine/query_space/source_definitions.py | 4 + .../surfaces/query_sandbox/bridge.py | 8 +- .../surfaces/query_sandbox/examples.py | 22 +- .../surfaces/query_sandbox/grammar.py | 3 + src/tests/benchmarks/test_locomo_protocol.py | 32 +- src/tests/benchmarks/test_locomo_runner.py | 10 +- .../benchmarks/test_locomo_store_backup.py | 6 +- src/tests/spine/test_canonical_bounds_sql.py | 32 + src/tests/spine/test_migrations.py | 3 +- src/tests/spine/test_query_space_batch_a.py | 13 +- src/tests/spine/test_query_space_manifest.py | 4 +- src/tests/surfaces/test_open_query_batch_f.py | 2 +- .../surfaces/test_query_sandbox_batch_b.py | 3 +- src/tests/surfaces/test_retrieval_batch_b.py | 35 + .../surfaces/test_saved_queries_batch_e.py | 14 +- website/src/app/docs/project-status/page.mdx | 11 +- .../app/docs/retrieval/open-query/page.mdx | 6 + 33 files changed, 1559 insertions(+), 95 deletions(-) create mode 100644 src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0aecc2a48..372230bed 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -371,7 +371,7 @@ jobs: 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_26_0047' + 'SELECT version_num FROM alembic_version')" = 'p9_27_0048' test "$(docker compose --env-file .env.example exec -T postgres \ psql -U rememberstack -d rememberstack -Atc \ 'SELECT count(*) FROM deployments')" = '1' diff --git a/benchmarks/locomo/README.md b/benchmarks/locomo/README.md index 47d971ab0..cf455373e 100644 --- a/benchmarks/locomo/README.md +++ b/benchmarks/locomo/README.md @@ -1,4 +1,4 @@ -# RS-LoCoMo-Full-v22 setup +# RS-LoCoMo-Full-v23 setup This directory contains the unshipped full-system LoCoMo adapter. It does not vendor or auto-download LoCoMo. Supply the exact pinned `locomo10.json` only after confirming its @@ -16,12 +16,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-v22 \ + --protocol full-v23 \ --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-v22` is the one +eight-question smoke plan. `--protocol` is prepare-only; `full-v23` 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). @@ -64,6 +64,12 @@ call sees the complete bounded candidate snapshot and returns a supplied candidate id or `new`. There is no insufficient-evidence result or confidence-routed frontier call. +V23 fingerprints D107 WP-T.0b: the query space exposes the same canonical +half-open bounds as `memory_v1.canonical_bounds` and `claims_canonical`, and +`examples.claims_as_of` overlaps those bounds and counts unknown precision by +precision alone. Ingestion, adjudication, and the library `claims_as_of` path +are those of v22; the surface manifest hash rolls. + V22 fingerprints D107 WP-T.0a: the observation adjudicator and `claims_as_of` compare canonical half-open bounds (a day is the whole calendar day, an instant a non-empty point, adjacent units do not overlap); everything else is diff --git a/benchmarks/locomo/__init__.py b/benchmarks/locomo/__init__.py index 23ea50f99..6aee63141 100644 --- a/benchmarks/locomo/__init__.py +++ b/benchmarks/locomo/__init__.py @@ -1 +1 @@ -"""The pinned RS-LoCoMo-Full-v22 benchmark adapter.""" +"""The pinned RS-LoCoMo-Full-v23 benchmark adapter.""" diff --git a/benchmarks/locomo/cli.py b/benchmarks/locomo/cli.py index 34fd5e843..88be1f07e 100644 --- a/benchmarks/locomo/cli.py +++ b/benchmarks/locomo/cli.py @@ -145,7 +145,7 @@ def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="python -m benchmarks.locomo", description=( - "RS-LoCoMo-Full-v22: prepare is local; ingest/answer/judge require " + "RS-LoCoMo-Full-v23: prepare is local; ingest/answer/judge require " "explicit execution acknowledgements" ), ) diff --git a/benchmarks/locomo/model.py b/benchmarks/locomo/model.py index d5d6a645b..989c6dc71 100644 --- a/benchmarks/locomo/model.py +++ b/benchmarks/locomo/model.py @@ -1,4 +1,4 @@ -"""Typed values for the full-system RS-LoCoMo-Full-v22 protocol.""" +"""Typed values for the full-system RS-LoCoMo-Full-v23 protocol.""" from __future__ import annotations @@ -31,8 +31,8 @@ Category = Literal[1, 2, 3, 4, 5] RetainedCategory = Literal[1, 2, 3, 4] Tier = Literal["smoke", "development", "publication"] -ProtocolKey = Literal["full-v22", "full-v22-gemma-vertex"] -ProtocolName = Literal["RS-LoCoMo-Full-v22", "RS-LoCoMo-Full-v22-GemmaVertex"] +ProtocolKey = Literal["full-v23", "full-v23-gemma-vertex"] +ProtocolName = Literal["RS-LoCoMo-Full-v23", "RS-LoCoMo-Full-v23-GemmaVertex"] SourceTimezoneBasis = Literal["assumed_utc"] AnswerAgentModel = Literal["openai/gpt-5.6-luna", "google/gemma-4-26b-a4b-it-maas"] JudgeModel = Literal["openai/gpt-5.6-luna"] @@ -126,7 +126,7 @@ class QuestionManifest(FrozenModel): class RunConfiguration(FrozenModel): """Immutable identity of one prepared benchmark run.""" - protocol_name: ProtocolName = "RS-LoCoMo-Full-v22" + protocol_name: ProtocolName = "RS-LoCoMo-Full-v23" adapter_version: NonEmpty prepared_at: datetime repository_revision: NonEmpty @@ -477,7 +477,7 @@ class SessionDiagnosticSummary(FrozenModel): class RunSummary(FrozenModel): """Publication-ready local aggregate with no hidden denominator.""" - protocol_name: ProtocolName = "RS-LoCoMo-Full-v22" + protocol_name: ProtocolName = "RS-LoCoMo-Full-v23" protocol_fingerprint: NonEmpty tier: Tier questions: int = Field(ge=1) diff --git a/benchmarks/locomo/protocol.py b/benchmarks/locomo/protocol.py index d4e94c650..429f78040 100644 --- a/benchmarks/locomo/protocol.py +++ b/benchmarks/locomo/protocol.py @@ -34,9 +34,9 @@ from rememberstack.model import Envelope from rememberstack.model import ToolDescriptor -PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v22" -DEFAULT_PROTOCOL_KEY: Final = "full-v22" -ADAPTER_VERSION: Final = "locomo-full-adapter-2026.09-canonical-bounds-v22" +PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v23" +DEFAULT_PROTOCOL_KEY: Final = "full-v23" +ADAPTER_VERSION: Final = "locomo-full-adapter-2026.09-query-space-canonical-bounds-v23" MAX_TOOL_CALLS: Final = 8 MAX_AGENT_CALLS: Final = 9 ANSWER_READER_RETRY_BUDGET: Final = 2 @@ -45,7 +45,7 @@ EXPECTED_DOCUMENT_BINDING_GENERATION: Final = "document-t0-v1" EXPECTED_SURFACE_MANIFEST_HASH: Final = ( - "3583f86ac5bb883481ba2cf4d9e7a0da1ac5e650ada140b97998fe273aa7edeb" + "0b9e8091dea477a4f6e4c3ff99c9031971395edb8797cd5576bba9dce773d2fa" ) EXPECTED_PIPELINE_STAGES: Final = ( "convert", @@ -118,12 +118,12 @@ 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-v22-GemmaVertex" -GEMMA_VERTEX_PROTOCOL_KEY: Final = "full-v22-gemma-vertex" +GEMMA_VERTEX_PROTOCOL_NAME: Final = "RS-LoCoMo-Full-v23-GemmaVertex" +GEMMA_VERTEX_PROTOCOL_KEY: Final = "full-v23-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 v22 pin -- ingestion bindings, prompts, +The variant protocol keeps every v23 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 @@ -235,8 +235,8 @@ class LoCoMoProtocol: """Which adapter serves the judge; kept on OpenRouter for comparability.""" -_FULL_V22 = LoCoMoProtocol( - key="full-v22", +_FULL_V23 = LoCoMoProtocol( + key="full-v23", name=PROTOCOL_NAME, answer_agent_model=ANSWER_AGENT_MODEL, judge_model=JUDGE_MODEL, @@ -257,7 +257,7 @@ class LoCoMoProtocol: answer_word_cap=None, ) -_FULL_V22_GEMMA_VERTEX = LoCoMoProtocol( +_FULL_V23_GEMMA_VERTEX = LoCoMoProtocol( key=GEMMA_VERTEX_PROTOCOL_KEY, name=GEMMA_VERTEX_PROTOCOL_NAME, answer_agent_model=GEMMA_VERTEX_ANSWER_AGENT_MODEL, @@ -282,7 +282,7 @@ class LoCoMoProtocol: ) PROTOCOL_REGISTRY: Final[Mapping[ProtocolKey, LoCoMoProtocol]] = MappingProxyType( - {_FULL_V22.key: _FULL_V22, _FULL_V22_GEMMA_VERTEX.key: _FULL_V22_GEMMA_VERTEX} + {_FULL_V23.key: _FULL_V23, _FULL_V23_GEMMA_VERTEX.key: _FULL_V23_GEMMA_VERTEX} ) diff --git a/benchmarks/locomo/runner.py b/benchmarks/locomo/runner.py index 5ba95847d..4ceab7522 100644 --- a/benchmarks/locomo/runner.py +++ b/benchmarks/locomo/runner.py @@ -417,7 +417,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-v22" + "deployment document binding generation differs from RS-LoCoMo-Full-v23" ) _require_current_query_surface(context=context, client=client) _require_exact_live_ingests( @@ -576,7 +576,7 @@ def answer_sample( ): raise ExecutionGuardError( "the deployment did not report the exact completed" - " RS-LoCoMo-Full-v22 pipeline, live graph, and fresh P3 projection" + " RS-LoCoMo-Full-v23 pipeline, live graph, and fresh P3 projection" ) _require_serving_revision(context=context, readiness=readiness) prior_readiness = context.state.readiness.get(sample_id) @@ -1200,7 +1200,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-v22") + raise BenchmarkRunError("run dataset hash is not RS-LoCoMo-Full-v23") 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: @@ -1210,7 +1210,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-v22") + raise BenchmarkRunError("run dataset commit is not RS-LoCoMo-Full-v23") if configuration.adapter_version != ADAPTER_VERSION: raise BenchmarkRunError("run adapter version differs from current code") if _models_hash(values=documents) != configuration.documents_sha256: @@ -1468,7 +1468,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-v22: " + "deployment ingest model bindings differ from RS-LoCoMo-Full-v23: " + ", ".join(mismatches) ) diff --git a/benchmarks/locomo/sharding/README.md b/benchmarks/locomo/sharding/README.md index bfcc04282..41533b38f 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-v22` | prepare-time protocol key | +| `LOCOMO_PROTOCOL` | `full-v23` | 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 | diff --git a/plan/designs/locomo_benchmark_design.md b/plan/designs/locomo_benchmark_design.md index e2adb24c5..dbb8ed5da 100644 --- a/plan/designs/locomo_benchmark_design.md +++ b/plan/designs/locomo_benchmark_design.md @@ -7,7 +7,16 @@ > assured surface rolls this protocol; the sequencing is > `plan/plans/temporal_clocks.md`. Contract: `temporal_clocks_design.md` §6–§8. -> **Binding D107 amendment, WP-T.0a (2026-09-03).** The current protocol is +> **Binding D107 amendment, WP-T.0b (2026-09-04).** The current protocol is +> `RS-LoCoMo-Full-v23`. It retains v22's dataset, rendered documents, models, +> tools, budgets, prompts, scoring, and ingest component versions. The query +> space now publishes `memory_v1.canonical_bounds` and `claims_canonical`, and +> `examples.claims_as_of` overlaps the half-open canonical window and counts +> unknown precision by precision alone (audit 4.21). The surface manifest +> hash, protocol identity, and fingerprint roll; ingestion provenance and the +> library `claims_as_of` result set do not. + +> **Historical D107 amendment, WP-T.0a (2026-09-03).** The WP-T.0a protocol was > `RS-LoCoMo-Full-v22`. It retains v21's dataset, rendered documents, models, > tools, budgets, prompts, and scoring. Its pinned `adjudicate_observations` > component version now carries canonical half-open bounds (D107 §5): the @@ -109,7 +118,7 @@ and spend ceiling. ## 2. Fixed protocol ```text -protocol RS-LoCoMo-Full-v22 +protocol RS-LoCoMo-Full-v23 dataset commit 3eb6f2c585f5e1699204e3c3bdf7adc5c28cb376 dataset SHA-256 79fa87e90f04081343b8c8debecb80a9a6842b76a7aa537dc9fdf651ea698ff4 categories 1, 2, 3, 4 @@ -681,7 +690,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-v22 requires to be +- the non-secret `document_binding_generation`, which Full-v23 requires to be exactly `document-t0-v1` and stores in `run.json` plus the protocol fingerprint. @@ -827,11 +836,11 @@ Local preparation: uv run --extra benchmark python -m benchmarks.locomo prepare \ --dataset /absolute/path/locomo10.json \ --tier smoke \ - --protocol full-v22 \ + --protocol full-v23 \ --output .benchmark-runs/locomo-smoke ``` -`--protocol` exists only on `prepare`. The sole choice is `full-v22`; ingest, +`--protocol` exists only on `prepare`. The sole choice is `full-v23`; ingest, answer, judge, and summarize read it from the prepared run and expose no protocol override. diff --git a/src/rememberstack/core/open_query_prose.py b/src/rememberstack/core/open_query_prose.py index d611698ca..e70bc4228 100644 --- a/src/rememberstack/core/open_query_prose.py +++ b/src/rememberstack/core/open_query_prose.py @@ -127,6 +127,31 @@ ORDER BY g.hops, g.relation_ids;\ """ +#: Purpose string for the shipped ``examples.claims_as_of`` identity. +CLAIMS_AS_OF_PURPOSE: Final = ( + "Claims whose canonical world-time window overlaps an inclusive interval;" + " unknown-precision claims are counted by precision, not by bounds" +) + +#: SQL body for the shipped ``examples.claims_as_of`` identity (byte-stable). +#: Overlap is half-open on ``canon_start`` / ``canon_end``; the caller's +#: inclusive ``to`` becomes ``to + 1 µs`` so ``($1, $1)`` is a point query. +CLAIMS_AS_OF_SQL: Final = ( + "SELECT c.claim_id, c.claim_text, c.source_handle," + " c.claim_valid_from, c.claim_valid_until, c.claim_valid_precision," + " c.canon_start, c.canon_end," + " (" + " SELECT count(*) FROM claims_canonical AS u" + " WHERE u.claim_valid_precision = 'unknown'" + " ) AS unknown_precision_excluded" + " FROM claims_canonical AS c" + " WHERE c.claim_valid_precision <> 'unknown'" + " AND c.canon_start < ($2::timestamptz + '1 microsecond'::interval)" + " AND (c.canon_end IS NULL OR c.canon_end > $1::timestamptz)" + " ORDER BY c.claim_valid_from DESC, c.claim_id" + " LIMIT 50" +) + #: Purpose string for the shipped ``examples.claims_verbatim`` identity. CLAIMS_VERBATIM_PURPOSE: Final = ( "Claims as asserted, nominated semantically and joined to live testimony" @@ -145,6 +170,9 @@ HONESTY_WARNINGS: Final[tuple[str, ...]] = ( "Claims are immutable source testimony; they do not answer current-truth" " questions.", + "Claim world-time overlap is half-open on claims_canonical.canon_start /" + " canon_end (or memory_v1.canonical_bounds); unknown-precision claims have" + " no interval and are counted by precision, never by bounds.", "Empty SQL is untyped exploratory_tabular: a view's source grain is never" " a claim about an arbitrary outer query's result grain.", "Graph helper absence is bounded by the disclosed traversal budgets; inspect" diff --git a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py new file mode 100644 index 000000000..992f1b115 --- /dev/null +++ b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py @@ -0,0 +1,178 @@ +"""Expose canonical bounds in the query space (D107 §5, WP-T.0b). + +``memory_v1.canonical_bounds`` wraps the public IMMUTABLE twins from +``p9_26_0047`` so open SQL can canonicalise a stored D41 window without +EXECUTE on the public schema. ``memory_v1.claims_canonical`` is +``claims_visible_history`` plus the half-open ``canon_start`` / ``canon_end`` +columns those twins compute. Claim storage is unchanged. + +revision: p9_27_0048 +""" + +from alembic import op + +from rememberstack.spine.migrations._helpers import apply_view_ddl + +revision: str = "p9_27_0048" +down_revision: str | None = "p9_26_0047" +branch_labels = None +depends_on = None + +_VIEW_OWNER = "rememberstack_view_owner" + +CANONICAL_BOUNDS_FUNCTION_DDL = r""" +CREATE FUNCTION memory_v1.canonical_bounds( + valid_from timestamptz, + valid_until timestamptz, + valid_precision text +) +RETURNS TABLE(canon_start timestamptz, canon_end timestamptz) +LANGUAGE sql +IMMUTABLE +PARALLEL SAFE +SECURITY DEFINER +SET search_path = public, pg_catalog +AS $$ + SELECT + claim_canonical_start( + valid_from, valid_precision::claim_valid_precision + ) AS canon_start, + claim_canonical_end( + valid_from, valid_until, valid_precision::claim_valid_precision + ) AS canon_end +$$; +""" + +CLAIMS_CANONICAL_VIEW_DDL = r""" +CREATE VIEW memory_v1.claims_canonical ( + deployment_id, -- The deployment that owns the claim. + claim_id, -- Stable identity of this immutable claim. + doc_id, -- The live lineage that asserted the claim. + version_id, -- The non-tombstoned version the claim was extracted from. + representation_id, -- The reading whose character offsets the claim's anchors use. + chunk_id, -- The chunk the claim was extracted from. + claim_text, -- The standalone assertion as extracted, which is source testimony rather than adjudicated truth. + source_span, -- The verbatim slice of the source the claim derives from. + char_start, -- Start character offset of source_span within the named representation's markdown. + char_end, -- End character offset of source_span within the named representation's markdown. + added_context, -- The substrings decontextualization added, each with the bundle source it came from. + temporal_class, -- How the claim behaves over time, either static, dynamic, or atemporal; null when unclassified. + is_attributed, -- True when the claim preserves an attribution, so it entails that someone said it rather than that it holds. + audit_status, -- Result of the sampled independent grounding audit, defaulting to unaudited. + kept_flagged, -- True when selection kept the claim but marked it for review. + extractor_version, -- The extractor generation that produced the claim, which is part of the D54 extraction basis. + asserted_at, -- Assertion-event time: when the source asserted this, null when the source carries no date. + claim_valid_from, -- Immutable inclusive start of the world-time interval the SOURCE asserted, null for unbounded-before or unknown. + claim_valid_until, -- Immutable inclusive end of that interval, null for open-per-source or unknown as disambiguated by claim_valid_precision. + claim_valid_precision, -- Granularity of the asserted interval, from unknown through instant, day, month, quarter, and year to open. + claim_valid_kind, -- Which world-interval was asserted, such as event_time or measurement_period; null when unclassified. + ingested_at, -- Transaction-time: when this deployment extracted the claim. + source_kind, -- The connector family of the asserting lineage. + source_handle, -- Stable human-usable handle for the asserting lineage, formed from its connector-native identity. + is_current_testimony, -- True while this claim is the current transcription of its chunk under D54; false once a newer extraction generation or a living-mode version move superseded it. + canon_start, -- Inclusive start of the half-open canonical window (D107 §5); null when precision is unknown. + canon_end -- Exclusive end of the half-open canonical window; null when the window is open or unknown. +) AS +SELECT + h.deployment_id, + h.claim_id, + h.doc_id, + h.version_id, + h.representation_id, + h.chunk_id, + h.claim_text, + h.source_span, + h.char_start, + h.char_end, + h.added_context, + h.temporal_class, + h.is_attributed, + h.audit_status, + h.kept_flagged, + h.extractor_version, + h.asserted_at, + h.claim_valid_from, + h.claim_valid_until, + h.claim_valid_precision, + h.claim_valid_kind, + h.ingested_at, + h.source_kind, + h.source_handle, + h.is_current_testimony, + b.canon_start, + b.canon_end +FROM memory_v1.claims_visible_history AS h +CROSS JOIN LATERAL memory_v1.canonical_bounds( + h.claim_valid_from, + h.claim_valid_until, + h.claim_valid_precision +) AS b; +COMMENT ON VIEW memory_v1.claims_canonical IS + 'One row per historically visible claim with surviving lineage, keyed by (deployment_id, claim_id), carrying the stored inclusive D41 window beside the half-open canonical bounds that every overlap predicate must use (D107 §5). canon_start is inclusive and canon_end exclusive; both are null when precision is unknown, and canon_end is also null for an open window. Overlap is a.start < b.end AND b.start < a.end with a null end as unbounded. This relation is IMMUTABLE SOURCE TESTIMONY: it never answers what currently holds. Claims of forgotten lineages and tombstoned versions are absent.'; +""" + + +def upgrade() -> None: + """Publish the wrapper function and the claims_canonical view.""" + op.execute( + "GRANT EXECUTE ON FUNCTION" + " claim_canonical_start(timestamptz, claim_valid_precision)" + f" TO {_VIEW_OWNER}" + ) + op.execute( + "GRANT EXECUTE ON FUNCTION" + " claim_canonical_end(timestamptz, timestamptz, claim_valid_precision)" + f" TO {_VIEW_OWNER}" + ) + op.execute(CANONICAL_BOUNDS_FUNCTION_DDL) + op.execute( + "COMMENT ON FUNCTION memory_v1.canonical_bounds(timestamptz, timestamptz, text)" + " IS " + + _quote( + "D107 §5: half-open canonical bounds [canon_start, canon_end) for one " + "stored D41 window. valid_precision is the claim_valid_precision " + "vocabulary as text; unknown yields a null interval; open yields a " + "null exclusive end. Wraps public.claim_canonical_start/end so the " + "query role never needs EXECUTE on the public schema." + ) + ) + op.execute( + "ALTER FUNCTION memory_v1.canonical_bounds(timestamptz, timestamptz, text)" + f" OWNER TO {_VIEW_OWNER}" + ) + apply_view_ddl(sql=CLAIMS_CANONICAL_VIEW_DDL) + op.execute(f"ALTER VIEW memory_v1.claims_canonical OWNER TO {_VIEW_OWNER}") + op.execute( + """ + DO $do$ + DECLARE + query_role text := 'rememberstack_query_' || current_database(); + BEGIN + EXECUTE format( + 'GRANT EXECUTE ON FUNCTION' + ' memory_v1.canonical_bounds(timestamptz, timestamptz, text) TO %I', + query_role + ); + EXECUTE format( + 'GRANT SELECT ON memory_v1.claims_canonical TO %I', + query_role + ); + END + $do$; + """ + ) + + +def downgrade() -> None: + """Drop the published view and wrapper; public twins stay.""" + op.execute("DROP VIEW IF EXISTS memory_v1.claims_canonical") + op.execute( + "DROP FUNCTION IF EXISTS" + " memory_v1.canonical_bounds(timestamptz, timestamptz, text)" + ) + + +def _quote(value: str) -> str: + """One SQL string literal.""" + escaped = value.replace("'", "''") + return f"'{escaped}'" diff --git a/src/rememberstack/spine/query_space/catalog.py b/src/rememberstack/spine/query_space/catalog.py index c934febde..7d3a26860 100644 --- a/src/rememberstack/spine/query_space/catalog.py +++ b/src/rememberstack/spine/query_space/catalog.py @@ -440,6 +440,92 @@ class ViewContract(BaseModel): positive_fixture="claims_visible_history.superseded_testimony_present", negative_fixture="claims_visible_history.forgotten_lineage_claim_absent", ), + ViewContract( + name="claims_canonical", + grain=( + "one historically visible claim with surviving lineage and its" + " half-open canonical window" + ), + grain_tag="claim_visible_history_canonical", + clock_semantics="claim_validity_immutable", + row_key=("deployment_id", "claim_id"), + join_keys=( + JoinKey( + columns=("deployment_id", "doc_id"), target="memory_v1.documents_live" + ), + JoinKey( + columns=("deployment_id", "version_id"), + target="memory_v1.document_versions_visible", + ), + ), + not_null=frozenset( + { + "deployment_id", + "claim_id", + "doc_id", + "version_id", + "representation_id", + "chunk_id", + "claim_text", + "source_span", + "char_start", + "char_end", + "added_context", + "is_attributed", + "audit_status", + "kept_flagged", + "extractor_version", + "claim_valid_precision", + "ingested_at", + "source_kind", + "source_handle", + "is_current_testimony", + } + ), + enum_values={ + "temporal_class": _CLAIM_TEMPORAL_CLASS, + "audit_status": _GROUNDING_AUDIT_STATUS, + "claim_valid_precision": _CLAIM_VALID_PRECISION, + "claim_valid_kind": _CLAIM_VALID_KIND, + }, + column_types={ + "deployment_id": "uuid", + "claim_id": "uuid", + "doc_id": "uuid", + "version_id": "uuid", + "representation_id": "uuid", + "chunk_id": "uuid", + "claim_text": "text", + "source_span": "text", + "char_start": "integer", + "char_end": "integer", + "added_context": "jsonb", + "temporal_class": "text", + "is_attributed": "boolean", + "audit_status": "text", + "kept_flagged": "boolean", + "extractor_version": "text", + "asserted_at": "timestamp with time zone", + "claim_valid_from": "timestamp with time zone", + "claim_valid_until": "timestamp with time zone", + "claim_valid_precision": "text", + "claim_valid_kind": "text", + "ingested_at": "timestamp with time zone", + "source_kind": "text", + "source_handle": "text", + "is_current_testimony": "boolean", + "canon_start": "timestamp with time zone", + "canon_end": "timestamp with time zone", + }, + indexes_used=( + "ix_claims_doc", + "ix_claims_chunk", + "ix_claims_valid_window", + "ix_claims_canonical_window", + ), + positive_fixture="claims_canonical.superseded_testimony_present", + negative_fixture="claims_canonical.forgotten_lineage_claim_absent", + ), ViewContract( name="claims_live", grain="one current-testimony claim", diff --git a/src/rememberstack/spine/query_space/d48_deletion_matrix.json b/src/rememberstack/spine/query_space/d48_deletion_matrix.json index eb7213867..b4a70c764 100644 --- a/src/rememberstack/spine/query_space/d48_deletion_matrix.json +++ b/src/rememberstack/spine/query_space/d48_deletion_matrix.json @@ -1,5 +1,5 @@ { - "cell_count": 279, + "cell_count": 288, "cells": [ { "basis": null, @@ -22,6 +22,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "lineage" }, + { + "basis": null, + "expectation": "The lineage target's forbidden identifiers are reachable through memory_v1.claims_canonical before the mutation, and no column of any row carries one of them after it.", + "status": "applicable", + "surface": "memory_v1.claims_canonical", + "target_id": "lineage" + }, { "basis": null, "expectation": "The lineage target's forbidden identifiers are reachable through memory_v1.claims_live before the mutation, and no column of any row carries one of them after it.", @@ -239,6 +246,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "version" }, + { + "basis": null, + "expectation": "The version target's forbidden identifiers are reachable through memory_v1.claims_canonical before the mutation, and no column of any row carries one of them after it.", + "status": "applicable", + "surface": "memory_v1.claims_canonical", + "target_id": "version" + }, { "basis": "no_identifier_of_this_class", "expectation": "memory_v1.claims_live publishes none of the identifier classes this target forbids (version, representation, structure_generation, section, chunk, claim, mention, currency_event); the gate proves that nothing from the forbidden set is reachable here, before or after the mutation, rather than assuming it.", @@ -456,6 +470,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "representation" }, + { + "basis": "no_identifier_of_this_class", + "expectation": "memory_v1.claims_canonical publishes none of the identifier classes this target forbids (representation, structure_generation, section, chunk); the gate proves that nothing from the forbidden set is reachable here, before or after the mutation, rather than assuming it.", + "status": "not_applicable", + "surface": "memory_v1.claims_canonical", + "target_id": "representation" + }, { "basis": "no_identifier_of_this_class", "expectation": "memory_v1.claims_live publishes none of the identifier classes this target forbids (representation, structure_generation, section, chunk); the gate proves that nothing from the forbidden set is reachable here, before or after the mutation, rather than assuming it.", @@ -673,6 +694,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "claim" }, + { + "basis": null, + "expectation": "The claim target's forbidden identifiers are reachable through memory_v1.claims_canonical before the mutation, and no column of any row carries one of them after it.", + "status": "applicable", + "surface": "memory_v1.claims_canonical", + "target_id": "claim" + }, { "basis": null, "expectation": "The claim target's forbidden identifiers are reachable through memory_v1.claims_live before the mutation, and no column of any row carries one of them after it.", @@ -890,6 +918,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "fact_provenance" }, + { + "basis": "no_identifier_of_this_class", + "expectation": "memory_v1.claims_canonical publishes none of the identifier classes this target forbids (fact); the gate proves that nothing from the forbidden set is reachable here, before or after the mutation, rather than assuming it.", + "status": "not_applicable", + "surface": "memory_v1.claims_canonical", + "target_id": "fact_provenance" + }, { "basis": "no_identifier_of_this_class", "expectation": "memory_v1.claims_live publishes none of the identifier classes this target forbids (fact); the gate proves that nothing from the forbidden set is reachable here, before or after the mutation, rather than assuming it.", @@ -1107,6 +1142,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "k_target" }, + { + "basis": null, + "expectation": "The k_target target's forbidden identifiers are reachable through memory_v1.claims_canonical before the mutation, and no column of any row carries one of them after it.", + "status": "applicable", + "surface": "memory_v1.claims_canonical", + "target_id": "k_target" + }, { "basis": null, "expectation": "The k_target target's forbidden identifiers are reachable through memory_v1.claims_live before the mutation, and no column of any row carries one of them after it.", @@ -1324,6 +1366,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "p1_candidate" }, + { + "basis": null, + "expectation": "Deferred to Batch C: the P1 nomination path and the in-function PostgreSQL confirmation that drops a stale candidate are Batch C, so this cell is recorded here with the batch that will execute it rather than left out of the enumeration.", + "status": "deferred", + "surface": "memory_v1.claims_canonical", + "target_id": "p1_candidate" + }, { "basis": null, "expectation": "Deferred to Batch C: the P1 nomination path and the in-function PostgreSQL confirmation that drops a stale candidate are Batch C, so this cell is recorded here with the batch that will execute it rather than left out of the enumeration.", @@ -1541,6 +1590,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "graph_edge" }, + { + "basis": "no_identifier_of_this_class", + "expectation": "memory_v1.claims_canonical publishes none of the identifier classes this target forbids (fact); the gate proves that nothing from the forbidden set is reachable here, before or after the mutation, rather than assuming it.", + "status": "not_applicable", + "surface": "memory_v1.claims_canonical", + "target_id": "graph_edge" + }, { "basis": "no_identifier_of_this_class", "expectation": "memory_v1.claims_live publishes none of the identifier classes this target forbids (fact); the gate proves that nothing from the forbidden set is reachable here, before or after the mutation, rather than assuming it.", @@ -1758,6 +1814,13 @@ "surface": "memory_v1.claim_occurrences_live", "target_id": "corpus_body" }, + { + "basis": null, + "expectation": "Deferred to Batch C: the id-addressed chunk-body fetch and the corpus filesystem that return body bytes are Batch C, so this cell is recorded here with the batch that will execute it rather than left out of the enumeration.", + "status": "deferred", + "surface": "memory_v1.claims_canonical", + "target_id": "corpus_body" + }, { "basis": null, "expectation": "Deferred to Batch C: the id-addressed chunk-body fetch and the corpus filesystem that return body bytes are Batch C, so this cell is recorded here with the batch that will execute it rather than left out of the enumeration.", @@ -1958,11 +2021,11 @@ "contract": "memory_v1.d48_deletion_matrix/2", "schema": "memory_v1", "status_counts": { - "applicable": 80, - "deferred": 62, - "not_applicable": 137 + "applicable": 84, + "deferred": 64, + "not_applicable": 140 }, - "surface_count": 31, + "surface_count": 32, "surfaces": [ { "caller_reachable": true, @@ -1979,6 +2042,11 @@ "compiles_deletion": true, "name": "memory_v1.claim_occurrences_live" }, + { + "caller_reachable": true, + "compiles_deletion": true, + "name": "memory_v1.claims_canonical" + }, { "caller_reachable": true, "compiles_deletion": true, @@ -2127,6 +2195,7 @@ "memory_v1.changes_visible", "memory_v1.chunks_live", "memory_v1.claim_occurrences_live", + "memory_v1.claims_canonical", "memory_v1.claims_live", "memory_v1.claims_visible_history", "memory_v1.contradiction_members_current", @@ -2178,6 +2247,7 @@ { "applicable_surfaces": [ "memory_v1.changes_visible", + "memory_v1.claims_canonical", "memory_v1.claims_visible_history", "memory_v1.document_versions_visible", "memory_v1.testimony_currency_events_visible" @@ -2221,6 +2291,7 @@ "applicable_surfaces": [ "memory_v1.changes_visible", "memory_v1.claim_occurrences_live", + "memory_v1.claims_canonical", "memory_v1.claims_live", "memory_v1.claims_visible_history", "memory_v1.evidence_lineage", @@ -2268,6 +2339,7 @@ "memory_v1.changes_visible", "memory_v1.chunks_live", "memory_v1.claim_occurrences_live", + "memory_v1.claims_canonical", "memory_v1.claims_live", "memory_v1.claims_visible_history", "memory_v1.document_versions_visible", diff --git a/src/rememberstack/spine/query_space/deletion_matrix.py b/src/rememberstack/spine/query_space/deletion_matrix.py index dd366ef91..2ecdb34be 100644 --- a/src/rememberstack/spine/query_space/deletion_matrix.py +++ b/src/rememberstack/spine/query_space/deletion_matrix.py @@ -215,6 +215,7 @@ def deferred(self) -> bool: "memory_v1.changes_visible", "memory_v1.chunks_live", "memory_v1.claim_occurrences_live", + "memory_v1.claims_canonical", "memory_v1.claims_live", "memory_v1.claims_visible_history", "memory_v1.contradiction_members_current", @@ -265,6 +266,7 @@ def deferred(self) -> bool: executed_in="A", applicable_surfaces=( "memory_v1.changes_visible", + "memory_v1.claims_canonical", "memory_v1.claims_visible_history", "memory_v1.document_versions_visible", "memory_v1.testimony_currency_events_visible", @@ -309,6 +311,7 @@ def deferred(self) -> bool: applicable_surfaces=( "memory_v1.changes_visible", "memory_v1.claim_occurrences_live", + "memory_v1.claims_canonical", "memory_v1.claims_live", "memory_v1.claims_visible_history", "memory_v1.evidence_lineage", @@ -361,6 +364,7 @@ def deferred(self) -> bool: "memory_v1.changes_visible", "memory_v1.chunks_live", "memory_v1.claim_occurrences_live", + "memory_v1.claims_canonical", "memory_v1.claims_live", "memory_v1.claims_visible_history", "memory_v1.document_versions_visible", diff --git a/src/rememberstack/spine/query_space/manifest.py b/src/rememberstack/spine/query_space/manifest.py index 8653f98f2..e449c6f86 100644 --- a/src/rememberstack/spine/query_space/manifest.py +++ b/src/rememberstack/spine/query_space/manifest.py @@ -231,6 +231,27 @@ def _bridge_function_signatures() -> dict[str, CanonicalValue]: "parallel": "unsafe", } ) + functions.append( + { + "name": "canonical_bounds", + "target": "claims", + "channel": "temporal", + "arguments_min": 3, + "arguments_max": 3, + "arguments": [ + {"name": "valid_from", "type": "timestamptz", "required": True}, + {"name": "valid_until", "type": "timestamptz", "required": True}, + {"name": "valid_precision", "type": "text", "required": True}, + ], + "volatility": "immutable", + "security": "definer", + "filters": [], + "pre_rank_filters": [], + "columns": ["canon_start", "canon_end"], + "column_types": ["timestamptz", "timestamptz"], + "parallel": "safe", + } + ) functions.append( { # Pure SQL: it needs no projection, so PostgreSQL runs it directly diff --git a/src/rememberstack/spine/query_space/memory_v1_manifest.json b/src/rememberstack/spine/query_space/memory_v1_manifest.json index cd97749e1..43f5642c6 100644 --- a/src/rememberstack/spine/query_space/memory_v1_manifest.json +++ b/src/rememberstack/spine/query_space/memory_v1_manifest.json @@ -34,6 +34,18 @@ "chunk_claims_pkey" ] }, + "claims_canonical": { + "fixtures": { + "negative": "claims_canonical.forgotten_lineage_claim_absent", + "positive": "claims_canonical.superseded_testimony_present" + }, + "indexes_used": [ + "ix_claims_doc", + "ix_claims_chunk", + "ix_claims_valid_window", + "ix_claims_canonical_window" + ] + }, "claims_live": { "fixtures": { "negative": "claims_live.superseded_testimony_absent", @@ -7598,6 +7610,43 @@ "contract": "memory_v1.functions/1", "declared_without_signatures": [], "functions": [ + { + "arguments": [ + { + "name": "valid_from", + "required": true, + "type": "timestamptz" + }, + { + "name": "valid_until", + "required": true, + "type": "timestamptz" + }, + { + "name": "valid_precision", + "required": true, + "type": "text" + } + ], + "arguments_max": 3, + "arguments_min": 3, + "channel": "temporal", + "column_types": [ + "timestamptz", + "timestamptz" + ], + "columns": [ + "canon_start", + "canon_end" + ], + "filters": [], + "name": "canonical_bounds", + "parallel": "safe", + "pre_rank_filters": [], + "security": "definer", + "target": "claims", + "volatility": "immutable" + }, { "arguments": [ { @@ -8543,6 +8592,7 @@ "bool_and", "bool_or", "btrim", + "canonical_bounds", "cardinality", "ceil", "coalesce", @@ -8614,6 +8664,7 @@ "~~*" ], "public_functions": [ + "canonical_bounds", "facts_as_of", "fetch_chunk_bodies", "graph_citation_path", @@ -8628,6 +8679,7 @@ ], "recursion_depth_max": 6, "srf_categories": { + "canonical_bounds": "temporal", "facts_as_of": "bitemporal", "fetch_chunk_bodies": "body_fetch", "graph_citation_path": "graph", @@ -18820,6 +18872,918 @@ "nullable": true, "type": "timestamp with time zone" }, + { + "comment": "Immutable inclusive start of the world-time interval the SOURCE asserted, null for unbounded-before or unknown.", + "enum_values": null, + "name": "claim_valid_from", + "nullable": true, + "type": "timestamp with time zone" + }, + { + "comment": "Immutable inclusive end of that interval, null for open-per-source or unknown as disambiguated by claim_valid_precision.", + "enum_values": null, + "name": "claim_valid_until", + "nullable": true, + "type": "timestamp with time zone" + }, + { + "comment": "Granularity of the asserted interval, from unknown through instant, day, month, quarter, and year to open.", + "enum_values": [ + "unknown", + "instant", + "day", + "month", + "quarter", + "year", + "open" + ], + "name": "claim_valid_precision", + "nullable": false, + "type": "text" + }, + { + "comment": "Which world-interval was asserted, such as event_time or measurement_period; null when unclassified.", + "enum_values": [ + "proposition_validity", + "event_time", + "measurement_period", + "effective_period" + ], + "name": "claim_valid_kind", + "nullable": true, + "type": "text" + }, + { + "comment": "Transaction-time: when this deployment extracted the claim.", + "enum_values": null, + "name": "ingested_at", + "nullable": false, + "type": "timestamp with time zone" + }, + { + "comment": "The connector family of the asserting lineage.", + "enum_values": null, + "name": "source_kind", + "nullable": false, + "type": "text" + }, + { + "comment": "Stable human-usable handle for the asserting lineage, formed from its connector-native identity.", + "enum_values": null, + "name": "source_handle", + "nullable": false, + "type": "text" + }, + { + "comment": "True while this claim is the current transcription of its chunk under D54; false once a newer extraction generation or a living-mode version move superseded it.", + "enum_values": null, + "name": "is_current_testimony", + "nullable": false, + "type": "boolean" + }, + { + "comment": "Inclusive start of the half-open canonical window (D107 §5); null when precision is unknown.", + "enum_values": null, + "name": "canon_start", + "nullable": true, + "type": "timestamp with time zone" + }, + { + "comment": "Exclusive end of the half-open canonical window; null when the window is open or unknown.", + "enum_values": null, + "name": "canon_end", + "nullable": true, + "type": "timestamp with time zone" + } + ], + "comment": "One row per historically visible claim with surviving lineage, keyed by (deployment_id, claim_id), carrying the stored inclusive D41 window beside the half-open canonical bounds that every overlap predicate must use (D107 §5). canon_start is inclusive and canon_end exclusive; both are null when precision is unknown, and canon_end is also null for an open window. Overlap is a.start < b.end AND b.start < a.end with a null end as unbounded. This relation is IMMUTABLE SOURCE TESTIMONY: it never answers what currently holds. Claims of forgotten lineages and tombstoned versions are absent.", + "definition_ast": { + "@": "ViewStmt", + "aliases": [ + { + "@": "String", + "sval": "deployment_id" + }, + { + "@": "String", + "sval": "claim_id" + }, + { + "@": "String", + "sval": "doc_id" + }, + { + "@": "String", + "sval": "version_id" + }, + { + "@": "String", + "sval": "representation_id" + }, + { + "@": "String", + "sval": "chunk_id" + }, + { + "@": "String", + "sval": "claim_text" + }, + { + "@": "String", + "sval": "source_span" + }, + { + "@": "String", + "sval": "char_start" + }, + { + "@": "String", + "sval": "char_end" + }, + { + "@": "String", + "sval": "added_context" + }, + { + "@": "String", + "sval": "temporal_class" + }, + { + "@": "String", + "sval": "is_attributed" + }, + { + "@": "String", + "sval": "audit_status" + }, + { + "@": "String", + "sval": "kept_flagged" + }, + { + "@": "String", + "sval": "extractor_version" + }, + { + "@": "String", + "sval": "asserted_at" + }, + { + "@": "String", + "sval": "claim_valid_from" + }, + { + "@": "String", + "sval": "claim_valid_until" + }, + { + "@": "String", + "sval": "claim_valid_precision" + }, + { + "@": "String", + "sval": "claim_valid_kind" + }, + { + "@": "String", + "sval": "ingested_at" + }, + { + "@": "String", + "sval": "source_kind" + }, + { + "@": "String", + "sval": "source_handle" + }, + { + "@": "String", + "sval": "is_current_testimony" + }, + { + "@": "String", + "sval": "canon_start" + }, + { + "@": "String", + "sval": "canon_end" + } + ], + "query": { + "@": "SelectStmt", + "all": false, + "fromClause": [ + { + "@": "JoinExpr", + "isNatural": false, + "jointype": { + "#": "JoinType", + "name": "JOIN_INNER" + }, + "larg": { + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "h" + }, + "inh": true, + "relname": "claims_visible_history", + "relpersistence": "p", + "schemaname": "memory_v1" + }, + "rarg": { + "@": "RangeFunction", + "alias": { + "@": "Alias", + "aliasname": "b" + }, + "functions": [ + [ + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_until" + } + ] + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "memory_v1" + }, + { + "@": "String", + "sval": "canonical_bounds" + } + ] + }, + null + ] + ], + "is_rowsfrom": false, + "lateral": true, + "ordinality": false + }, + "rtindex": 0 + } + ], + "groupDistinct": false, + "limitOption": { + "#": "LimitOption", + "name": "LIMIT_OPTION_DEFAULT" + }, + "op": { + "#": "SetOperation", + "name": "SETOP_NONE" + }, + "targetList": [ + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_id" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "doc_id" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "version_id" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "representation_id" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "chunk_id" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_text" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "source_span" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "char_start" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "char_end" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "added_context" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "temporal_class" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "is_attributed" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "audit_status" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "kept_flagged" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "extractor_version" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "asserted_at" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_until" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_kind" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "ingested_at" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "source_kind" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "source_handle" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "is_current_testimony" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "b" + }, + { + "@": "String", + "sval": "canon_start" + } + ] + } + }, + { + "@": "ResTarget", + "val": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "b" + }, + { + "@": "String", + "sval": "canon_end" + } + ] + } + } + ] + }, + "replace": false, + "view": { + "@": "RangeVar", + "inh": true, + "relname": "claims_canonical", + "relpersistence": "p", + "schemaname": "memory_v1" + }, + "withCheckOption": { + "#": "ViewCheckOption", + "name": "NO_CHECK_OPTION" + } + }, + "grain": "one historically visible claim with surviving lineage and its half-open canonical window", + "grain_tag": "claim_visible_history_canonical", + "join_keys": [ + { + "columns": [ + "deployment_id", + "doc_id" + ], + "target": "memory_v1.documents_live" + }, + { + "columns": [ + "deployment_id", + "version_id" + ], + "target": "memory_v1.document_versions_visible" + } + ], + "name": "claims_canonical", + "qualified_name": "memory_v1.claims_canonical", + "row_key": [ + "deployment_id", + "claim_id" + ] + }, + { + "clock_semantics": "claim_validity_immutable", + "columns": [ + { + "comment": "The deployment that owns the claim.", + "enum_values": null, + "name": "deployment_id", + "nullable": false, + "type": "uuid" + }, + { + "comment": "Stable identity of this immutable claim.", + "enum_values": null, + "name": "claim_id", + "nullable": false, + "type": "uuid" + }, + { + "comment": "The live lineage that asserted the claim.", + "enum_values": null, + "name": "doc_id", + "nullable": false, + "type": "uuid" + }, + { + "comment": "The non-tombstoned version the claim was extracted from.", + "enum_values": null, + "name": "version_id", + "nullable": false, + "type": "uuid" + }, + { + "comment": "The reading whose character offsets the claim's anchors use.", + "enum_values": null, + "name": "representation_id", + "nullable": false, + "type": "uuid" + }, + { + "comment": "The chunk the claim was extracted from.", + "enum_values": null, + "name": "chunk_id", + "nullable": false, + "type": "uuid" + }, + { + "comment": "The standalone assertion as extracted, which is source testimony rather than adjudicated truth.", + "enum_values": null, + "name": "claim_text", + "nullable": false, + "type": "text" + }, + { + "comment": "The verbatim slice of the source the claim derives from.", + "enum_values": null, + "name": "source_span", + "nullable": false, + "type": "text" + }, + { + "comment": "Start character offset of source_span within the named representation's markdown.", + "enum_values": null, + "name": "char_start", + "nullable": false, + "type": "integer" + }, + { + "comment": "End character offset of source_span within the named representation's markdown.", + "enum_values": null, + "name": "char_end", + "nullable": false, + "type": "integer" + }, + { + "comment": "The substrings decontextualization added, each with the bundle source it came from.", + "enum_values": null, + "name": "added_context", + "nullable": false, + "type": "jsonb" + }, + { + "comment": "How the claim behaves over time, either static, dynamic, or atemporal; null when unclassified.", + "enum_values": [ + "static", + "dynamic", + "atemporal" + ], + "name": "temporal_class", + "nullable": true, + "type": "text" + }, + { + "comment": "True when the claim preserves an attribution, so it entails that someone said it rather than that it holds.", + "enum_values": null, + "name": "is_attributed", + "nullable": false, + "type": "boolean" + }, + { + "comment": "Result of the sampled independent grounding audit, defaulting to unaudited.", + "enum_values": [ + "unaudited", + "sampled_pass", + "sampled_fail", + "escalated" + ], + "name": "audit_status", + "nullable": false, + "type": "text" + }, + { + "comment": "True when selection kept the claim but marked it for review.", + "enum_values": null, + "name": "kept_flagged", + "nullable": false, + "type": "boolean" + }, + { + "comment": "The extractor generation that produced the claim, which is part of the D54 extraction basis.", + "enum_values": null, + "name": "extractor_version", + "nullable": false, + "type": "text" + }, + { + "comment": "Assertion-event time: when the source asserted this, null when the source carries no date.", + "enum_values": null, + "name": "asserted_at", + "nullable": true, + "type": "timestamp with time zone" + }, { "comment": "Immutable start of the world-time interval the SOURCE asserted, null for unbounded-before or unknown.", "enum_values": null, @@ -37492,5 +38456,5 @@ } }, "manifest_contract": "memory_v1.manifest/2", - "surface_manifest_hash": "3583f86ac5bb883481ba2cf4d9e7a0da1ac5e650ada140b97998fe273aa7edeb" + "surface_manifest_hash": "0b9e8091dea477a4f6e4c3ff99c9031971395edb8797cd5576bba9dce773d2fa" } diff --git a/src/rememberstack/spine/query_space/source_definitions.py b/src/rememberstack/spine/query_space/source_definitions.py index 9a2472b0b..bfcec19b5 100644 --- a/src/rememberstack/spine/query_space/source_definitions.py +++ b/src/rememberstack/spine/query_space/source_definitions.py @@ -59,6 +59,9 @@ from rememberstack.spine.migrations.versions.p9_14_0035_drop_entity_type import ( MEMORY_V1_TYPE_CUT_DDL, ) +from rememberstack.spine.migrations.versions.p9_27_0048_query_space_canonical_bounds import ( + CLAIMS_CANONICAL_VIEW_DDL, +) from rememberstack.spine.query_space.ast_serializer import serialize_definition from rememberstack.spine.query_space.canonical import CanonicalValue from rememberstack.spine.query_space.catalog import QUERY_SPACE_SCHEMA @@ -157,6 +160,7 @@ def _authored_parts() -> tuple[ GRAPH_EDGE_VIEW_DDL, FACT_AUTHORITY_DDL, MEMORY_V1_TYPE_CUT_DDL, + CLAIMS_CANONICAL_VIEW_DDL, ): statements.extend(_statements(sql=block)) for view, column, comment in view_column_comments(sql=block): diff --git a/src/rememberstack/surfaces/query_sandbox/bridge.py b/src/rememberstack/surfaces/query_sandbox/bridge.py index f406d82b1..1ca776b57 100644 --- a/src/rememberstack/surfaces/query_sandbox/bridge.py +++ b/src/rememberstack/surfaces/query_sandbox/bridge.py @@ -56,7 +56,13 @@ #: executor leaves their invocation in place and the planner sees straight #: through it; model-assisted P1 functions are resolved and substituted. SQL_NATIVE_FUNCTIONS: Final = frozenset( - {"facts_as_of", "graph_neighborhood", "graph_path", "graph_citation_path"} + { + "canonical_bounds", + "facts_as_of", + "graph_neighborhood", + "graph_path", + "graph_citation_path", + } ) #: Which adapter each public function actually needs. The SQL-native functions diff --git a/src/rememberstack/surfaces/query_sandbox/examples.py b/src/rememberstack/surfaces/query_sandbox/examples.py index 48653e0be..a24d26f50 100644 --- a/src/rememberstack/surfaces/query_sandbox/examples.py +++ b/src/rememberstack/surfaces/query_sandbox/examples.py @@ -19,6 +19,8 @@ from typing import Final from uuid import UUID +from rememberstack.core.open_query_prose import CLAIMS_AS_OF_PURPOSE +from rememberstack.core.open_query_prose import CLAIMS_AS_OF_SQL from rememberstack.core.open_query_prose import CLAIMS_VERBATIM_PURPOSE from rememberstack.core.open_query_prose import CLAIMS_VERBATIM_SQL @@ -48,25 +50,7 @@ " ORDER BY c.asserted_at DESC, c.claim_id" " LIMIT 50", ), - "claims_as_of": ( - "Claims whose immutable validity window overlaps an inclusive interval", - "SELECT c.claim_id, c.claim_text, c.source_handle," - " c.claim_valid_from, c.claim_valid_until, c.claim_valid_precision," - " (" - " SELECT count(*) FROM claims_visible_history AS u" - " WHERE u.claim_valid_precision = 'unknown'" - " AND u.claim_valid_from <= $2::timestamptz" - " AND (u.claim_valid_until IS NULL" - " OR u.claim_valid_until >= $1::timestamptz)" - " ) AS unknown_precision_excluded" - " FROM claims_visible_history AS c" - " WHERE c.claim_valid_precision <> 'unknown'" - " AND c.claim_valid_from <= $2::timestamptz" - " AND (c.claim_valid_until IS NULL" - " OR c.claim_valid_until >= $1::timestamptz)" - " ORDER BY c.claim_valid_from DESC, c.claim_id" - " LIMIT 50", - ), + "claims_as_of": (CLAIMS_AS_OF_PURPOSE, CLAIMS_AS_OF_SQL), "claims_hybrid_rrf": ( "Semantic and lexical claim channels fused by reciprocal rank", "WITH semantic AS (SELECT claim_id, rank FROM semantic_claims($1, 20))," diff --git a/src/rememberstack/surfaces/query_sandbox/grammar.py b/src/rememberstack/surfaces/query_sandbox/grammar.py index 6489e3c0f..fa026c4eb 100644 --- a/src/rememberstack/surfaces/query_sandbox/grammar.py +++ b/src/rememberstack/surfaces/query_sandbox/grammar.py @@ -50,6 +50,7 @@ # exists, with the store-phase taxonomy). PUBLIC_SRF_NAMES: Final = frozenset( { + "canonical_bounds", "facts_as_of", "semantic_claims", "semantic_chunks", @@ -78,6 +79,7 @@ "lexical_chunks": "nomination", "fetch_chunk_bodies": "body_fetch", "facts_as_of": "bitemporal", + "canonical_bounds": "temporal", "graph_neighborhood": "graph", "graph_path": "graph", "graph_citation_path": "graph", @@ -116,6 +118,7 @@ "date_trunc", "extract", "make_interval", + "canonical_bounds", "array_length", "cardinality", "jsonb_typeof", diff --git a/src/tests/benchmarks/test_locomo_protocol.py b/src/tests/benchmarks/test_locomo_protocol.py index 997e85983..9633964b8 100644 --- a/src/tests/benchmarks/test_locomo_protocol.py +++ b/src/tests/benchmarks/test_locomo_protocol.py @@ -246,10 +246,10 @@ def test_current_protocol_pins_manifest_and_complete_read_plane() -> None: assert len(tool_catalog_sha256()) == 64 -def test_protocol_is_v22_and_answer_prompt_has_reasoning_and_loop_guards() -> None: +def test_protocol_is_v23_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-v22" - assert DEFAULT_PROTOCOL_KEY == "full-v22" + assert PROTOCOL_NAME == "RS-LoCoMo-Full-v23" + assert DEFAULT_PROTOCOL_KEY == "full-v23" prompt = ANSWER_AGENT_PROMPT_TEMPLATE normalized_prompt = " ".join(prompt.split()) assert ( @@ -281,10 +281,10 @@ def test_protocol_is_v22_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-v22", "full-v22-gemma-vertex") - protocol = PROTOCOL_REGISTRY["full-v22"] + assert tuple(PROTOCOL_REGISTRY) == ("full-v23", "full-v23-gemma-vertex") + protocol = PROTOCOL_REGISTRY["full-v23"] - assert protocol.name == "RS-LoCoMo-Full-v22" + assert protocol.name == "RS-LoCoMo-Full-v23" assert protocol.answer_agent_model == "openai/gpt-5.6-luna" assert protocol.answer_agent_reasoning_effort == "none" assert protocol.judge_reasoning_effort == "none" @@ -322,7 +322,7 @@ def fake_prepare_run(**values: object) -> _Prepared: ) assert exit_code == 0 - assert selected == ["full-v22"] + assert selected == ["full-v23"] def test_summarize_cli_accepts_multiple_run_flags( @@ -460,12 +460,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 v22 pins, so its scores are + """The variant is a provider swap over identical v23 pins, so its scores are an answer-agent comparison rather than a new benchmark identity.""" - base = PROTOCOL_REGISTRY["full-v22"] - variant = PROTOCOL_REGISTRY["full-v22-gemma-vertex"] + base = PROTOCOL_REGISTRY["full-v23"] + variant = PROTOCOL_REGISTRY["full-v23-gemma-vertex"] - assert variant.name == "RS-LoCoMo-Full-v22-GemmaVertex" + assert variant.name == "RS-LoCoMo-Full-v23-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" @@ -503,7 +503,7 @@ def test_gemma_vertex_variant_swaps_only_the_answer_agent() -> None: base.judge_repetitions, base.answer_word_cap, ) - assert DEFAULT_PROTOCOL_KEY == "full-v22" + assert DEFAULT_PROTOCOL_KEY == "full-v23" def _write_run_json(*, run_dir: Path, protocol_key: str) -> None: @@ -539,7 +539,7 @@ def test_cli_composes_vertex_only_for_the_seats_the_protocol_pins( monkeypatch: pytest.MonkeyPatch, tmp_path: Path ) -> None: """Gemma routes to Vertex; the judge and embeddings stay on OpenRouter.""" - _write_run_json(run_dir=tmp_path, protocol_key="full-v22-gemma-vertex") + _write_run_json(run_dir=tmp_path, protocol_key="full-v23-gemma-vertex") monkeypatch.setenv("REMEMBERSTACK_OPENROUTER_API_KEY", "test-key") monkeypatch.setenv("REMEMBERSTACK_VERTEX_PROJECT_ID", "umc-locomo-vertex-lab") built: list[VertexSettings] = [] @@ -569,12 +569,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-v22") + _write_run_json(run_dir=tmp_path, protocol_key="full-v23") 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-v22") + raise AssertionError("Vertex must not be composed for full-v23") monkeypatch.setattr(cli, "VertexModelProvider", refuse) @@ -585,7 +585,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-v22-gemma-vertex") + _write_run_json(run_dir=tmp_path, protocol_key="full-v23-gemma-vertex") monkeypatch.setenv("REMEMBERSTACK_OPENROUTER_API_KEY", "test-key") monkeypatch.delenv("REMEMBERSTACK_VERTEX_PROJECT_ID", raising=False) diff --git a/src/tests/benchmarks/test_locomo_runner.py b/src/tests/benchmarks/test_locomo_runner.py index 48c52de53..1d2f9e541 100644 --- a/src/tests/benchmarks/test_locomo_runner.py +++ b/src/tests/benchmarks/test_locomo_runner.py @@ -1054,7 +1054,7 @@ def test_answer_persists_usage_when_provider_drifts_after_tool_call() -> None: "invalid_first_step_completions", "invalid_reader_completions", ), - (("full-v22", "openai/gpt-5.6-luna", "none", 0, 2),), + (("full-v23", "openai/gpt-5.6-luna", "none", 0, 2),), ) def test_staged_mock_run_uses_prepared_protocol_and_resumes( protocol: ProtocolKey, @@ -1687,7 +1687,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-v22 cannot silently process with document-local T0 disabled.""" + """Full-v23 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) @@ -1913,8 +1913,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-v22","protocol_fingerprint":' - '"a41cf907b69919b432726b66cb78edebe79e8ea825d955315a0d98f942488db5",' + '{"protocol_name":"RS-LoCoMo-Full-v23","protocol_fingerprint":' + '"188647c743a01d64a0c6fdf7e4d2a1a9759e53e534f4f350e7549140836e1b28",' '"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,' @@ -2133,7 +2133,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-v22" + assert prepared.protocol_name == "RS-LoCoMo-Full-v23" assert prepared.answer_agent_model == "openai/gpt-5.6-luna" assert prepared.answer_agent_reasoning_effort == "none" assert prepared.answer_reader_retry_budget == 2 diff --git a/src/tests/benchmarks/test_locomo_store_backup.py b/src/tests/benchmarks/test_locomo_store_backup.py index 8b4b7b29d..5195a0615 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-v22", + "protocol_name": "RS-LoCoMo-Full-v23", "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-v22", + protocol_name="RS-LoCoMo-Full-v23", 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-v22", + protocol_name="RS-LoCoMo-Full-v23", protocol_fingerprint="p" * 64, repository_revision=revision, prepared_at="2026-08-11T00:00:00Z", diff --git a/src/tests/spine/test_canonical_bounds_sql.py b/src/tests/spine/test_canonical_bounds_sql.py index d7b47a8e4..a48b2410d 100644 --- a/src/tests/spine/test_canonical_bounds_sql.py +++ b/src/tests/spine/test_canonical_bounds_sql.py @@ -140,6 +140,38 @@ def test_sql_twin_is_session_timezone_independent( assert row.e == expected.end, (session_zone, precision, "end") +def test_query_space_canonical_bounds_wraps_the_public_twins( + database_engine: Engine, +) -> None: + """memory_v1.canonical_bounds is the public twins, published as text precision.""" + valid_from = _ts("2022-01-01T00:00") + valid_until = _ts("2022-12-31T00:00") + expected = canonical_bounds( + valid_from=valid_from, valid_until=valid_until, precision="year" + ) + with database_engine.connect() as connection: + row = connection.execute( + text( + "SELECT canon_start, canon_end" + " FROM memory_v1.canonical_bounds(" + " CAST(:f AS timestamptz), CAST(:u AS timestamptz), 'year')" + ), + {"f": "2022-01-01T00:00+00:00", "u": "2022-12-31T00:00+00:00"}, + ).one() + unknown = connection.execute( + text( + "SELECT canon_start, canon_end" + " FROM memory_v1.canonical_bounds(" + " CAST(:f AS timestamptz), CAST(:u AS timestamptz), 'unknown')" + ), + {"f": "2022-01-01T00:00+00:00", "u": "2022-12-31T00:00+00:00"}, + ).one() + assert row.canon_start == expected.start + assert row.canon_end == expected.end + assert unknown.canon_start is None + assert unknown.canon_end is None + + def test_prompt_dates_render_the_utc_calendar_day() -> None: """A driver row in a non-UTC session zone must still print the UTC day.""" from zoneinfo import ZoneInfo diff --git a/src/tests/spine/test_migrations.py b/src/tests/spine/test_migrations.py index cf486fa93..2edcb2774 100644 --- a/src/tests/spine/test_migrations.py +++ b/src/tests/spine/test_migrations.py @@ -126,6 +126,7 @@ def test_revision_graph_is_one_linear_structural_chain() -> None: "p9_24_0045", "p9_25_0046", "p9_26_0047", + "p9_27_0048", ) assert len(script.get_heads()) == 1 @@ -664,7 +665,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_26_0047" + assert head_before_noop == head_after_noop == "p9_27_0048" assert _inventory(database_url=database_url) == restored_inventory diff --git a/src/tests/spine/test_query_space_batch_a.py b/src/tests/spine/test_query_space_batch_a.py index cfde08c47..7787858dc 100644 --- a/src/tests/spine/test_query_space_batch_a.py +++ b/src/tests/spine/test_query_space_batch_a.py @@ -1198,6 +1198,17 @@ def _fixture_cases(corpus: _Corpus) -> dict[str, tuple[str, dict[str, Any]]]: " WHERE claim_id = :claim)", {"claim": corpus.claim["erased"]}, ), + "claims_canonical.superseded_testimony_present": ( + f"SELECT EXISTS (SELECT 1 FROM {schema}.claims_canonical" + " WHERE claim_id = :claim AND NOT is_current_testimony" + " AND (claim_valid_precision = 'unknown' OR canon_start IS NOT NULL))", + {"claim": corpus.claim["old"]}, + ), + "claims_canonical.forgotten_lineage_claim_absent": ( + f"SELECT NOT EXISTS (SELECT 1 FROM {schema}.claims_canonical" + " WHERE claim_id = :claim)", + {"claim": corpus.claim["erased"]}, + ), "claims_live.current_testimony_present": ( f"SELECT EXISTS (SELECT 1 FROM {schema}.claims_live" " WHERE claim_id = :claim)", @@ -2689,7 +2700,7 @@ def test_corrupt_coordinates_leak_no_identifier_through_any_surface( public_surfaces = tuple( surface for surface in MATRIX_SURFACES if surface.caller_reachable ) - assert len(public_surfaces) == 24 + assert len(public_surfaces) == len(VIEW_CONTRACTS) leaks = { surface.name: _reachable_values( connection=connection, relation=surface.name, forbidden=forbidden diff --git a/src/tests/spine/test_query_space_manifest.py b/src/tests/spine/test_query_space_manifest.py index 201d96ba3..e6f04a0da 100644 --- a/src/tests/spine/test_query_space_manifest.py +++ b/src/tests/spine/test_query_space_manifest.py @@ -166,6 +166,7 @@ def test_checked_in_manifest_binds_the_later_members_structurally() -> None: # vocabulary, and the columns it answers with, so a caller can read the # contract without executing anything. assert {entry["name"] for entry in published} == { # type: ignore[index] + "canonical_bounds", "facts_as_of", "fetch_chunk_bodies", "graph_citation_path", @@ -239,6 +240,7 @@ def test_checked_in_manifest_binds_the_later_members_structurally() -> None: grammar = limits["sql_grammar"] assert isinstance(grammar, dict) assert grammar["public_functions"] == [ + "canonical_bounds", "facts_as_of", "fetch_chunk_bodies", "graph_citation_path", @@ -307,7 +309,7 @@ def test_manifest_covers_exactly_the_declared_relations() -> None: names = [str(view["name"]) for view in views if isinstance(view, dict)] assert names == sorted(names) assert set(names) == {contract.name for contract in VIEW_CONTRACTS} - assert len(names) == 24 + assert len(names) == len(VIEW_CONTRACTS) def test_deletion_matrix_artifact_matches_its_generator() -> None: diff --git a/src/tests/surfaces/test_open_query_batch_f.py b/src/tests/surfaces/test_open_query_batch_f.py index 1b667cfc2..b4763486b 100644 --- a/src/tests/surfaces/test_open_query_batch_f.py +++ b/src/tests/surfaces/test_open_query_batch_f.py @@ -961,7 +961,7 @@ def test_core_prose_is_authority_for_live_graph_and_claims_verbatim() -> None: assert "memory_v1.graph_neighborhood" in graph_entry["example"] assert ( load_manifest()["surface_manifest_hash"] - == "3583f86ac5bb883481ba2cf4d9e7a0da1ac5e650ada140b97998fe273aa7edeb" + == "0b9e8091dea477a4f6e4c3ff99c9031971395edb8797cd5576bba9dce773d2fa" ) diff --git a/src/tests/surfaces/test_query_sandbox_batch_b.py b/src/tests/surfaces/test_query_sandbox_batch_b.py index 371888c3d..423d654de 100644 --- a/src/tests/surfaces/test_query_sandbox_batch_b.py +++ b/src/tests/surfaces/test_query_sandbox_batch_b.py @@ -23,6 +23,7 @@ from sqlalchemy.engine import make_url from rememberstack.spine.query_space import load_manifest +from rememberstack.spine.query_space import VIEW_CONTRACTS from rememberstack.spine.settings import load_database_settings from rememberstack.surfaces.query_sandbox.audit import AuditTrail from rememberstack.surfaces.query_sandbox.audit import KillSwitches @@ -520,7 +521,7 @@ def test_discovery_serves_manifest_and_headline() -> None: description = describe_query_space() members = load_manifest()["hash_members"] assert description.schema == "memory_v1" - assert len(description.views) == 24 + assert len(description.views) == len(VIEW_CONTRACTS) assert description.headline == TWO_LAYER_HEADLINE_FULL assert set(description.functions) == PUBLIC_SRF_NAMES assert description.limits == { diff --git a/src/tests/surfaces/test_retrieval_batch_b.py b/src/tests/surfaces/test_retrieval_batch_b.py index 934c3ceaf..fe82e99ea 100644 --- a/src/tests/surfaces/test_retrieval_batch_b.py +++ b/src/tests/surfaces/test_retrieval_batch_b.py @@ -18,6 +18,7 @@ from rememberstack.adapters import PostgresP1Index from rememberstack.adapters.testing import FakeModelProvider +from rememberstack.core.temporal import inclusive_request from rememberstack.model import DeploymentBootstrapInput from rememberstack.model import EmbeddingRequest from rememberstack.model import NegativeKind @@ -548,6 +549,40 @@ def test_claims_as_of_intersects_open_windows_and_counts_unknown( assert answer.excluded_unstamped == 1 +def test_claims_canonical_unknown_count_and_overlap_match_engine_as_of( + corpus: _Corpus, +) -> None: + """WP-T.0b: the open-SQL view matches the engine as-of set and counts unknown.""" + answer = corpus.query_engine().claims_as_of( + deployment_id=_DEPLOYMENT_ID, from_=_WINDOW_FROM, to=_WINDOW_TO, k=20 + ) + window = inclusive_request(from_=_WINDOW_FROM, to=_WINDOW_TO) + with corpus.engine.connect() as connection: + unknown = int( + connection.execute( + text( + "SELECT count(*) FROM memory_v1.claims_canonical" + " WHERE claim_valid_precision = 'unknown'" + ) + ).scalar_one() + ) + overlap = { + row[0] + for row in connection.execute( + text( + "SELECT claim_id FROM memory_v1.claims_canonical" + " WHERE claim_valid_precision <> 'unknown'" + " AND canon_start < :to_exclusive" + " AND (canon_end IS NULL OR canon_end > :from_instant)" + ), + {"from_instant": window.start, "to_exclusive": window.end}, + ) + } + assert unknown > 0 + assert unknown == answer.excluded_unstamped + assert overlap == {claim.claim_id for claim in answer.evidence} + + def test_claims_as_of_excludes_tombstoned_lineages_before_candidate_bound( corpus: _Corpus, ) -> None: diff --git a/src/tests/surfaces/test_saved_queries_batch_e.py b/src/tests/surfaces/test_saved_queries_batch_e.py index 3b8d6486f..8371e6bb2 100644 --- a/src/tests/surfaces/test_saved_queries_batch_e.py +++ b/src/tests/surfaces/test_saved_queries_batch_e.py @@ -1578,9 +1578,9 @@ def test_the_shipped_examples_are_the_eighteen_the_design_maps() -> None: "claims_verbatim": ("semantic_claims", "claims_live", "JOIN"), "claims_about": ("mentions_live", "claim_occurrences_live", "claims_live"), "claims_as_of": ( - "claims_visible_history", - "claim_valid_from <= $2", - "claim_valid_until >= $1", + "claims_canonical", + "canon_start <", + "canon_end > $1", "unknown", ), "claims_hybrid_rrf": ("semantic_claims", "lexical_claims"), @@ -1628,9 +1628,13 @@ def test_example_bodies_match_section_2_mappings() -> None: def test_claims_as_of_uses_two_parameter_inclusive_overlap() -> None: sql = EXAMPLE_QUERIES["claims_as_of"][1] assert "$1::timestamptz" in sql and "$2::timestamptz" in sql - assert "claim_valid_from <= $2" in sql - assert "claim_valid_until >= $1" in sql + assert "claims_canonical" in sql + assert "canon_start <" in sql + assert "canon_end > $1" in sql + assert "1 microsecond" in sql assert "unknown" in sql + assert "claim_valid_from <=" not in sql + assert "claim_valid_until >=" not in sql def test_always_empty_substitution_fails_positive(registry_url: str) -> None: diff --git a/website/src/app/docs/project-status/page.mdx b/website/src/app/docs/project-status/page.mdx index a116f4b36..59dbcf18d 100644 --- a/website/src/app/docs/project-status/page.mdx +++ b/website/src/app/docs/project-status/page.mdx @@ -178,7 +178,10 @@ adjudication uses the same bounds and the partial expression index used by `claims_as_of`; claim storage is unchanged. Observation generations roll, so rebuilding changes stored ingestion provenance, and `claims_as_of` results change under the corrected -window semantics. +window semantics. Migration `p9_27_0048` publishes those bounds to open SQL as +`memory_v1.canonical_bounds` and `claims_canonical`; the shipped +`examples.claims_as_of` query overlaps the canonical window and counts +unknown-precision claims by precision. **A release now carries the API contract beside the binaries.** The generated `openapi.json` is attached to the GitHub release, so client generation can pin @@ -299,7 +302,11 @@ examined, and the failure looks like the deployment being down. retrieval, retry, reasoning-effort, or call-budget work. - Historical `RS-LoCoMo-Full-v20` also requires every distinct retrieved value that directly satisfies the question. It does not add a retrieval or retry. -- The current `RS-LoCoMo-Full-v22` pins canonical half-open claim bounds +- The current `RS-LoCoMo-Full-v23` pins the query-space publication of those + bounds (D107 WP-T.0b): `memory_v1.canonical_bounds`, `claims_canonical`, and + the rewritten `examples.claims_as_of`. Ingestion and the library + `claims_as_of` path are unchanged from v22; the surface manifest hash rolls. +- Historical `RS-LoCoMo-Full-v22` pins canonical half-open claim bounds (D107 WP-T.0a): a day-precision claim is found from an intraday `claims_as_of` window and the observation adjudicator no longer treats a day as a zero-width point. Ingestion provenance and `claims_as_of` results change; the diff --git a/website/src/app/docs/retrieval/open-query/page.mdx b/website/src/app/docs/retrieval/open-query/page.mdx index cde57952f..12dfd131a 100644 --- a/website/src/app/docs/retrieval/open-query/page.mdx +++ b/website/src/app/docs/retrieval/open-query/page.mdx @@ -55,6 +55,12 @@ WHERE claim_valid_from <= $1::timestamptz Claim validity is **source-asserted testimony**, not system belief. +World-time overlap on claims uses the **half-open canonical window** +(`claims_canonical.canon_start` / `canon_end`, or `canonical_bounds(...)`). +A stored day is the whole calendar day; an instant is a non-empty point; +unknown precision has no interval and is counted by precision, not by bounds. +The shipped `examples.claims_as_of` query is the honest pattern. + **RIGHT — start from adjudicated current facts, join testimony:** ```sql From e0f7c3e3cd5a89d8d5f237a7141b5e4ca695df82 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Fri, 4 Sep 2026 18:39:08 +0200 Subject: [PATCH 2/6] fix(temporal): apply WP-T.0b round-1 Codex and Antigravity review Default sharded prepare to full-v23. Project public twins in claims_canonical instead of a lateral SECURITY DEFINER SRF, mark the SRF ROWS 1, stop claiming the expression index, and point claims_visible_history/claims_live comments at the canonical overlap. Remove the dead FUNCTION_ALLOWLIST entry, run the shipped examples.claims_as_of SQL in the acceptance proof, and regenerate the surface hash / Full-v23 fingerprint. --- benchmarks/locomo/README.md | 6 +- benchmarks/locomo/protocol.py | 2 +- benchmarks/locomo/sharding/run_shard.sh | 4 +- src/rememberstack/core/open_query_prose.py | 6 +- ...p9_27_0048_query_space_canonical_bounds.py | 37 ++- .../spine/query_space/catalog.py | 7 +- .../spine/query_space/memory_v1_manifest.json | 239 ++++++++++-------- .../spine/query_space/source_definitions.py | 4 + .../surfaces/query_sandbox/grammar.py | 1 - src/tests/benchmarks/test_locomo_runner.py | 4 +- src/tests/spine/test_canonical_bounds_sql.py | 37 +-- src/tests/spine/test_query_space_batch_a.py | 9 +- src/tests/surfaces/test_open_query_batch_f.py | 2 +- src/tests/surfaces/test_retrieval_batch_b.py | 53 ++-- .../app/docs/retrieval/open-query/page.mdx | 13 +- 15 files changed, 245 insertions(+), 179 deletions(-) diff --git a/benchmarks/locomo/README.md b/benchmarks/locomo/README.md index cf455373e..e0b64d84a 100644 --- a/benchmarks/locomo/README.md +++ b/benchmarks/locomo/README.md @@ -163,9 +163,9 @@ 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-v22-gemma-vertex`) +## Gemma 4 on Vertex as the answer agent (`full-v23-gemma-vertex`) -`full-v22-gemma-vertex` is a *variant* of `full-v22`, not a new benchmark +`full-v23-gemma-vertex` is a *variant* of `full-v23`, 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 @@ -194,7 +194,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-v22-gemma-vertex \ + --protocol full-v23-gemma-vertex \ --output .benchmark-runs/locomo-gemma-smoke ``` diff --git a/benchmarks/locomo/protocol.py b/benchmarks/locomo/protocol.py index 429f78040..7d5244c2a 100644 --- a/benchmarks/locomo/protocol.py +++ b/benchmarks/locomo/protocol.py @@ -45,7 +45,7 @@ EXPECTED_DOCUMENT_BINDING_GENERATION: Final = "document-t0-v1" EXPECTED_SURFACE_MANIFEST_HASH: Final = ( - "0b9e8091dea477a4f6e4c3ff99c9031971395edb8797cd5576bba9dce773d2fa" + "2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870" ) EXPECTED_PIPELINE_STAGES: Final = ( "convert", diff --git a/benchmarks/locomo/sharding/run_shard.sh b/benchmarks/locomo/sharding/run_shard.sh index 95a9a536a..c0b5d0c70 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-v22} +protocol=${LOCOMO_PROTOCOL:-full-v23} mount_root=${LOCOMO_MOUNT_ROOT:-$run_dir/.mounts} max_documents=${LOCOMO_MAX_DOCUMENTS:-100} max_questions=${LOCOMO_MAX_QUESTIONS:-1540} @@ -59,7 +59,7 @@ backup_python() { "$python_bin" "$@" } -# RS-LoCoMo-Full-v22's non-secret ingest identity. Override ambient self-host +# RS-LoCoMo-Full-v23'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 diff --git a/src/rememberstack/core/open_query_prose.py b/src/rememberstack/core/open_query_prose.py index e70bc4228..62980883e 100644 --- a/src/rememberstack/core/open_query_prose.py +++ b/src/rememberstack/core/open_query_prose.py @@ -171,8 +171,10 @@ "Claims are immutable source testimony; they do not answer current-truth" " questions.", "Claim world-time overlap is half-open on claims_canonical.canon_start /" - " canon_end (or memory_v1.canonical_bounds); unknown-precision claims have" - " no interval and are counted by precision, never by bounds.", + " canon_end. memory_v1.canonical_bounds is a top-level FROM function that" + " canonicalises an explicit window; it is not a row expression. Unknown-" + "precision claims have no interval and are counted by precision, never by" + " bounds.", "Empty SQL is untyped exploratory_tabular: a view's source grain is never" " a claim about an arbitrary outer query's result grain.", "Graph helper absence is bounded by the disclosed traversal budgets; inspect" diff --git a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py index 992f1b115..c1aaa5515 100644 --- a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py +++ b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py @@ -32,6 +32,7 @@ PARALLEL SAFE SECURITY DEFINER SET search_path = public, pg_catalog +ROWS 1 AS $$ SELECT claim_canonical_start( @@ -99,18 +100,27 @@ h.source_kind, h.source_handle, h.is_current_testimony, - b.canon_start, - b.canon_end -FROM memory_v1.claims_visible_history AS h -CROSS JOIN LATERAL memory_v1.canonical_bounds( - h.claim_valid_from, - h.claim_valid_until, - h.claim_valid_precision -) AS b; + claim_canonical_start( + h.claim_valid_from, + h.claim_valid_precision::claim_valid_precision + ), + claim_canonical_end( + h.claim_valid_from, + h.claim_valid_until, + h.claim_valid_precision::claim_valid_precision + ) +FROM memory_v1.claims_visible_history AS h; COMMENT ON VIEW memory_v1.claims_canonical IS 'One row per historically visible claim with surviving lineage, keyed by (deployment_id, claim_id), carrying the stored inclusive D41 window beside the half-open canonical bounds that every overlap predicate must use (D107 §5). canon_start is inclusive and canon_end exclusive; both are null when precision is unknown, and canon_end is also null for an open window. Overlap is a.start < b.end AND b.start < a.end with a null end as unbounded. This relation is IMMUTABLE SOURCE TESTIMONY: it never answers what currently holds. Claims of forgotten lineages and tombstoned versions are absent.'; """ +CLAIMS_CLOCK_COMMENT_DDL = r""" +COMMENT ON VIEW memory_v1.claims_visible_history IS + 'One row per claim whose source lineage is live and whose source version is not tombstoned, keyed by (deployment_id, claim_id) and joined to documents_live on (deployment_id, doc_id) and to document_versions_visible on (deployment_id, version_id). This relation is IMMUTABLE SOURCE TESTIMONY and never answers what currently holds: claim_valid_from and claim_valid_until are the inclusive stored D41 window (an instant has equal endpoints). World-time overlap MUST use claims_canonical.canon_start / canon_end, which are the half-open canonical bounds; filtering these raw columns as a current-truth or overlap predicate is the wrong query — use facts_current for what holds now, and claims_canonical for as-of testimony. A null claim_valid_from means unbounded-before or unknown and a null claim_valid_until means open-per-source or unknown, disambiguated by claim_valid_precision. Claims of forgotten lineages and tombstoned versions are absent; is_current_testimony is D54 bookkeeping and never validity. The view carries no counts.'; +COMMENT ON VIEW memory_v1.claims_live IS + 'One row per current-testimony claim, keyed by (deployment_id, claim_id): the subset of claims_visible_history whose D54 currency flag is still set. Like every claim relation this is IMMUTABLE SOURCE TESTIMONY, and "live" here means current transcription of a live source, never current truth: a claim in this relation can be contradicted by the adjudicated worldview, and querying its validity window to answer what holds now is the wrong query — start from facts_current and follow fact_claim_evidence_live back to here. The stored claim_valid_* window is inclusive D41 storage; world-time overlap belongs on claims_canonical. Claims of forgotten lineages and tombstoned versions are absent, and this relation is the sole claim input to the D54 counting path. The view carries no counts.'; +""" + def upgrade() -> None: """Publish the wrapper function and the claims_canonical view.""" @@ -141,6 +151,7 @@ def upgrade() -> None: f" OWNER TO {_VIEW_OWNER}" ) apply_view_ddl(sql=CLAIMS_CANONICAL_VIEW_DDL) + op.execute(CLAIMS_CLOCK_COMMENT_DDL) op.execute(f"ALTER VIEW memory_v1.claims_canonical OWNER TO {_VIEW_OWNER}") op.execute( """ @@ -170,6 +181,16 @@ def downgrade() -> None: "DROP FUNCTION IF EXISTS" " memory_v1.canonical_bounds(timestamptz, timestamptz, text)" ) + op.execute( + "REVOKE EXECUTE ON FUNCTION" + " claim_canonical_start(timestamptz, claim_valid_precision)" + f" FROM {_VIEW_OWNER}" + ) + op.execute( + "REVOKE EXECUTE ON FUNCTION" + " claim_canonical_end(timestamptz, timestamptz, claim_valid_precision)" + f" FROM {_VIEW_OWNER}" + ) def _quote(value: str) -> str: diff --git a/src/rememberstack/spine/query_space/catalog.py b/src/rememberstack/spine/query_space/catalog.py index 7d3a26860..e09e984d4 100644 --- a/src/rememberstack/spine/query_space/catalog.py +++ b/src/rememberstack/spine/query_space/catalog.py @@ -517,12 +517,7 @@ class ViewContract(BaseModel): "canon_start": "timestamp with time zone", "canon_end": "timestamp with time zone", }, - indexes_used=( - "ix_claims_doc", - "ix_claims_chunk", - "ix_claims_valid_window", - "ix_claims_canonical_window", - ), + indexes_used=("ix_claims_doc", "ix_claims_chunk", "ix_claims_valid_window"), positive_fixture="claims_canonical.superseded_testimony_present", negative_fixture="claims_canonical.forgotten_lineage_claim_absent", ), diff --git a/src/rememberstack/spine/query_space/memory_v1_manifest.json b/src/rememberstack/spine/query_space/memory_v1_manifest.json index 43f5642c6..d468e62cd 100644 --- a/src/rememberstack/spine/query_space/memory_v1_manifest.json +++ b/src/rememberstack/spine/query_space/memory_v1_manifest.json @@ -42,8 +42,7 @@ "indexes_used": [ "ix_claims_doc", "ix_claims_chunk", - "ix_claims_valid_window", - "ix_claims_canonical_window" + "ix_claims_valid_window" ] }, "claims_live": { @@ -8592,7 +8591,6 @@ "bool_and", "bool_or", "btrim", - "canonical_bounds", "cardinality", "ceil", "coalesce", @@ -19074,101 +19072,15 @@ "all": false, "fromClause": [ { - "@": "JoinExpr", - "isNatural": false, - "jointype": { - "#": "JoinType", - "name": "JOIN_INNER" - }, - "larg": { - "@": "RangeVar", - "alias": { - "@": "Alias", - "aliasname": "h" - }, - "inh": true, - "relname": "claims_visible_history", - "relpersistence": "p", - "schemaname": "memory_v1" - }, - "rarg": { - "@": "RangeFunction", - "alias": { - "@": "Alias", - "aliasname": "b" - }, - "functions": [ - [ - { - "@": "FuncCall", - "agg_distinct": false, - "agg_star": false, - "agg_within_group": false, - "args": [ - { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "claim_valid_from" - } - ] - }, - { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "claim_valid_until" - } - ] - }, - { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "claim_valid_precision" - } - ] - } - ], - "func_variadic": false, - "funcformat": { - "#": "CoercionForm", - "name": "COERCE_EXPLICIT_CALL" - }, - "funcname": [ - { - "@": "String", - "sval": "memory_v1" - }, - { - "@": "String", - "sval": "canonical_bounds" - } - ] - }, - null - ] - ], - "is_rowsfrom": false, - "lateral": true, - "ordinality": false + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "h" }, - "rtindex": 0 + "inh": true, + "relname": "claims_visible_history", + "relpersistence": "p", + "schemaname": "memory_v1" } ], "groupDistinct": false, @@ -19584,15 +19496,62 @@ { "@": "ResTarget", "val": { - "@": "ColumnRef", - "fields": [ + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ { - "@": "String", - "sval": "b" + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] }, + { + "@": "TypeCast", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "claim_valid_precision" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ { "@": "String", - "sval": "canon_start" + "sval": "claim_canonical_start" } ] } @@ -19600,15 +19559,75 @@ { "@": "ResTarget", "val": { - "@": "ColumnRef", - "fields": [ + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ { - "@": "String", - "sval": "b" + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_until" + } + ] + }, + { + "@": "TypeCast", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "claim_valid_precision" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ { "@": "String", - "sval": "canon_end" + "sval": "claim_canonical_end" } ] } @@ -19847,7 +19866,7 @@ "type": "text" } ], - "comment": "One row per current-testimony claim, keyed by (deployment_id, claim_id): the subset of claims_visible_history whose D54 currency flag is still set. Like every claim relation this is IMMUTABLE SOURCE TESTIMONY, and \"live\" here means current transcription of a live source, never current truth: a claim in this relation can be contradicted by the adjudicated worldview, and querying its validity window to answer what holds now is the wrong query — start from facts_current and follow fact_claim_evidence_live back to here. Claim-evidence overlap is inclusive at both endpoints; a null endpoint is unbounded or unknown per claim_valid_precision. Claims of forgotten lineages and tombstoned versions are absent, and this relation is the sole claim input to the D54 counting path. The view carries no counts.", + "comment": "One row per current-testimony claim, keyed by (deployment_id, claim_id): the subset of claims_visible_history whose D54 currency flag is still set. Like every claim relation this is IMMUTABLE SOURCE TESTIMONY, and \"live\" here means current transcription of a live source, never current truth: a claim in this relation can be contradicted by the adjudicated worldview, and querying its validity window to answer what holds now is the wrong query — start from facts_current and follow fact_claim_evidence_live back to here. The stored claim_valid_* window is inclusive D41 storage; world-time overlap belongs on claims_canonical. Claims of forgotten lineages and tombstoned versions are absent, and this relation is the sole claim input to the D54 counting path. The view carries no counts.", "definition_ast": { "@": "ViewStmt", "aliases": [ @@ -20612,7 +20631,7 @@ "type": "boolean" } ], - "comment": "One row per claim whose source lineage is live and whose source version is not tombstoned, keyed by (deployment_id, claim_id) and joined to documents_live on (deployment_id, doc_id) and to document_versions_visible on (deployment_id, version_id). This relation is IMMUTABLE SOURCE TESTIMONY and never answers what currently holds: claim_valid_from and claim_valid_until say when a source asserted a proposition applied, not what the system believes now, and filtering them by an instant is the classic wrong current-truth query — use facts_current instead. Claim-evidence overlap is INCLUSIVE at both endpoints, because an instant-precision claim has equal endpoints that a half-open convention would make empty. A null claim_valid_from means unbounded-before or unknown and a null claim_valid_until means open-per-source or unknown, disambiguated by claim_valid_precision. Claims of forgotten lineages and tombstoned versions are absent; is_current_testimony is D54 bookkeeping and never validity. The view carries no counts.", + "comment": "One row per claim whose source lineage is live and whose source version is not tombstoned, keyed by (deployment_id, claim_id) and joined to documents_live on (deployment_id, doc_id) and to document_versions_visible on (deployment_id, version_id). This relation is IMMUTABLE SOURCE TESTIMONY and never answers what currently holds: claim_valid_from and claim_valid_until are the inclusive stored D41 window (an instant has equal endpoints). World-time overlap MUST use claims_canonical.canon_start / canon_end, which are the half-open canonical bounds; filtering these raw columns as a current-truth or overlap predicate is the wrong query — use facts_current for what holds now, and claims_canonical for as-of testimony. A null claim_valid_from means unbounded-before or unknown and a null claim_valid_until means open-per-source or unknown, disambiguated by claim_valid_precision. Claims of forgotten lineages and tombstoned versions are absent; is_current_testimony is D54 bookkeeping and never validity. The view carries no counts.", "definition_ast": { "@": "ViewStmt", "aliases": [ @@ -38456,5 +38475,5 @@ } }, "manifest_contract": "memory_v1.manifest/2", - "surface_manifest_hash": "0b9e8091dea477a4f6e4c3ff99c9031971395edb8797cd5576bba9dce773d2fa" + "surface_manifest_hash": "2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870" } diff --git a/src/rememberstack/spine/query_space/source_definitions.py b/src/rememberstack/spine/query_space/source_definitions.py index bfcec19b5..a5f47a829 100644 --- a/src/rememberstack/spine/query_space/source_definitions.py +++ b/src/rememberstack/spine/query_space/source_definitions.py @@ -62,6 +62,9 @@ from rememberstack.spine.migrations.versions.p9_27_0048_query_space_canonical_bounds import ( CLAIMS_CANONICAL_VIEW_DDL, ) +from rememberstack.spine.migrations.versions.p9_27_0048_query_space_canonical_bounds import ( + CLAIMS_CLOCK_COMMENT_DDL, +) from rememberstack.spine.query_space.ast_serializer import serialize_definition from rememberstack.spine.query_space.canonical import CanonicalValue from rememberstack.spine.query_space.catalog import QUERY_SPACE_SCHEMA @@ -161,6 +164,7 @@ def _authored_parts() -> tuple[ FACT_AUTHORITY_DDL, MEMORY_V1_TYPE_CUT_DDL, CLAIMS_CANONICAL_VIEW_DDL, + CLAIMS_CLOCK_COMMENT_DDL, ): statements.extend(_statements(sql=block)) for view, column, comment in view_column_comments(sql=block): diff --git a/src/rememberstack/surfaces/query_sandbox/grammar.py b/src/rememberstack/surfaces/query_sandbox/grammar.py index fa026c4eb..1b845728e 100644 --- a/src/rememberstack/surfaces/query_sandbox/grammar.py +++ b/src/rememberstack/surfaces/query_sandbox/grammar.py @@ -118,7 +118,6 @@ "date_trunc", "extract", "make_interval", - "canonical_bounds", "array_length", "cardinality", "jsonb_typeof", diff --git a/src/tests/benchmarks/test_locomo_runner.py b/src/tests/benchmarks/test_locomo_runner.py index 1d2f9e541..d2275b045 100644 --- a/src/tests/benchmarks/test_locomo_runner.py +++ b/src/tests/benchmarks/test_locomo_runner.py @@ -1914,7 +1914,7 @@ def test_single_run_summary_json_is_unchanged( assert serialized == ( '{"protocol_name":"RS-LoCoMo-Full-v23","protocol_fingerprint":' - '"188647c743a01d64a0c6fdf7e4d2a1a9759e53e534f4f350e7549140836e1b28",' + '"3fd2198d5c7c0075b0fe5c36022e38c3efd4727507e8252ad479b4af269fdafc",' '"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,' @@ -3403,7 +3403,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-v22-gemma-vertex"] + protocol = PROTOCOL_REGISTRY["full-v23-gemma-vertex"] configuration = RunConfiguration( protocol_name=protocol.name, adapter_version="synthetic", diff --git a/src/tests/spine/test_canonical_bounds_sql.py b/src/tests/spine/test_canonical_bounds_sql.py index a48b2410d..136de7aff 100644 --- a/src/tests/spine/test_canonical_bounds_sql.py +++ b/src/tests/spine/test_canonical_bounds_sql.py @@ -140,36 +140,43 @@ def test_sql_twin_is_session_timezone_independent( assert row.e == expected.end, (session_zone, precision, "end") +@pytest.mark.parametrize( + ("precision", "valid_from", "valid_until"), + [ + ("year", "2022-01-01T00:00", "2022-12-31T00:00"), + ("day", "2023-05-07T12:00", "2023-05-07T12:00"), + ("instant", "2023-05-07T12:00:00.000001", "2023-05-07T12:00:00.000001"), + ("open", "2019-01-01T00:00", None), + ("unknown", "2022-01-01T00:00", "2022-12-31T00:00"), + ], +) def test_query_space_canonical_bounds_wraps_the_public_twins( database_engine: Engine, + precision: str, + valid_from: str, + valid_until: str | None, ) -> None: """memory_v1.canonical_bounds is the public twins, published as text precision.""" - valid_from = _ts("2022-01-01T00:00") - valid_until = _ts("2022-12-31T00:00") expected = canonical_bounds( - valid_from=valid_from, valid_until=valid_until, precision="year" + valid_from=_ts(valid_from), + valid_until=_ts(valid_until) if valid_until else None, + precision=precision, ) with database_engine.connect() as connection: row = connection.execute( text( "SELECT canon_start, canon_end" " FROM memory_v1.canonical_bounds(" - " CAST(:f AS timestamptz), CAST(:u AS timestamptz), 'year')" - ), - {"f": "2022-01-01T00:00+00:00", "u": "2022-12-31T00:00+00:00"}, - ).one() - unknown = connection.execute( - text( - "SELECT canon_start, canon_end" - " FROM memory_v1.canonical_bounds(" - " CAST(:f AS timestamptz), CAST(:u AS timestamptz), 'unknown')" + " CAST(:f AS timestamptz), CAST(:u AS timestamptz), :p)" ), - {"f": "2022-01-01T00:00+00:00", "u": "2022-12-31T00:00+00:00"}, + { + "f": valid_from + "+00:00", + "u": (valid_until + "+00:00") if valid_until else None, + "p": precision, + }, ).one() assert row.canon_start == expected.start assert row.canon_end == expected.end - assert unknown.canon_start is None - assert unknown.canon_end is None def test_prompt_dates_render_the_utc_calendar_day() -> None: diff --git a/src/tests/spine/test_query_space_batch_a.py b/src/tests/spine/test_query_space_batch_a.py index 7787858dc..4ab8ff0d8 100644 --- a/src/tests/spine/test_query_space_batch_a.py +++ b/src/tests/spine/test_query_space_batch_a.py @@ -3166,8 +3166,13 @@ def test_no_claim_row_is_ever_accepted_as_a_current_fact(corpus: _Corpus) -> Non assert not claim_columns & {"evaluated_at", "support_state", "evidence_count"} -def test_claim_evidence_overlap_is_inclusive_at_both_endpoints(corpus: _Corpus) -> None: - """An instant claim has equal endpoints a half-open rule would erase.""" +def test_stored_claim_windows_keep_inclusive_instant_endpoints( + corpus: _Corpus, +) -> None: + """D41 storage is inclusive: an instant has equal endpoints on the raw columns. + + World-time overlap belongs on claims_canonical, not this predicate. + """ overlap = ( "SELECT coalesce(array_agg(claim_id ORDER BY claim_id), '{}'::uuid[])" " FROM memory_v1.claims_visible_history" diff --git a/src/tests/surfaces/test_open_query_batch_f.py b/src/tests/surfaces/test_open_query_batch_f.py index b4763486b..f092b2613 100644 --- a/src/tests/surfaces/test_open_query_batch_f.py +++ b/src/tests/surfaces/test_open_query_batch_f.py @@ -961,7 +961,7 @@ def test_core_prose_is_authority_for_live_graph_and_claims_verbatim() -> None: assert "memory_v1.graph_neighborhood" in graph_entry["example"] assert ( load_manifest()["surface_manifest_hash"] - == "0b9e8091dea477a4f6e4c3ff99c9031971395edb8797cd5576bba9dce773d2fa" + == "2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870" ) diff --git a/src/tests/surfaces/test_retrieval_batch_b.py b/src/tests/surfaces/test_retrieval_batch_b.py index fe82e99ea..33e23e693 100644 --- a/src/tests/surfaces/test_retrieval_batch_b.py +++ b/src/tests/surfaces/test_retrieval_batch_b.py @@ -18,6 +18,7 @@ from rememberstack.adapters import PostgresP1Index from rememberstack.adapters.testing import FakeModelProvider +from rememberstack.core.open_query_prose import CLAIMS_AS_OF_SQL from rememberstack.core.temporal import inclusive_request from rememberstack.model import DeploymentBootstrapInput from rememberstack.model import EmbeddingRequest @@ -552,35 +553,45 @@ def test_claims_as_of_intersects_open_windows_and_counts_unknown( def test_claims_canonical_unknown_count_and_overlap_match_engine_as_of( corpus: _Corpus, ) -> None: - """WP-T.0b: the open-SQL view matches the engine as-of set and counts unknown.""" + """WP-T.0b: the shipped example counts unknown by precision and overlaps canonically. + + Engine ``claims_as_of`` reads ``claims`` plus ``documents.deleted_at``; + ``claims_canonical`` additionally requires a surviving version. This corpus + is live-lineage, so the claim-id sets match; a tombstoned version would + diverge by design. + """ answer = corpus.query_engine().claims_as_of( - deployment_id=_DEPLOYMENT_ID, from_=_WINDOW_FROM, to=_WINDOW_TO, k=20 + deployment_id=_DEPLOYMENT_ID, from_=_WINDOW_FROM, to=_WINDOW_TO, k=50 + ) + example_sql = CLAIMS_AS_OF_SQL.replace("$1::timestamptz", ":from_instant").replace( + "$2::timestamptz", ":to_instant" ) - window = inclusive_request(from_=_WINDOW_FROM, to=_WINDOW_TO) + point = datetime(2024, 6, 15, 12, tzinfo=UTC) with corpus.engine.connect() as connection: - unknown = int( + rows = list( connection.execute( - text( - "SELECT count(*) FROM memory_v1.claims_canonical" - " WHERE claim_valid_precision = 'unknown'" - ) - ).scalar_one() + text(example_sql), + {"from_instant": _WINDOW_FROM, "to_instant": _WINDOW_TO}, + ) ) - overlap = { - row[0] - for row in connection.execute( - text( - "SELECT claim_id FROM memory_v1.claims_canonical" - " WHERE claim_valid_precision <> 'unknown'" - " AND canon_start < :to_exclusive" - " AND (canon_end IS NULL OR canon_end > :from_instant)" - ), - {"from_instant": window.start, "to_exclusive": window.end}, + point_rows = list( + connection.execute( + text(example_sql), + {"from_instant": point, "to_instant": point}, ) - } + ) + assert rows + unknown = int(rows[0].unknown_precision_excluded) assert unknown > 0 assert unknown == answer.excluded_unstamped - assert overlap == {claim.claim_id for claim in answer.evidence} + assert {row.claim_id for row in rows} == {claim.claim_id for claim in answer.evidence} + assert all(row.unknown_precision_excluded == unknown for row in rows) + window = inclusive_request(from_=point, to=point) + assert all( + row.canon_start is not None and row.canon_start < window.end + and (row.canon_end is None or row.canon_end > window.start) + for row in point_rows + ) def test_claims_as_of_excludes_tombstoned_lineages_before_candidate_bound( diff --git a/website/src/app/docs/retrieval/open-query/page.mdx b/website/src/app/docs/retrieval/open-query/page.mdx index 12dfd131a..e7182a3c4 100644 --- a/website/src/app/docs/retrieval/open-query/page.mdx +++ b/website/src/app/docs/retrieval/open-query/page.mdx @@ -55,11 +55,14 @@ WHERE claim_valid_from <= $1::timestamptz Claim validity is **source-asserted testimony**, not system belief. -World-time overlap on claims uses the **half-open canonical window** -(`claims_canonical.canon_start` / `canon_end`, or `canonical_bounds(...)`). -A stored day is the whole calendar day; an instant is a non-empty point; -unknown precision has no interval and is counted by precision, not by bounds. -The shipped `examples.claims_as_of` query is the honest pattern. +World-time overlap on claims uses the **half-open canonical window** on +`claims_canonical.canon_start` / `canon_end`. A stored day is the whole +calendar day; an instant is a non-empty point; unknown precision has no +interval and is counted by precision, not by bounds. The shipped +`examples.claims_as_of` query is the honest pattern. +`memory_v1.canonical_bounds` is a top-level `FROM` function for an explicit +window (`SELECT * FROM canonical_bounds($1, $2, $3)`), not a per-row +expression. **RIGHT — start from adjudicated current facts, join testimony:** From 59398f9e3f479fb5c4f97b71dd6ce1eb50758a54 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sun, 6 Sep 2026 23:13:26 +0200 Subject: [PATCH 3/6] fix(temporal): preserve sandbox permissions and migration order --- benchmarks/locomo/protocol.py | 2 +- .../versions/p9_02_0023_query_space_roles.py | 38 +- ...p9_27_0048_query_space_canonical_bounds.py | 66 +- .../spine/query_space/catalog.py | 2 +- .../spine/query_space/memory_v1_manifest.json | 1878 ++++++++++++++++- src/tests/benchmarks/test_locomo_runner.py | 2 +- src/tests/spine/test_canonical_bounds_sql.py | 9 +- src/tests/spine/test_query_space_batch_a.py | 4 +- src/tests/surfaces/test_retrieval_batch_b.py | 97 +- .../surfaces/test_saved_queries_batch_e.py | 7 +- 10 files changed, 1931 insertions(+), 174 deletions(-) diff --git a/benchmarks/locomo/protocol.py b/benchmarks/locomo/protocol.py index 7d5244c2a..05f372671 100644 --- a/benchmarks/locomo/protocol.py +++ b/benchmarks/locomo/protocol.py @@ -45,7 +45,7 @@ EXPECTED_DOCUMENT_BINDING_GENERATION: Final = "document-t0-v1" EXPECTED_SURFACE_MANIFEST_HASH: Final = ( - "2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870" + "7d8ee75d2a102485df10d96511f306e0f4e5c8d1d387b1cc9f271497480b84f9" ) EXPECTED_PIPELINE_STAGES: Final = ( "convert", diff --git a/src/rememberstack/spine/migrations/versions/p9_02_0023_query_space_roles.py b/src/rememberstack/spine/migrations/versions/p9_02_0023_query_space_roles.py index 054e075f8..d45cb0506 100644 --- a/src/rememberstack/spine/migrations/versions/p9_02_0023_query_space_roles.py +++ b/src/rememberstack/spine/migrations/versions/p9_02_0023_query_space_roles.py @@ -43,9 +43,35 @@ def query_role_name(database: str) -> str: return f"{_QUERY_ROLE_PREFIX}_{database}" -# The exhaustive public view list is read from the checked-in catalog at -# runtime so this migration can never drift from the schema contract. -from rememberstack.spine.query_space.catalog import VIEW_CONTRACTS_BY_NAME # noqa: E402 +# Freeze the views created by revision 0022. Reading the live application +# catalog here would make a fresh install grant views before later migrations +# create them, and would also break reverse-order downgrades. +_INITIAL_PUBLIC_VIEWS = ( + "changes_visible", + "chunks_live", + "claim_occurrences_live", + "claims_live", + "claims_visible_history", + "contradiction_members_current", + "document_crossrefs_live", + "document_versions_visible", + "documents_live", + "entities_current", + "entity_aliases_current", + "entity_document_mentions", + "evidence_lineage", + "fact_claim_evidence_live", + "facts_current", + "facts_visible_history", + "graph_edges_current", + "graph_edges_visible_history", + "identity_events_visible", + "mentions_live", + "page_evidence_visible", + "pages_live", + "sections_live", + "testimony_currency_events_visible", +) _PRIVATE_HELPERS = ( "v_memory_entity_survivor", @@ -127,11 +153,11 @@ def upgrade() -> None: " REVOKE EXECUTE ON FUNCTIONS FROM PUBLIC" ) - for view_name in sorted(VIEW_CONTRACTS_BY_NAME): + for view_name in _INITIAL_PUBLIC_VIEWS: op.execute(f"ALTER VIEW memory_v1.{view_name} OWNER TO {_VIEW_OWNER}") op.execute(f"GRANT USAGE ON SCHEMA memory_v1 TO {query_role}") - for view_name in sorted(VIEW_CONTRACTS_BY_NAME): + for view_name in _INITIAL_PUBLIC_VIEWS: op.execute(f"GRANT SELECT ON memory_v1.{view_name} TO {query_role}") # Durable role settings: the query role may not set superuser-only GUCs # per request, so the caps that require privilege are pinned here by the @@ -160,7 +186,7 @@ def downgrade() -> None: for helper in _PRIVATE_HELPERS: op.execute(f"ALTER VIEW public.{helper} OWNER TO CURRENT_USER") op.execute(f"ALTER ROLE {query_role} RESET ALL") - for view_name in sorted(VIEW_CONTRACTS_BY_NAME): + for view_name in _INITIAL_PUBLIC_VIEWS: op.execute(f"REVOKE ALL ON memory_v1.{view_name} FROM {query_role}") op.execute(f"ALTER VIEW memory_v1.{view_name} OWNER TO CURRENT_USER") op.execute(f"REVOKE USAGE ON SCHEMA memory_v1 FROM {query_role}") diff --git a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py index c1aaa5515..7a3a0b718 100644 --- a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py +++ b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py @@ -11,7 +11,11 @@ from alembic import op +from rememberstack.spine.migrations._helpers import _split_sql from rememberstack.spine.migrations._helpers import apply_view_ddl +from rememberstack.spine.migrations.versions.p9_01_0022_memory_v1_query_space import ( + MEMORY_V1_AUTHORED_DDL, +) revision: str = "p9_27_0048" down_revision: str | None = "p9_26_0047" @@ -31,7 +35,7 @@ IMMUTABLE PARALLEL SAFE SECURITY DEFINER -SET search_path = public, pg_catalog +SET search_path = pg_catalog, public, pg_temp ROWS 1 AS $$ SELECT @@ -100,16 +104,30 @@ h.source_kind, h.source_handle, h.is_current_testimony, - claim_canonical_start( - h.claim_valid_from, - h.claim_valid_precision::claim_valid_precision - ), - claim_canonical_end( - h.claim_valid_from, - h.claim_valid_until, - h.claim_valid_precision::claim_valid_precision - ) -FROM memory_v1.claims_visible_history AS h; + -- Inline the immutable twins' expressions: view ownership supplies table + -- privileges, not EXECUTE on private functions. Keeping expressions visible + -- also allows the planner to match ix_claims_canonical_window after inlining + -- the index's SQL functions. Database tests pin all three projections equal. + CASE + WHEN c.claim_valid_from IS NULL OR c.claim_valid_precision = 'unknown' THEN NULL + WHEN c.claim_valid_precision = 'day' THEN date_trunc('day', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + WHEN c.claim_valid_precision = 'month' THEN date_trunc('month', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + WHEN c.claim_valid_precision = 'quarter' THEN date_trunc('quarter', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + WHEN c.claim_valid_precision = 'year' THEN date_trunc('year', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + ELSE c.claim_valid_from + END, + CASE + WHEN c.claim_valid_from IS NULL OR c.claim_valid_precision = 'unknown' THEN NULL + WHEN c.claim_valid_precision = 'open' THEN NULL + WHEN c.claim_valid_precision = 'instant' THEN c.claim_valid_from + interval '1 microsecond' + WHEN c.claim_valid_precision = 'day' THEN (date_trunc('day', coalesce(c.claim_valid_until, c.claim_valid_from) AT TIME ZONE 'UTC') + interval '1 day') AT TIME ZONE 'UTC' + WHEN c.claim_valid_precision = 'month' THEN (date_trunc('month', coalesce(c.claim_valid_until, c.claim_valid_from) AT TIME ZONE 'UTC') + interval '1 month') AT TIME ZONE 'UTC' + WHEN c.claim_valid_precision = 'quarter' THEN (date_trunc('quarter', coalesce(c.claim_valid_until, c.claim_valid_from) AT TIME ZONE 'UTC') + interval '3 months') AT TIME ZONE 'UTC' + WHEN c.claim_valid_precision = 'year' THEN (date_trunc('year', coalesce(c.claim_valid_until, c.claim_valid_from) AT TIME ZONE 'UTC') + interval '1 year') AT TIME ZONE 'UTC' + END +FROM memory_v1.claims_visible_history AS h +JOIN public.claims AS c + ON c.deployment_id = h.deployment_id AND c.claim_id = h.claim_id; COMMENT ON VIEW memory_v1.claims_canonical IS 'One row per historically visible claim with surviving lineage, keyed by (deployment_id, claim_id), carrying the stored inclusive D41 window beside the half-open canonical bounds that every overlap predicate must use (D107 §5). canon_start is inclusive and canon_end exclusive; both are null when precision is unknown, and canon_end is also null for an open window. Overlap is a.start < b.end AND b.start < a.end with a null end as unbounded. This relation is IMMUTABLE SOURCE TESTIMONY: it never answers what currently holds. Claims of forgotten lineages and tombstoned versions are absent.'; """ @@ -134,6 +152,16 @@ def upgrade() -> None: " claim_canonical_end(timestamptz, timestamptz, claim_valid_precision)" f" TO {_VIEW_OWNER}" ) + # A bound predicate proves canon_start non-null, even through the public + # precision-as-text projection. The prior enum predicate could not be + # inferred by the planner through that projection. + op.execute("DROP INDEX ix_claims_canonical_window") + op.execute( + "CREATE INDEX ix_claims_canonical_window ON claims (" + "deployment_id, claim_canonical_start(claim_valid_from, claim_valid_precision)," + "claim_canonical_end(claim_valid_from, claim_valid_until, claim_valid_precision))" + " WHERE claim_canonical_start(claim_valid_from, claim_valid_precision) IS NOT NULL" + ) op.execute(CANONICAL_BOUNDS_FUNCTION_DDL) op.execute( "COMMENT ON FUNCTION memory_v1.canonical_bounds(timestamptz, timestamptz, text)" @@ -177,6 +205,22 @@ def upgrade() -> None: def downgrade() -> None: """Drop the published view and wrapper; public twins stay.""" op.execute("DROP VIEW IF EXISTS memory_v1.claims_canonical") + for block in MEMORY_V1_AUTHORED_DDL: + for statement in _split_sql(sql=block): + if statement.startswith( + ( + "COMMENT ON VIEW memory_v1.claims_visible_history IS", + "COMMENT ON VIEW memory_v1.claims_live IS", + ) + ): + op.execute(statement) + op.execute("DROP INDEX ix_claims_canonical_window") + op.execute( + "CREATE INDEX ix_claims_canonical_window ON claims (" + "deployment_id, claim_canonical_start(claim_valid_from, claim_valid_precision)," + "claim_canonical_end(claim_valid_from, claim_valid_until, claim_valid_precision))" + " WHERE claim_valid_precision <> 'unknown'" + ) op.execute( "DROP FUNCTION IF EXISTS" " memory_v1.canonical_bounds(timestamptz, timestamptz, text)" diff --git a/src/rememberstack/spine/query_space/catalog.py b/src/rememberstack/spine/query_space/catalog.py index e09e984d4..7d4b69ad0 100644 --- a/src/rememberstack/spine/query_space/catalog.py +++ b/src/rememberstack/spine/query_space/catalog.py @@ -517,7 +517,7 @@ class ViewContract(BaseModel): "canon_start": "timestamp with time zone", "canon_end": "timestamp with time zone", }, - indexes_used=("ix_claims_doc", "ix_claims_chunk", "ix_claims_valid_window"), + indexes_used=("ix_claims_doc", "ix_claims_chunk", "ix_claims_canonical_window"), positive_fixture="claims_canonical.superseded_testimony_present", negative_fixture="claims_canonical.forgotten_lineage_claim_absent", ), diff --git a/src/rememberstack/spine/query_space/memory_v1_manifest.json b/src/rememberstack/spine/query_space/memory_v1_manifest.json index d468e62cd..e0ec461b6 100644 --- a/src/rememberstack/spine/query_space/memory_v1_manifest.json +++ b/src/rememberstack/spine/query_space/memory_v1_manifest.json @@ -42,7 +42,7 @@ "indexes_used": [ "ix_claims_doc", "ix_claims_chunk", - "ix_claims_valid_window" + "ix_claims_canonical_window" ] }, "claims_live": { @@ -19072,15 +19072,126 @@ "all": false, "fromClause": [ { - "@": "RangeVar", - "alias": { - "@": "Alias", - "aliasname": "h" + "@": "JoinExpr", + "isNatural": false, + "jointype": { + "#": "JoinType", + "name": "JOIN_INNER" }, - "inh": true, - "relname": "claims_visible_history", - "relpersistence": "p", - "schemaname": "memory_v1" + "larg": { + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "h" + }, + "inh": true, + "relname": "claims_visible_history", + "relpersistence": "p", + "schemaname": "memory_v1" + }, + "quals": { + "@": "BoolExpr", + "args": [ + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "h" + }, + { + "@": "String", + "sval": "claim_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "boolop": { + "#": "BoolExprType", + "name": "AND_EXPR" + } + }, + "rarg": { + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "c" + }, + "inh": true, + "relname": "claims", + "relpersistence": "p", + "schemaname": "public" + }, + "rtindex": 0 } ], "groupDistinct": false, @@ -19496,138 +19607,1679 @@ { "@": "ResTarget", "val": { - "@": "FuncCall", - "agg_distinct": false, - "agg_star": false, - "agg_within_group": false, + "@": "CaseExpr", "args": [ { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "claim_valid_from" + "@": "CaseWhen", + "expr": { + "@": "BoolExpr", + "args": [ + { + "@": "NullTest", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + }, + "argisrow": false, + "nulltesttype": { + "#": "NullTestType", + "name": "IS_NULL" + } + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "unknown" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "boolop": { + "#": "BoolExprType", + "name": "OR_EXPR" } - ] + }, + "result": { + "@": "A_Const", + "isnull": true + } }, { - "@": "TypeCast", - "arg": { - "@": "ColumnRef", - "fields": [ + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ { "@": "String", - "sval": "h" + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "day" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "day" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" }, { "@": "String", - "sval": "claim_valid_precision" + "sval": "timezone" } ] - }, - "typeName": { - "@": "TypeName", - "names": [ + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ { "@": "String", - "sval": "claim_valid_precision" + "sval": "=" } ], - "pct_type": false, - "setof": false, - "typemod": -1 - } - } - ], - "func_variadic": false, - "funcformat": { - "#": "CoercionForm", - "name": "COERCE_EXPLICIT_CALL" - }, - "funcname": [ - { - "@": "String", - "sval": "claim_canonical_start" - } - ] - } - }, - { - "@": "ResTarget", - "val": { - "@": "FuncCall", - "agg_distinct": false, - "agg_star": false, - "agg_within_group": false, - "args": [ - { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "month" + } }, - { - "@": "String", - "sval": "claim_valid_from" - } - ] - }, - { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "month" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" }, - { - "@": "String", - "sval": "claim_valid_until" - } - ] - }, - { - "@": "TypeCast", - "arg": { - "@": "ColumnRef", - "fields": [ + "funcname": [ { "@": "String", - "sval": "h" + "sval": "pg_catalog" }, { "@": "String", - "sval": "claim_valid_precision" + "sval": "timezone" } ] - }, - "typeName": { - "@": "TypeName", - "names": [ + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ { "@": "String", - "sval": "claim_valid_precision" + "sval": "=" } ], - "pct_type": false, - "setof": false, - "typemod": -1 - } - } - ], - "func_variadic": false, - "funcformat": { - "#": "CoercionForm", - "name": "COERCE_EXPLICIT_CALL" - }, - "funcname": [ - { - "@": "String", - "sval": "claim_canonical_end" + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "quarter" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "quarter" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "year" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "year" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + } + ], + "defresult": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + } + }, + { + "@": "ResTarget", + "val": { + "@": "CaseExpr", + "args": [ + { + "@": "CaseWhen", + "expr": { + "@": "BoolExpr", + "args": [ + { + "@": "NullTest", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + }, + "argisrow": false, + "nulltesttype": { + "#": "NullTestType", + "name": "IS_NULL" + } + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "unknown" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "boolop": { + "#": "BoolExprType", + "name": "OR_EXPR" + } + }, + "result": { + "@": "A_Const", + "isnull": true + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "open" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "A_Const", + "isnull": true + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "instant" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "+" + } + ], + "rexpr": { + "@": "TypeCast", + "arg": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "1 microsecond" + } + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "interval" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "day" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "day" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "CoalesceExpr", + "args": [ + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_until" + } + ] + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "+" + } + ], + "rexpr": { + "@": "TypeCast", + "arg": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "1 day" + } + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "interval" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "month" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "month" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "CoalesceExpr", + "args": [ + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_until" + } + ] + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "+" + } + ], + "rexpr": { + "@": "TypeCast", + "arg": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "1 month" + } + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "interval" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "quarter" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "quarter" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "CoalesceExpr", + "args": [ + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_until" + } + ] + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "+" + } + ], + "rexpr": { + "@": "TypeCast", + "arg": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "3 months" + } + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "interval" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + }, + { + "@": "CaseWhen", + "expr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "year" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "result": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "year" + } + }, + { + "@": "FuncCall", + "agg_distinct": false, + "agg_star": false, + "agg_within_group": false, + "args": [ + { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "UTC" + } + }, + { + "@": "CoalesceExpr", + "args": [ + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_until" + } + ] + }, + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_from" + } + ] + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_EXPLICIT_CALL" + }, + "funcname": [ + { + "@": "String", + "sval": "date_trunc" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "+" + } + ], + "rexpr": { + "@": "TypeCast", + "arg": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "1 year" + } + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "interval" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "func_variadic": false, + "funcformat": { + "#": "CoercionForm", + "name": "COERCE_SQL_SYNTAX" + }, + "funcname": [ + { + "@": "String", + "sval": "pg_catalog" + }, + { + "@": "String", + "sval": "timezone" + } + ] + } } ] } @@ -38475,5 +40127,5 @@ } }, "manifest_contract": "memory_v1.manifest/2", - "surface_manifest_hash": "2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870" + "surface_manifest_hash": "7d8ee75d2a102485df10d96511f306e0f4e5c8d1d387b1cc9f271497480b84f9" } diff --git a/src/tests/benchmarks/test_locomo_runner.py b/src/tests/benchmarks/test_locomo_runner.py index d2275b045..35bfe8f10 100644 --- a/src/tests/benchmarks/test_locomo_runner.py +++ b/src/tests/benchmarks/test_locomo_runner.py @@ -1914,7 +1914,7 @@ def test_single_run_summary_json_is_unchanged( assert serialized == ( '{"protocol_name":"RS-LoCoMo-Full-v23","protocol_fingerprint":' - '"3fd2198d5c7c0075b0fe5c36022e38c3efd4727507e8252ad479b4af269fdafc",' + '"2199ce226f54a4168cc7221465ac7cc9ecc08701a3928f1032f39ec3b16e895a",' '"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,' diff --git a/src/tests/spine/test_canonical_bounds_sql.py b/src/tests/spine/test_canonical_bounds_sql.py index 136de7aff..68919bf41 100644 --- a/src/tests/spine/test_canonical_bounds_sql.py +++ b/src/tests/spine/test_canonical_bounds_sql.py @@ -151,10 +151,7 @@ def test_sql_twin_is_session_timezone_independent( ], ) def test_query_space_canonical_bounds_wraps_the_public_twins( - database_engine: Engine, - precision: str, - valid_from: str, - valid_until: str | None, + database_engine: Engine, precision: str, valid_from: str, valid_until: str | None ) -> None: """memory_v1.canonical_bounds is the public twins, published as text precision.""" expected = canonical_bounds( @@ -163,6 +160,10 @@ def test_query_space_canonical_bounds_wraps_the_public_twins( precision=precision, ) with database_engine.connect() as connection: + role = database_engine.dialect.identifier_preparer.quote( + f"rememberstack_query_{database_engine.url.database}" + ) + connection.exec_driver_sql(f"SET LOCAL ROLE {role}") row = connection.execute( text( "SELECT canon_start, canon_end" diff --git a/src/tests/spine/test_query_space_batch_a.py b/src/tests/spine/test_query_space_batch_a.py index 4ab8ff0d8..1e7cd0021 100644 --- a/src/tests/spine/test_query_space_batch_a.py +++ b/src/tests/spine/test_query_space_batch_a.py @@ -3166,9 +3166,7 @@ def test_no_claim_row_is_ever_accepted_as_a_current_fact(corpus: _Corpus) -> Non assert not claim_columns & {"evaluated_at", "support_state", "evidence_count"} -def test_stored_claim_windows_keep_inclusive_instant_endpoints( - corpus: _Corpus, -) -> None: +def test_stored_claim_windows_keep_inclusive_instant_endpoints(corpus: _Corpus) -> None: """D41 storage is inclusive: an instant has equal endpoints on the raw columns. World-time overlap belongs on claims_canonical, not this predicate. diff --git a/src/tests/surfaces/test_retrieval_batch_b.py b/src/tests/surfaces/test_retrieval_batch_b.py index 33e23e693..7cab63e1c 100644 --- a/src/tests/surfaces/test_retrieval_batch_b.py +++ b/src/tests/surfaces/test_retrieval_batch_b.py @@ -9,6 +9,7 @@ from alembic import command from alembic.config import Config +import psycopg from pydantic import ValidationError import pytest from sqlalchemy import create_engine @@ -18,8 +19,6 @@ from rememberstack.adapters import PostgresP1Index from rememberstack.adapters.testing import FakeModelProvider -from rememberstack.core.open_query_prose import CLAIMS_AS_OF_SQL -from rememberstack.core.temporal import inclusive_request from rememberstack.model import DeploymentBootstrapInput from rememberstack.model import EmbeddingRequest from rememberstack.model import NegativeKind @@ -29,6 +28,8 @@ from rememberstack.spine import DeploymentBootstrapper from rememberstack.spine.settings import load_database_settings from rememberstack.surfaces import QueryEngine +from rememberstack.surfaces.query_sandbox.examples import EXAMPLE_QUERIES +from rememberstack.surfaces.query_sandbox.executor import QuerySandboxExecutor _ROOT = Path(__file__).resolve().parents[3] _DEPLOYMENT_ID = UUID("59000000-0000-0000-0000-000000000001") @@ -563,35 +564,75 @@ def test_claims_canonical_unknown_count_and_overlap_match_engine_as_of( answer = corpus.query_engine().claims_as_of( deployment_id=_DEPLOYMENT_ID, from_=_WINDOW_FROM, to=_WINDOW_TO, k=50 ) - example_sql = CLAIMS_AS_OF_SQL.replace("$1::timestamptz", ":from_instant").replace( - "$2::timestamptz", ":to_instant" - ) - point = datetime(2024, 6, 15, 12, tzinfo=UTC) - with corpus.engine.connect() as connection: - rows = list( - connection.execute( - text(example_sql), - {"from_instant": _WINDOW_FROM, "to_instant": _WINDOW_TO}, - ) - ) - point_rows = list( - connection.execute( - text(example_sql), - {"from_instant": point, "to_instant": point}, - ) + role = f"rememberstack_query_{corpus.engine.url.database}" + quoted_role = corpus.engine.dialect.identifier_preparer.quote(role) + with corpus.engine.begin() as connection: + connection.exec_driver_sql( + f"ALTER ROLE {quoted_role} PASSWORD 'temporal-test-only'" ) - assert rows - unknown = int(rows[0].unknown_precision_excluded) - assert unknown > 0 - assert unknown == answer.excluded_unstamped - assert {row.claim_id for row in rows} == {claim.claim_id for claim in answer.evidence} - assert all(row.unknown_precision_excluded == unknown for row in rows) - window = inclusive_request(from_=point, to=point) + query_url = corpus.engine.url.set( + drivername="postgresql", username=role, password="temporal-test-only" + ).render_as_string(hide_password=False) + + def connect_query_role() -> psycopg.Connection: + """Authenticate as the real restricted login, including after DISCARD ALL.""" + return psycopg.connect(query_url) + + executor = QuerySandboxExecutor( + deployment_id=_DEPLOYMENT_ID, connect=connect_query_role + ) + result = executor.query_sql( + sql=EXAMPLE_QUERIES["claims_as_of"][1], + parameters=(_WINDOW_FROM, _WINDOW_TO), + max_rows=50, + ) + assert result.error_code is None, result.error_message + assert result.rows + columns = [column.name for column in result.columns] + rows = [dict(zip(columns, row, strict=True)) for row in result.rows] assert all( - row.canon_start is not None and row.canon_start < window.end - and (row.canon_end is None or row.canon_end > window.start) - for row in point_rows + row["unknown_precision_excluded"] == answer.excluded_unstamped for row in rows ) + assert answer.excluded_unstamped > 0 + assert {row["claim_id"] for row in rows} == { + claim.claim_id for claim in answer.evidence + } + point = datetime(2024, 6, 15, 12, tzinfo=UTC) + point_result = executor.query_sql( + sql=EXAMPLE_QUERIES["claims_as_of"][1], parameters=(point, point), max_rows=50 + ) + assert point_result.error_code is None, point_result.error_message + point_answer = corpus.query_engine().claims_as_of( + deployment_id=_DEPLOYMENT_ID, from_=point, to=point, k=50 + ) + assert point_result.rows, "the point-query proof must not pass vacuously" + assert {row[columns.index("claim_id")] for row in point_result.rows} == { + claim.claim_id for claim in point_answer.evidence + } + with connect_query_role() as connection: + for statement in ( + "SELECT * FROM public.claims", + "SELECT public.claim_canonical_start(NULL, 'unknown')", + "SELECT public.claim_canonical_end(NULL, NULL, 'unknown')", + ): + with pytest.raises(psycopg.errors.InsufficientPrivilege): + connection.execute(statement) + connection.rollback() + # Tiny fixtures favor sequential scans. Disabling them proves that a + # canonical bound can be an index condition, not only a residual filter. + connection.execute("SET LOCAL enable_seqscan = off") + plan = connection.execute( + "EXPLAIN (FORMAT JSON) SELECT claim_id FROM memory_v1.claims_canonical" + " WHERE deployment_id = %s AND canon_start < %s" + " AND (canon_end IS NULL OR canon_end > %s)", + (_DEPLOYMENT_ID, _WINDOW_TO, _WINDOW_FROM), + ).fetchone() + assert plan is not None + import json + + rendered = json.dumps(plan[0], default=str) + assert "ix_claims_canonical_window" in rendered, rendered + assert "Index Cond" in rendered, rendered def test_claims_as_of_excludes_tombstoned_lineages_before_candidate_bound( diff --git a/src/tests/surfaces/test_saved_queries_batch_e.py b/src/tests/surfaces/test_saved_queries_batch_e.py index 8371e6bb2..21d0b8f7c 100644 --- a/src/tests/surfaces/test_saved_queries_batch_e.py +++ b/src/tests/surfaces/test_saved_queries_batch_e.py @@ -1577,12 +1577,7 @@ def test_the_shipped_examples_are_the_eighteen_the_design_maps() -> None: _EXAMPLE_MAPPING_SIGNALS: dict[str, tuple[str, ...]] = { "claims_verbatim": ("semantic_claims", "claims_live", "JOIN"), "claims_about": ("mentions_live", "claim_occurrences_live", "claims_live"), - "claims_as_of": ( - "claims_canonical", - "canon_start <", - "canon_end > $1", - "unknown", - ), + "claims_as_of": ("claims_canonical", "canon_start <", "canon_end > $1", "unknown"), "claims_hybrid_rrf": ("semantic_claims", "lexical_claims"), "chunks_hybrid_rrf": ("semantic_chunks", "lexical_chunks"), "chunk_neighbors": ("chunks_live",), From 3d2c4075ac2796aca422932df2b53a1e1bfc198e Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sun, 6 Sep 2026 23:27:31 +0200 Subject: [PATCH 4/6] fix(temporal): make canonical range index usable by query login --- benchmarks/locomo/protocol.py | 2 +- ...p9_27_0048_query_space_canonical_bounds.py | 108 ++- .../spine/query_space/memory_v1_manifest.json | 820 ++++++++++++++++-- src/tests/benchmarks/test_locomo_runner.py | 2 +- src/tests/spine/test_query_space_batch_a.py | 69 ++ src/tests/surfaces/test_open_query_batch_f.py | 2 +- src/tests/surfaces/test_retrieval_batch_b.py | 3 +- 7 files changed, 865 insertions(+), 141 deletions(-) diff --git a/benchmarks/locomo/protocol.py b/benchmarks/locomo/protocol.py index 05f372671..56de2788a 100644 --- a/benchmarks/locomo/protocol.py +++ b/benchmarks/locomo/protocol.py @@ -45,7 +45,7 @@ EXPECTED_DOCUMENT_BINDING_GENERATION: Final = "document-t0-v1" EXPECTED_SURFACE_MANIFEST_HASH: Final = ( - "7d8ee75d2a102485df10d96511f306e0f4e5c8d1d387b1cc9f271497480b84f9" + "c7a7c0e5bfc9126ba1d7ed7bedcf2489a8537393801b4288742fdbd29079539e" ) EXPECTED_PIPELINE_STAGES: Final = ( "convert", diff --git a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py index 7a3a0b718..35d9f9283 100644 --- a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py +++ b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py @@ -48,7 +48,18 @@ $$; """ -CLAIMS_CANONICAL_VIEW_DDL = r""" +_CANONICAL_START_SQL = """ +CASE + WHEN claim_valid_from IS NULL OR claim_valid_precision = 'unknown' THEN NULL + WHEN claim_valid_precision = 'day' THEN date_trunc('day', claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + WHEN claim_valid_precision = 'month' THEN date_trunc('month', claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + WHEN claim_valid_precision = 'quarter' THEN date_trunc('quarter', claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + WHEN claim_valid_precision = 'year' THEN date_trunc('year', claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' + ELSE claim_valid_from + END +""".strip() + +CLAIMS_CANONICAL_VIEW_DDL = rf""" CREATE VIEW memory_v1.claims_canonical ( deployment_id, -- The deployment that owns the claim. claim_id, -- Stable identity of this immutable claim. @@ -79,43 +90,36 @@ canon_end -- Exclusive end of the half-open canonical window; null when the window is open or unknown. ) AS SELECT - h.deployment_id, - h.claim_id, - h.doc_id, - h.version_id, - h.representation_id, - h.chunk_id, - h.claim_text, - h.source_span, - h.char_start, - h.char_end, - h.added_context, - h.temporal_class, - h.is_attributed, - h.audit_status, - h.kept_flagged, - h.extractor_version, - h.asserted_at, - h.claim_valid_from, - h.claim_valid_until, - h.claim_valid_precision, - h.claim_valid_kind, - h.ingested_at, - h.source_kind, - h.source_handle, - h.is_current_testimony, + c.deployment_id, + c.claim_id, + c.doc_id, + ch.version_id, + ch.representation_id, + c.chunk_id, + c.claim_text, + c.source_span, + c.char_start, + c.char_end, + c.added_context, + c.temporal_class::text, + c.is_attributed, + c.audit_status::text, + c.kept_flagged, + c.extractor_version, + c.asserted_at, + c.claim_valid_from, + c.claim_valid_until, + c.claim_valid_precision::text, + c.claim_valid_kind::text, + c.ingested_at, + dl.source_kind, + dl.source_kind || ':' || coalesce(dl.source_ref, dl.doc_id::text), + c.is_current_testimony, -- Inline the immutable twins' expressions: view ownership supplies table -- privileges, not EXECUTE on private functions. Keeping expressions visible -- also allows the planner to match ix_claims_canonical_window after inlining -- the index's SQL functions. Database tests pin all three projections equal. - CASE - WHEN c.claim_valid_from IS NULL OR c.claim_valid_precision = 'unknown' THEN NULL - WHEN c.claim_valid_precision = 'day' THEN date_trunc('day', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' - WHEN c.claim_valid_precision = 'month' THEN date_trunc('month', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' - WHEN c.claim_valid_precision = 'quarter' THEN date_trunc('quarter', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' - WHEN c.claim_valid_precision = 'year' THEN date_trunc('year', c.claim_valid_from AT TIME ZONE 'UTC') AT TIME ZONE 'UTC' - ELSE c.claim_valid_from - END, + {_CANONICAL_START_SQL.replace("claim_valid_", "c.claim_valid_")}, CASE WHEN c.claim_valid_from IS NULL OR c.claim_valid_precision = 'unknown' THEN NULL WHEN c.claim_valid_precision = 'open' THEN NULL @@ -125,9 +129,25 @@ WHEN c.claim_valid_precision = 'quarter' THEN (date_trunc('quarter', coalesce(c.claim_valid_until, c.claim_valid_from) AT TIME ZONE 'UTC') + interval '3 months') AT TIME ZONE 'UTC' WHEN c.claim_valid_precision = 'year' THEN (date_trunc('year', coalesce(c.claim_valid_until, c.claim_valid_from) AT TIME ZONE 'UTC') + interval '1 year') AT TIME ZONE 'UTC' END -FROM memory_v1.claims_visible_history AS h -JOIN public.claims AS c - ON c.deployment_id = h.deployment_id AND c.claim_id = h.claim_id; +-- Identical coordinate/visibility joins to claims_visible_history (0025). +-- Project directly from c so filtering does not require a second claims scan. +FROM public.claims AS c +JOIN public.chunks AS ch + ON ch.deployment_id = c.deployment_id + AND ch.chunk_id = c.chunk_id + AND ch.doc_id = c.doc_id +JOIN memory_v1.document_versions_visible AS vv + ON vv.deployment_id = ch.deployment_id + AND vv.version_id = ch.version_id + AND vv.doc_id = ch.doc_id +JOIN public.document_representations AS representation + ON representation.deployment_id = ch.deployment_id + AND representation.version_id = ch.version_id + AND representation.representation_id = ch.representation_id + AND representation.status = 'ready' +JOIN memory_v1.documents_live AS dl + ON dl.deployment_id = c.deployment_id + AND dl.doc_id = c.doc_id; COMMENT ON VIEW memory_v1.claims_canonical IS 'One row per historically visible claim with surviving lineage, keyed by (deployment_id, claim_id), carrying the stored inclusive D41 window beside the half-open canonical bounds that every overlap predicate must use (D107 §5). canon_start is inclusive and canon_end exclusive; both are null when precision is unknown, and canon_end is also null for an open window. Overlap is a.start < b.end AND b.start < a.end with a null end as unbounded. This relation is IMMUTABLE SOURCE TESTIMONY: it never answers what currently holds. Claims of forgotten lineages and tombstoned versions are absent.'; """ @@ -152,15 +172,15 @@ def upgrade() -> None: " claim_canonical_end(timestamptz, timestamptz, claim_valid_precision)" f" TO {_VIEW_OWNER}" ) - # A bound predicate proves canon_start non-null, even through the public - # precision-as-text projection. The prior enum predicate could not be - # inferred by the planner through that projection. + # Spell the start expression in the index: a query login without EXECUTE + # cannot inline a private SQL function even during index-path matching. + # The application can still inline its twin to this exact expression. op.execute("DROP INDEX ix_claims_canonical_window") op.execute( - "CREATE INDEX ix_claims_canonical_window ON claims (" - "deployment_id, claim_canonical_start(claim_valid_from, claim_valid_precision)," - "claim_canonical_end(claim_valid_from, claim_valid_until, claim_valid_precision))" - " WHERE claim_canonical_start(claim_valid_from, claim_valid_precision) IS NOT NULL" + f"CREATE INDEX ix_claims_canonical_window ON claims (deployment_id," + f" ({_CANONICAL_START_SQL})," + " claim_canonical_end(claim_valid_from, claim_valid_until, claim_valid_precision))" + f" WHERE ({_CANONICAL_START_SQL}) IS NOT NULL" ) op.execute(CANONICAL_BOUNDS_FUNCTION_DDL) op.execute( diff --git a/src/rememberstack/spine/query_space/memory_v1_manifest.json b/src/rememberstack/spine/query_space/memory_v1_manifest.json index e0ec461b6..3de21bc86 100644 --- a/src/rememberstack/spine/query_space/memory_v1_manifest.json +++ b/src/rememberstack/spine/query_space/memory_v1_manifest.json @@ -19079,15 +19079,507 @@ "name": "JOIN_INNER" }, "larg": { - "@": "RangeVar", - "alias": { - "@": "Alias", - "aliasname": "h" + "@": "JoinExpr", + "isNatural": false, + "jointype": { + "#": "JoinType", + "name": "JOIN_INNER" + }, + "larg": { + "@": "JoinExpr", + "isNatural": false, + "jointype": { + "#": "JoinType", + "name": "JOIN_INNER" + }, + "larg": { + "@": "JoinExpr", + "isNatural": false, + "jointype": { + "#": "JoinType", + "name": "JOIN_INNER" + }, + "larg": { + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "c" + }, + "inh": true, + "relname": "claims", + "relpersistence": "p", + "schemaname": "public" + }, + "quals": { + "@": "BoolExpr", + "args": [ + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "chunk_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "chunk_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "doc_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "doc_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "boolop": { + "#": "BoolExprType", + "name": "AND_EXPR" + } + }, + "rarg": { + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "ch" + }, + "inh": true, + "relname": "chunks", + "relpersistence": "p", + "schemaname": "public" + }, + "rtindex": 0 + }, + "quals": { + "@": "BoolExpr", + "args": [ + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "vv" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "vv" + }, + { + "@": "String", + "sval": "version_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "version_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "vv" + }, + { + "@": "String", + "sval": "doc_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "doc_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "boolop": { + "#": "BoolExprType", + "name": "AND_EXPR" + } + }, + "rarg": { + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "vv" + }, + "inh": true, + "relname": "document_versions_visible", + "relpersistence": "p", + "schemaname": "memory_v1" + }, + "rtindex": 0 }, - "inh": true, - "relname": "claims_visible_history", - "relpersistence": "p", - "schemaname": "memory_v1" + "quals": { + "@": "BoolExpr", + "args": [ + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "representation" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "deployment_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "representation" + }, + { + "@": "String", + "sval": "version_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "version_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "representation" + }, + { + "@": "String", + "sval": "representation_id" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "ch" + }, + { + "@": "String", + "sval": "representation_id" + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "representation" + }, + { + "@": "String", + "sval": "status" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "=" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": "ready" + } + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + } + ], + "boolop": { + "#": "BoolExprType", + "name": "AND_EXPR" + } + }, + "rarg": { + "@": "RangeVar", + "alias": { + "@": "Alias", + "aliasname": "representation" + }, + "inh": true, + "relname": "document_representations", + "relpersistence": "p", + "schemaname": "public" + }, + "rtindex": 0 }, "quals": { "@": "BoolExpr", @@ -19103,7 +19595,7 @@ "fields": [ { "@": "String", - "sval": "c" + "sval": "dl" }, { "@": "String", @@ -19122,7 +19614,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19144,11 +19636,11 @@ "fields": [ { "@": "String", - "sval": "c" + "sval": "dl" }, { "@": "String", - "sval": "claim_id" + "sval": "doc_id" } ] }, @@ -19163,11 +19655,11 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", - "sval": "claim_id" + "sval": "doc_id" } ] }, @@ -19184,12 +19676,12 @@ "@": "RangeVar", "alias": { "@": "Alias", - "aliasname": "c" + "aliasname": "dl" }, "inh": true, - "relname": "claims", + "relname": "documents_live", "relpersistence": "p", - "schemaname": "public" + "schemaname": "memory_v1" }, "rtindex": 0 } @@ -19211,7 +19703,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19227,7 +19719,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19243,7 +19735,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19259,7 +19751,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "ch" }, { "@": "String", @@ -19275,7 +19767,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "ch" }, { "@": "String", @@ -19291,7 +19783,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19307,7 +19799,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19323,7 +19815,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19339,7 +19831,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19355,7 +19847,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19371,7 +19863,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19380,20 +19872,35 @@ ] } }, - { - "@": "ResTarget", - "val": { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "temporal_class" - } - ] + { + "@": "ResTarget", + "val": { + "@": "TypeCast", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "temporal_class" + } + ] + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "text" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } } }, { @@ -19403,7 +19910,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19415,17 +19922,32 @@ { "@": "ResTarget", "val": { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "audit_status" - } - ] + "@": "TypeCast", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "audit_status" + } + ] + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "text" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } } }, { @@ -19435,7 +19957,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19451,7 +19973,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19467,7 +19989,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19483,7 +20005,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19499,7 +20021,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19511,33 +20033,63 @@ { "@": "ResTarget", "val": { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "claim_valid_precision" - } - ] + "@": "TypeCast", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_precision" + } + ] + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "text" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } } }, { "@": "ResTarget", "val": { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" - }, - { - "@": "String", - "sval": "claim_valid_kind" - } - ] + "@": "TypeCast", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "c" + }, + { + "@": "String", + "sval": "claim_valid_kind" + } + ] + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "text" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } } }, { @@ -19547,7 +20099,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -19563,7 +20115,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "dl" }, { "@": "String", @@ -19575,17 +20127,101 @@ { "@": "ResTarget", "val": { - "@": "ColumnRef", - "fields": [ - { - "@": "String", - "sval": "h" + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "A_Expr", + "kind": { + "#": "A_Expr_Kind", + "name": "AEXPR_OP" + }, + "lexpr": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "dl" + }, + { + "@": "String", + "sval": "source_kind" + } + ] + }, + "name": [ + { + "@": "String", + "sval": "||" + } + ], + "rexpr": { + "@": "A_Const", + "isnull": false, + "val": { + "@": "String", + "sval": ":" + } }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 + }, + "name": [ { "@": "String", - "sval": "source_handle" + "sval": "||" } - ] + ], + "rexpr": { + "@": "CoalesceExpr", + "args": [ + { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "dl" + }, + { + "@": "String", + "sval": "source_ref" + } + ] + }, + { + "@": "TypeCast", + "arg": { + "@": "ColumnRef", + "fields": [ + { + "@": "String", + "sval": "dl" + }, + { + "@": "String", + "sval": "doc_id" + } + ] + }, + "typeName": { + "@": "TypeName", + "names": [ + { + "@": "String", + "sval": "text" + } + ], + "pct_type": false, + "setof": false, + "typemod": -1 + } + } + ] + }, + "rexpr_list_end": 0, + "rexpr_list_start": 0 } }, { @@ -19595,7 +20231,7 @@ "fields": [ { "@": "String", - "sval": "h" + "sval": "c" }, { "@": "String", @@ -40127,5 +40763,5 @@ } }, "manifest_contract": "memory_v1.manifest/2", - "surface_manifest_hash": "7d8ee75d2a102485df10d96511f306e0f4e5c8d1d387b1cc9f271497480b84f9" + "surface_manifest_hash": "c7a7c0e5bfc9126ba1d7ed7bedcf2489a8537393801b4288742fdbd29079539e" } diff --git a/src/tests/benchmarks/test_locomo_runner.py b/src/tests/benchmarks/test_locomo_runner.py index 35bfe8f10..40f865c2e 100644 --- a/src/tests/benchmarks/test_locomo_runner.py +++ b/src/tests/benchmarks/test_locomo_runner.py @@ -1914,7 +1914,7 @@ def test_single_run_summary_json_is_unchanged( assert serialized == ( '{"protocol_name":"RS-LoCoMo-Full-v23","protocol_fingerprint":' - '"2199ce226f54a4168cc7221465ac7cc9ecc08701a3928f1032f39ec3b16e895a",' + '"73794e3cfb45cd26a75884133418419d30a5765a4342591f72382fedc5532cc4",' '"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,' diff --git a/src/tests/spine/test_query_space_batch_a.py b/src/tests/spine/test_query_space_batch_a.py index 1e7cd0021..3a835455d 100644 --- a/src/tests/spine/test_query_space_batch_a.py +++ b/src/tests/spine/test_query_space_batch_a.py @@ -3191,6 +3191,75 @@ def test_stored_claim_windows_keep_inclusive_instant_endpoints(corpus: _Corpus) assert corpus.claim["instant"] not in after_instant +@pytest.mark.parametrize( + ("precision", "start", "end"), + [ + ("day", "2023-05-07T12:00:00+00:00", "2023-05-07T12:00:00+00:00"), + ("month", "2023-05-07T12:00:00+00:00", "2023-05-08T12:00:00+00:00"), + ("quarter", "2023-05-07T12:00:00+00:00", "2023-05-08T12:00:00+00:00"), + ("year", "2022-01-01T00:00:00+00:00", "2022-12-31T00:00:00+00:00"), + ( + "instant", + "2023-05-07T12:00:00.000001+00:00", + "2023-05-07T12:00:00.000001+00:00", + ), + ("open", "2019-01-01T16:30:00+00:00", None), + ("unknown", None, None), + ], +) +def test_canonical_view_matches_private_twins_under_query_role( + corpus: _Corpus, precision: str, start: str | None, end: str | None +) -> None: + """All published projections preserve source membership and UTC clock arithmetic.""" + with corpus.engine.connect() as connection: + connection.execute( + text( + "UPDATE claims SET claim_valid_from=CAST(:start AS timestamptz)," + " claim_valid_until=CAST(:end AS timestamptz)," + " claim_valid_precision=CAST(:precision AS claim_valid_precision)," + " claim_valid_kind=CASE WHEN :precision='unknown' THEN NULL" + " ELSE 'event_time'::claim_valid_kind END WHERE claim_id=:claim" + ), + { + "start": start, + "end": end, + "precision": precision, + "claim": corpus.claim["a"], + }, + ) + expected = connection.execute( + text( + "SELECT claim_canonical_start(claim_valid_from,claim_valid_precision)," + " claim_canonical_end(claim_valid_from,claim_valid_until,claim_valid_precision)" + " FROM claims WHERE claim_id=:claim" + ), + {"claim": corpus.claim["a"]}, + ).one() + role = corpus.engine.dialect.identifier_preparer.quote( + f"rememberstack_query_{corpus.engine.url.database}" + ) + connection.exec_driver_sql(f"SET LOCAL ROLE {role}") + connection.exec_driver_sql("SET LOCAL TIME ZONE 'Pacific/Auckland'") + actual = connection.execute( + text( + "SELECT canon_start,canon_end FROM memory_v1.claims_canonical WHERE claim_id=:claim" + ), + {"claim": corpus.claim["a"]}, + ).one() + assert tuple(actual) == tuple(expected) + differing = connection.execute( + text( + "SELECT count(*) FROM (" + " (SELECT claim_id FROM memory_v1.claims_canonical EXCEPT SELECT claim_id FROM memory_v1.claims_visible_history)" + " UNION ALL" + " (SELECT claim_id FROM memory_v1.claims_visible_history EXCEPT SELECT claim_id FROM memory_v1.claims_canonical)" + ") AS difference" + ) + ).scalar_one() + assert differing == 0 + connection.rollback() + + # ── §9.4 D54 lifecycle ─────────────────────────────────────────────────── _COUNTS = ( diff --git a/src/tests/surfaces/test_open_query_batch_f.py b/src/tests/surfaces/test_open_query_batch_f.py index f092b2613..f19faae74 100644 --- a/src/tests/surfaces/test_open_query_batch_f.py +++ b/src/tests/surfaces/test_open_query_batch_f.py @@ -961,7 +961,7 @@ def test_core_prose_is_authority_for_live_graph_and_claims_verbatim() -> None: assert "memory_v1.graph_neighborhood" in graph_entry["example"] assert ( load_manifest()["surface_manifest_hash"] - == "2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870" + == "c7a7c0e5bfc9126ba1d7ed7bedcf2489a8537393801b4288742fdbd29079539e" ) diff --git a/src/tests/surfaces/test_retrieval_batch_b.py b/src/tests/surfaces/test_retrieval_batch_b.py index 7cab63e1c..0537da3e4 100644 --- a/src/tests/surfaces/test_retrieval_batch_b.py +++ b/src/tests/surfaces/test_retrieval_batch_b.py @@ -3,6 +3,7 @@ from collections.abc import Iterator from datetime import datetime from datetime import UTC +import json from pathlib import Path from uuid import UUID from uuid import uuid4 @@ -628,8 +629,6 @@ def connect_query_role() -> psycopg.Connection: (_DEPLOYMENT_ID, _WINDOW_TO, _WINDOW_FROM), ).fetchone() assert plan is not None - import json - rendered = json.dumps(plan[0], default=str) assert "ix_claims_canonical_window" in rendered, rendered assert "Index Cond" in rendered, rendered From 470f992134129b35194cf025efe2140e74f3d56d Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sun, 6 Sep 2026 23:38:55 +0200 Subject: [PATCH 5/6] test(temporal): verify canonical range index with selective corpus --- src/tests/surfaces/test_retrieval_batch_b.py | 69 ++++++++++++++++---- 1 file changed, 56 insertions(+), 13 deletions(-) diff --git a/src/tests/surfaces/test_retrieval_batch_b.py b/src/tests/surfaces/test_retrieval_batch_b.py index 0537da3e4..4ef41390e 100644 --- a/src/tests/surfaces/test_retrieval_batch_b.py +++ b/src/tests/surfaces/test_retrieval_batch_b.py @@ -619,19 +619,62 @@ def connect_query_role() -> psycopg.Connection: with pytest.raises(psycopg.errors.InsufficientPrivilege): connection.execute(statement) connection.rollback() - # Tiny fixtures favor sequential scans. Disabling them proves that a - # canonical bound can be an index condition, not only a residual filter. - connection.execute("SET LOCAL enable_seqscan = off") - plan = connection.execute( - "EXPLAIN (FORMAT JSON) SELECT claim_id FROM memory_v1.claims_canonical" - " WHERE deployment_id = %s AND canon_start < %s" - " AND (canon_end IS NULL OR canon_end > %s)", - (_DEPLOYMENT_ID, _WINDOW_TO, _WINDOW_FROM), - ).fetchone() - assert plan is not None - rendered = json.dumps(plan[0], default=str) - assert "ix_claims_canonical_window" in rendered, rendered - assert "Index Cond" in rendered, rendered + + +def test_claims_canonical_uses_range_index_for_selective_window( + corpus: _Corpus, +) -> None: + """The restricted role can use canonical bounds as index conditions at scale.""" + role = f"rememberstack_query_{corpus.engine.url.database}" + quoted_role = corpus.engine.dialect.identifier_preparer.quote(role) + # Keep the shared corpus unchanged. Many dated claims in one live chunk make + # its chunk index unselective, while the requested window matches four rows. + # Planner settings remain at their defaults: this proves a useful access path. + with corpus.engine.connect() as connection: + transaction = connection.begin() + try: + connection.execute( + text( + "INSERT INTO claims (claim_id, deployment_id, doc_id, chunk_id," + " section_id, claim_text, source_span, char_start, char_end," + " anchor_ok, window_membership_ok, claim_valid_from," + " claim_valid_until, claim_valid_precision, claim_valid_kind," + " extractor_version, ingested_at)" + " SELECT gen_random_uuid(), deployment_id, doc_id, chunk_id," + " section_id, claim_text, source_span, char_start, char_end," + " anchor_ok, window_membership_ok," + " TIMESTAMPTZ '2030-01-01 00:00:00+00' + n * INTERVAL '1 day'," + " TIMESTAMPTZ '2030-01-01 00:00:00+00' + n * INTERVAL '1 day'," + " 'day', 'event_time', extractor_version, ingested_at" + " FROM claims CROSS JOIN generate_series(1, 10000) AS n" + " WHERE claim_id = :claim" + ), + {"claim": corpus.claim_ids[0]}, + ) + connection.exec_driver_sql("ANALYZE claims") + connection.exec_driver_sql(f"SET LOCAL ROLE {quoted_role}") + plan = connection.execute( + text( + "EXPLAIN (FORMAT JSON) SELECT claim_id" + " FROM memory_v1.claims_canonical" + " WHERE deployment_id = :deployment AND canon_start < :to" + " AND (canon_end IS NULL OR canon_end > :from_)" + ), + {"deployment": _DEPLOYMENT_ID, "to": _WINDOW_TO, "from_": _WINDOW_FROM}, + ).scalar_one() + nodes = [plan[0]["Plan"]] + canonical_conditions: list[str] = [] + while nodes: + node = nodes.pop() + nodes.extend(node.get("Plans", [])) + if node.get("Index Name") == "ix_claims_canonical_window": + canonical_conditions.append(node.get("Index Cond", "")) + assert any( + "CASE" in condition and " < " in condition + for condition in canonical_conditions + ), json.dumps(plan, default=str) + finally: + transaction.rollback() def test_claims_as_of_excludes_tombstoned_lineages_before_candidate_bound( From ddd2ea8febe3db20be682510cd34b97530de3f99 Mon Sep 17 00:00:00 2001 From: Jiri Puc Date: Sun, 6 Sep 2026 23:55:53 +0200 Subject: [PATCH 6/6] fix(temporal): explicitly revoke public execution of canonical twins --- .../p9_27_0048_query_space_canonical_bounds.py | 16 ++++++++++++++++ src/tests/surfaces/test_retrieval_batch_b.py | 14 ++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py index 35d9f9283..ae06d2d79 100644 --- a/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py +++ b/src/rememberstack/spine/migrations/versions/p9_27_0048_query_space_canonical_bounds.py @@ -162,6 +162,20 @@ def upgrade() -> None: """Publish the wrapper function and the claims_canonical view.""" + # Per-schema default ACLs cannot subtract PostgreSQL's global PUBLIC + # EXECUTE default. Explicitly protect these private twins even on stores + # where 0047 ran after 0023's per-schema default-privilege statement. + # Schema USAGE remains a separate boundary, not a substitute for this ACL. + op.execute( + "REVOKE EXECUTE ON FUNCTION" + " public.claim_canonical_start(timestamptz, public.claim_valid_precision)" + " FROM PUBLIC" + ) + op.execute( + "REVOKE EXECUTE ON FUNCTION" + " public.claim_canonical_end(timestamptz, timestamptz, public.claim_valid_precision)" + " FROM PUBLIC" + ) op.execute( "GRANT EXECUTE ON FUNCTION" " claim_canonical_start(timestamptz, claim_valid_precision)" @@ -224,6 +238,8 @@ def upgrade() -> None: def downgrade() -> None: """Drop the published view and wrapper; public twins stay.""" + # Keep the explicit private-function PUBLIC revocations: downgrading the + # published contract must not restore the earlier unintended execute ACL. op.execute("DROP VIEW IF EXISTS memory_v1.claims_canonical") for block in MEMORY_V1_AUTHORED_DDL: for statement in _split_sql(sql=block): diff --git a/src/tests/surfaces/test_retrieval_batch_b.py b/src/tests/surfaces/test_retrieval_batch_b.py index 4ef41390e..bbcde82fc 100644 --- a/src/tests/surfaces/test_retrieval_batch_b.py +++ b/src/tests/surfaces/test_retrieval_batch_b.py @@ -571,6 +571,20 @@ def test_claims_canonical_unknown_count_and_overlap_match_engine_as_of( connection.exec_driver_sql( f"ALTER ROLE {quoted_role} PASSWORD 'temporal-test-only'" ) + # A missing schema USAGE grant can hide a leaked function EXECUTE ACL. + # Check both permission layers independently before authenticating. + assert not connection.execute( + text("SELECT has_schema_privilege(:role, 'public', 'USAGE')"), + {"role": role}, + ).scalar_one() + for signature in ( + "public.claim_canonical_start(timestamptz, public.claim_valid_precision)", + "public.claim_canonical_end(timestamptz, timestamptz, public.claim_valid_precision)", + ): + assert not connection.execute( + text("SELECT has_function_privilege(:role, :signature, 'EXECUTE')"), + {"role": role, "signature": signature}, + ).scalar_one() query_url = corpus.engine.url.set( drivername="postgresql", username=role, password="temporal-test-only" ).render_as_string(hide_password=False)