Skip to content

feat(temporal): expose canonical bounds in the query space (D107 WP-T.0b) - #375

Merged
fazpu merged 6 commits into
mainfrom
feat/wp-t0b-query-space-canonical-bounds
Sep 6, 2026
Merged

fazpu merged 6 commits into
mainfrom
feat/wp-t0b-query-space-canonical-bounds

Conversation

@fazpu

@fazpu fazpu commented Sep 4, 2026 •

Copy link
Copy Markdown
Member

Problem and result

Open SQL could not use the canonical half-open claim windows already shipped by the engine-internal T.0a path. The saved examples.claims_as_of still compared inclusive raw fields and its unknown-precision count could never be nonzero.

This PR publishes memory_v1.canonical_bounds for explicit top-level FROM calls and claims_canonical for claim filtering, fixes the saved example, and rolls the query-space manifest and both LoCoMo variants to Full-v23. Claim storage and the Python QueryEngine path are unchanged.

Implementation and important decisions

  • Migration 0048 publishes a SECURITY DEFINER arithmetic wrapper with a pinned trusted search path. The query login receives no private-schema access or EXECUTE on the public twins.
  • The view spells canonical expressions directly and uses the same coordinate/visibility joins as claims_visible_history. PostgreSQL view ownership supplies table permissions, not private function EXECUTE. Direct joins avoid a second claims scan.
  • The canonical index spells the first CASE expression and its nonnull predicate directly. The query role cannot inline a private function even while matching an index; the application can still inline its twin to this expression. The existing end expression remains. Downgrade restores the old index and view comments.
  • Migration 0023 freezes its historical 24-view grant set, so fresh upgrades and reverse downgrades do not reference a view introduced by 0048.
  • Catalog fixtures, deletion-matrix cells, grammar, saved SQL, docs, manifest, and protocol fingerprints move together.

Sources inspected

D107 plan/designs/temporal_clocks_design.md §5; plan/plans/temporal_clocks.md T.0b; query-space role/grammar contracts; migrations 0022/0023/0025/0047; PostgreSQL CREATE VIEW permission rules and actual PostgreSQL behavior. Round-one Codex and Antigravity findings and round-two Antigravity findings were triaged.

Validation and review

Local lint, formatting and type checking pass. The latest targeted local run passed 136 tests, with 19 database-dependent tests skipped. An isolated 10,000-row PostgreSQL 15 probe confirmed query-role use of the direct-expression canonical index; PostgreSQL 19 CI remains the integration authority.

Database tests execute the exact shipped example through QuerySandboxExecutor authenticated as the restricted query login; compare unknown counts and point/window claim sets with the library; assert private accesses fail; check the canonical index path; and compare all seven precisions and row membership under a non-UTC session. Fresh migration, downgrade/reupgrade and catalog/deletion gates run in CI.

Antigravity rounds two through four are resolved; final review APPROVED at ddd2ea8. In addition to the manifest/index fixes, the private canonical twins now explicitly revoke PUBLIC EXECUTE (per-schema default ACLs cannot remove PostgreSQL global defaults). Tests inspect schema USAGE and function EXECUTE independently. Downgrade retains that restriction. The final reviewer independently checked role/wrapper/index/downgrade/re-upgrade behavior in an isolated PostgreSQL15 fixture. All full integration jobs must pass before merge, even if the fast PR gate completes earlier.

Limitations and follow-up

T.0b publishes source testimony, not adjudicated truth. Engine and query-space lineage/version filters have an existing documented difference for tombstoned versions; the clean live-corpus equality test does not claim universal equality. T.4 and the four design spikes before T.1 remain separate work under #364.

Contributor agreement

@fazpu

fazpu commented Sep 4, 2026

Copy link
Copy Markdown
Member Author

Codex review (gpt-5.6-sol, xhigh) — round 1

Verdict: request changes.

Triage

# Sev Finding Decision
C1 major claims_visible_history / claims_live comments still teach inclusive overlap fix — replace comments in p9_27_0048 pointing at claims_canonical; regenerate manifest
C2 major Acceptance tests never execute the shipped examples.claims_as_of under the query role fix — run the exact example SQL; keep live-corpus equality as directional, not a tombstone A/B
C3 major SECURITY DEFINER SRF in the view cannot use ix_claims_canonical_window; indexes_used is false fix — project the public twins in the view SELECT (indexable); keep the SRF for FROM canonical_bounds($1,$2,$3) with ROWS 1; correct indexes_used
C4 major run_shard.sh still defaults full-v22 fix
C5 minor Downgrade does not revoke view-owner EXECUTE on the public twins fix

EOF
python3 -c "
from pathlib import Path
head = Path('/tmp/pr375-codex-comment.md').read_text()
body = Path.home().joinpath('.grok/long-running-background-tasks/wp-t0b-codex-review-final.md').read_text()
Path('/tmp/pr375-codex-comment.md').write_text(head + body)
print(len(head+body))
"

Findings

  1. Severity: major
    file:line: memory_v1_manifest.json:20615
    Evidence: The published claims_visible_history comment still says overlap is “INCLUSIVE at both endpoints” and that half-open semantics would erase instant claims. claims_live repeats the same instruction at memory_v1_manifest.json:19850. The authored source comes from p9_01_0022_memory_v1_query_space.py:455 and p9_01_0022_memory_v1_query_space.py:511. The existing test at test_query_space_batch_a.py:3169 also describes this as the operative claim-overlap rule.
    Why: D41 storage remains inclusive, but D107 §5 changes all claim-window comparisons to half-open canonical bounds. The discovery manifest now gives callers mutually contradictory instructions and can lead them directly back to the forbidden raw-bound predicate.
    Concrete fix: In p9_27_0048, replace both existing view comments with wording that distinguishes inclusive raw storage from canonical half-open comparison and points to claims_canonical. Feed those latest comments into source-definition generation, regenerate the manifest/hash, and rename the old test so it clearly asserts raw storage only while adding canonical overlap assertions.

  2. Severity: major
    file:line: test_retrieval_batch_b.py:552
    Evidence: The purported acceptance test uses privileged corpus.engine.connect(), runs hand-written SQL with an already-converted to_exclusive, and counts unknown rows in a separate statement. It never executes EXAMPLE_QUERIES["claims_as_of"], never observes its unknown_precision_excluded column, and never goes through QuerySandboxExecutor or the query role. The example tests at test_saved_queries_batch_e.py:1609 and test_saved_queries_batch_e.py:1628 provide parsing/substring checks only. The generic execution corpus uses the Batch-A seeder (test_saved_queries_batch_e.py:1889), whose persistent claims contain no unknown precision.
    Why: Neither binding acceptance criterion is asserted through the shipped path. The test would continue to pass if the example lost to + 1µs, returned a zero unknown count, or failed specifically under query-role permissions. It also lacks executed point, adjacent-day, and open-window assertions over the new surface.
    Concrete fix: Seed both a visible unstamped claim and matching stamped claims in the open-query corpus; execute the exact shipped example through the sandbox/query role with the inclusive request parameters; assert every returned row reports a non-zero unknown count and compare its claim IDs with library claims_as_of. Add point (t,t), adjacent-day, open-end, and unknown-exclusion cases.

  3. Severity: major
    file:line: p9_27_0048_query_space_canonical_bounds.py:33
    Evidence: canonical_bounds is both SECURITY DEFINER and has a SET search_path clause, and the view invokes it as a lateral table function at p9_27_0048_query_space_canonical_bounds.py:104. Nevertheless, the catalog declares that this view uses ix_claims_canonical_window at catalog.py:520. That index is defined on the direct public-twin expressions at p9_26_0047_canonical_bounds.py:66.
    Why: PostgreSQL cannot inline this table function: the current optimizer rejects SRF inlining for either SECURITY DEFINER or a non-null function configuration. Consequently, outer predicates on b.canon_start/b.canon_end cannot become the public-twin expressions required by that index. The catalog’s indexes_used declaration is therefore false, and the shipped query is exposed to per-row function evaluation/full scans. The function also omits ROWS 1, so PostgreSQL’s default SRF estimate is 1,000 rows. See the PostgreSQL 18 optimizer source and CREATE FUNCTION documentation.
    Concrete fix: Preserve the secure SRF for direct open-SQL calls, but give the view an indexable expression path—for example, memory-v1 security-definer scalar wrappers projected directly by the view plus a matching expression index, while retaining the public-twin index for the engine. Declare ROWS 1 on the SRF, correct indexes_used, and add a query-role EXPLAIN assertion proving the canonical index path.

  4. Severity: major
    file:line: run_shard.sh:28
    Evidence: The sharded runner still defaults LOCOMO_PROTOCOL to full-v22, then passes it to prepare at run_shard.sh:200. The model accepts only full-v23 at model.py:31, while the sharding README advertises full-v23.
    Why: A normal sharded run with no override fails during argument parsing/preparation. This makes the Full-v23 operational roll incomplete.
    Concrete fix: Change the shell default to full-v23, update the v22 comment at line 53, and extend the shard-runner static test to assert the protocol default.

  5. Severity: minor
    file:line: p9_27_0048_query_space_canonical_bounds.py:166
    Evidence: Upgrade grants rememberstack_view_owner EXECUTE on both public twins at lines 117–125, but downgrade only drops the view and wrapper.
    Why: Downgrade leaves a privilege expansion that did not exist before T.0b, so it does not restore the prior ACL state even though the public twins correctly remain installed.
    Concrete fix: After dropping the dependent view and wrapper, revoke those two exact EXECUTE grants from rememberstack_view_owner.

Verified

  • Clock arithmetic is correct: the example uses canonical half-open overlap, converts inclusive to with + 1 microsecond, excludes unknown precision, and counts unknown by precision alone at open_query_prose.py:139. The wrapper delegates to the UTC-safe T.0a twins rather than repeating calendar arithmetic (p9_27_0048_query_space_canonical_bounds.py:35, p9_26_0047_canonical_bounds.py:23).
  • Query-role isolation is structurally correct: the function is owned by rememberstack_view_owner, has a fixed trusted search path, grants the query role only memory-v1 EXECUTE/SELECT, and grants public-twin EXECUTE only to the view owner (p9_27_0048_query_space_canonical_bounds.py:115). The query role still has no public-schema usage (p9_02_0023_query_space_roles.py:76). The wrapper contains no table access or dynamic SQL, so I found no private-table read attack.
  • claims_canonical has the same membership as claims_visible_history: it reads that view directly and its wrapper always produces one result row, including the all-null unknown case (p9_27_0048_query_space_canonical_bounds.py:104). The Batch-B equality comparison is honest for that clean live-lineage corpus, but deliberately does not prove equality for tombstoned-version states where the engine and view have different source filters.
  • Types, nullable canonical columns, grain, joins, and fixtures are declared correctly at catalog.py:443. Deletion-matrix applicability was added for lineage, version, claim, and k_target, without leaking claim identifiers on representation/fact-provenance targets (deletion_matrix.py:214).
  • Source definitions include the latest new view DDL at source_definitions.py:151. Static regeneration matched the checked-in manifest and hash 0b9e…d2fa (memory_v1_manifest.json:38459).
  • canonical_bounds is SQL-native, allowed in top-level FROM, separately categorized as temporal, and does not consume or bypass nomination/body-fetch quotas (grammar.py:51, bridge.py:58). Static validate_sql accepted the shipped example and a top-level FROM canonical_bounds(...) call.
  • Full-v23’s code-level roll is otherwise honest: only protocol identity, adapter identity, and surface hash changed; ingest versions remain at protocol.py:58, and the answer prompt and library claims_as_of SQL are unchanged. The v22 wording in dataset.py:141 is a truthful frozen-dataset provenance label, not a claim that the active protocol is v22.
  • Migration head/chain and CI gate correctly use p9_27_0048 (test_migrations.py:128, ci.yml:374). Downgrade drops the view before the wrapper and leaves the public twins installed.
  • Open-query and project-status documentation describe shipped T.0b behavior rather than aspiration (open-query/page.mdx:56, project-status/page.mdx:304).

No PostgreSQL-backed tests or PostgreSQL process were run. I made no file changes; static validation, manifest regeneration comparison, and git diff --check passed.

Merge verdict

Request changes. The core clock calculation, timezone handling, view membership, and privilege boundary are correct, but the shipped catalog still publishes obsolete inclusive-overlap guidance, the binding acceptance criteria are not exercised through the actual example/query-role path, the declared canonical index cannot serve predicates through the opaque security-definer SRF, and the sharded benchmark defaults to a protocol key that no longer exists.

@fazpu

fazpu commented Sep 4, 2026

Copy link
Copy Markdown
Member Author

Antigravity review — round 1

Verdict: request changes.

Triage

# Sev Finding Decision
A1 blocker run_shard.sh defaults full-v22 fix (same as Codex C4)
A2 major canonical_bounds on FUNCTION_ALLOWLIST is dead; SELECT/LATERAL rejected fix — remove from FUNCTION_ALLOWLIST; docs must say it is a top-level SRF, overlap goes through claims_canonical columns
A3 major Acceptance test is a false match and never runs the shipped example fix (same as Codex C2); tombstoned-lineage divergence is real and will be documented in the test, not papered over
A4 minor Missing clock cases on the wrapper/view fix — parametrize wrapper across precisions; add point-query overlap on the view
A5 minor Docs imply canonical_bounds(...) can be used as a row expression fix (same as A2)
A6 nit dataset.py error strings still say Full-v22 wontfix as a protocol lie — Codex is right that this is the frozen dataset pin label; leave it

EOF
python3 -c "
from pathlib import Path
head = Path('/tmp/pr375-agy-comment.md').read_text()
body = Path.home().joinpath('.grok/long-running-background-tasks/wp-t0b-agy-review-final.md').read_text()
Path('/tmp/pr375-agy-comment.md').write_text(head + body)
print(len(head+body))
"

Findings

1. Sharding default protocol key breaks on LoCoMo run

  • Severity: blocker
  • File & Line: benchmarks/locomo/sharding/run_shard.sh:28 (and comment at line 53)
  • Evidence:
    protocol=${LOCOMO_PROTOCOL:-full-v22}
    # RS-LoCoMo-Full-v22's non-secret ingest identity. Override ambient self-host
  • Why it is wrong relative to D107 §5 / WP-T.0b / query-space contract:
    PR feat(temporal): expose canonical bounds in the query space (D107 WP-T.0b) #375 rolls the LoCoMo protocol from full-v22 to full-v23. In protocol.py, PROTOCOL_REGISTRY now only contains {"full-v23": _FULL_V23}, and ProtocolKey is Literal["full-v23"]. While benchmarks/locomo/sharding/README.md:181 was updated to document LOCOMO_PROTOCOL defaulting to full-v23, run_shard.sh:28 was missed and still defaults to full-v22. When invoked without an explicit LOCOMO_PROTOCOL environment variable, run_shard.sh passes --protocol full-v22 to benchmarks.locomo prepare, which immediately aborts with an unrecognized protocol error.
  • Concrete fix:
    Update line 28 of run_shard.sh to:
    protocol=${LOCOMO_PROTOCOL:-full-v23}
    and update line 53 to reference RS-LoCoMo-Full-v23.

2. canonical_bounds is dead code in FUNCTION_ALLOWLIST and cannot be called in SELECT or LATERAL

  • Severity: major
  • File & Line: src/rememberstack/surfaces/query_sandbox/grammar.py:119 (in interaction with lines 386–395, 945–988, 1406–1414)
  • Evidence:
    In grammar.py:119, "canonical_bounds" is added to FUNCTION_ALLOWLIST:
    FUNCTION_ALLOWLIST: Final = frozenset(
        (
            ...
            "make_interval",
            "canonical_bounds",
            "array_length",
    While in line 53 it is added to PUBLIC_SRF_NAMES:
    PUBLIC_SRF_NAMES: Final = frozenset(
        {
            "canonical_bounds",
    In _AllowlistVisitor.visit_FuncCall (lines 386–395):
            if name in PUBLIC_SRF_NAMES:
                self.srf_calls.append(node)
                self.functions.add(name)
                return None
            if name not in FUNCTION_ALLOWLIST:
                raise _reject(...)
    And in validate_sql (lines 1409–1414):
        for call in gate.srf_calls:
            if id(call) not in accepted:
                raise _reject(
                    QueryErrorCode.FUNCTION_PLACEMENT_NOT_ALLOWED,
                    "public functions are callable only as top-level FROM items",
                )
  • Why it is wrong relative to D107 §5 / WP-T.0b / query-space contract:
    The PR added "canonical_bounds" to FUNCTION_ALLOWLIST (the scalar expression allowlist), but because visit_FuncCall checks name in PUBLIC_SRF_NAMES first, any call to canonical_bounds is categorized as an SRF call. _SrfPlacementVisitor then insists that all SRF calls be top-level RangeFunctions with literal or parameter arguments (_assert_srf_arguments_bindable).
    As a result:
    1. SELECT canonical_bounds(...) fails validate_sql with function_placement_not_allowed: public functions are callable only as top-level FROM items.
    2. CROSS JOIN LATERAL canonical_bounds(...) fails validate_sql with function_placement_not_allowed.
    3. FROM canonical_bounds(c.claim_valid_from, ...) fails validate_sql with public function arguments must be literals or bound parameters.
      The entry in FUNCTION_ALLOWLIST is completely ineffective dead code. canonical_bounds can only be called as a standalone top-level SRF with literal/parameter arguments (e.g. SELECT * FROM canonical_bounds($1, $2, $3)).
  • Concrete fix:
    Remove "canonical_bounds" from FUNCTION_ALLOWLIST in grammar.py:119. If canonical_bounds was only intended as an SRF table function over bound arguments, remove the dead allowlist entry and align the documentation (see Finding 5). If it was intended to be callable in SELECT or LATERAL over row values, _AllowlistVisitor and _SrfPlacementVisitor must be updated to permit scalar expression or lateral placement for this function.

3. View membership acceptance test is a false match and omits the shipped example query

  • Severity: major
  • File & Line: src/tests/surfaces/test_retrieval_batch_b.py:552-583
  • Evidence:
    def test_claims_canonical_unknown_count_and_overlap_match_engine_as_of(
        corpus: _Corpus,
    ) -> None:
        ...
        assert unknown > 0
        assert unknown == answer.excluded_unstamped
        assert overlap == {claim.claim_id for claim in answer.evidence}
  • Why it is wrong relative to D107 §5 / WP-T.0b / query-space contract:
    1. False match on excluded_unstamped: In query_engine.py:3610, _UNSTAMPED_CLAIM_COUNT counts directly from claims:
      SELECT count(*) FROM claims WHERE deployment_id = :deployment_id AND claim_valid_precision = 'unknown'
      This query does not join documents or document_versions. In contrast, claims_canonical derives from claims_visible_history, which INNER JOINs documents_live and document_versions_visible. If any document lineage is deleted or version tombstoned, claims_as_of counts its unstamped claims, while claims_canonical excludes them. Testing unknown == answer.excluded_unstamped exclusively on a 100% live fixture corpus conceals this structural divergence.
    2. Shipped example query is never executed: Acceptance criterion 1 ("The example's unknown count is non-zero on a corpus with unstamped claims") is tested by running an ad-hoc custom query (SELECT count(*) FROM memory_v1.claims_canonical WHERE ...). The actual shipped query string EXAMPLE_QUERIES["claims_as_of"][1] (CLAIMS_AS_OF_SQL) with its correlated subquery, ordering, limit, and microsecond interval arithmetic ($2::timestamptz + '1 microsecond'::interval) is never executed against PostgreSQL in any test.
  • Concrete fix:
    In test_retrieval_batch_b.py, execute EXAMPLE_QUERIES["claims_as_of"][1] with parameters $1 = _WINDOW_FROM and $2 = _WINDOW_TO and assert that the returned unknown_precision_excluded column is non-zero and that the returned claim IDs match answer.evidence. Add a test with a tombstoned version/lineage to assert that claims_canonical correctly excludes tombstoned testimony.

4. Missing clock assertions on claims_canonical and canonical_bounds

  • Severity: minor
  • File & Line: src/tests/spine/test_canonical_bounds_sql.py:140-170 and src/tests/surfaces/test_retrieval_batch_b.py:552-583
  • Evidence:
    test_query_space_canonical_bounds_wraps_the_public_twins only tests precision 'year' and 'unknown':
    row = connection.execute(text("... memory_v1.canonical_bounds(..., 'year')"))
    unknown = connection.execute(text("... memory_v1.canonical_bounds(..., 'unknown')"))
    test_claims_canonical_unknown_count_and_overlap_match_engine_as_of only evaluates a single 30-day window [2024-06-01, 2024-06-30].
  • Why it is wrong relative to D107 §5 / WP-T.0b / query-space contract:
    WP-T.0b mandates verifying the clock behavior of the published query space:
    • Point query: claims_canonical evaluated with ($1, $1) (yielding [$1, $1 + 1µs)) matching instant and enclosing windows.
    • Adjacent windows: two abutting query windows (e.g. June 1 vs June 2) not matching each other's claims.
    • Open window: claims with claim_valid_precision = 'open' (canon_end IS NULL) matching queries past their start.
    • Wrapper coverage: day, month, quarter, instant, and open are untested through memory_v1.canonical_bounds.
  • Concrete fix:
    Parametrize test_query_space_canonical_bounds_wraps_the_public_twins across all precision enum values, and add point query (t, t) and open window overlap queries over claims_canonical.

5. Documentation and prose claim canonical_bounds(...) can be used for claim overlap

  • Severity: minor
  • File & Line: website/src/app/docs/retrieval/open-query/page.mdx:57 and src/rememberstack/core/open_query_prose.py:174
  • Evidence:
    page.mdx:57:
    World-time overlap on claims uses the **half-open canonical window**
    (`claims_canonical.canon_start` / `canon_end`, or `canonical_bounds(...)`).
    open_query_prose.py:174:
    "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."
  • Why it is wrong relative to D107 §5 / WP-T.0b / query-space contract:
    As proven in Finding 2, users cannot invoke canonical_bounds(...) in SELECT, WHERE, or LATERAL join on claim rows within open SQL. Promising (or memory_v1.canonical_bounds) leads open-query users to write queries that get rejected by the query sandbox parser.
  • Concrete fix:
    Update the documentation and prose to state that claim overlap queries should select against claims_canonical.canon_start and canon_end, noting that memory_v1.canonical_bounds is a table-valued function for converting explicit window bounds.

6. Stale dataset validation error message strings in dataset.py

  • Severity: nit
  • File & Line: benchmarks/locomo/dataset.py:143, 146
  • Evidence:
    if commit != DATASET_COMMIT:
        raise DatasetValidationError(
            "manifest dataset commit is not RS-LoCoMo-Full-v22"
        )
    if hash_ != DATASET_SHA256:
        raise DatasetValidationError("manifest dataset hash is not RS-LoCoMo-Full-v22")
  • Why it is wrong relative to D107 §5 / WP-T.0b / query-space contract:
    benchmarks/locomo/runner.py:1180, 1190 was updated to "RS-LoCoMo-Full-v23", but dataset.py was left mentioning "RS-LoCoMo-Full-v22". The dataset commit and SHA-256 are unchanged (frozen dataset across protocols), so this is a cosmetic mismatch in error text rather than a semantic dataset pin issue.
  • Concrete fix:
    Update "RS-LoCoMo-Full-v22" to "RS-LoCoMo-Full-v23" in dataset.py:143, 146.

Verified

  • Clock correctness:
    • The half-open overlap condition in CLAIMS_AS_OF_SQL (c.canon_start < ($2::timestamptz + '1 microsecond'::interval) AND (c.canon_end IS NULL OR c.canon_end > $1::timestamptz)) correctly implements a.start < b.end AND b.start < a.end with NULL end as $+∞$.
    • Converting $2 to exclusive by adding '1 microsecond'::interval ensures (t, t) executes as a non-empty point query.
    • Unknown precision claims are excluded by WHERE c.claim_valid_precision <> 'unknown' and counted by precision alone in the subquery.
  • Query-role isolation:
    • Migration p9_27_0048 grants EXECUTE on the public twins only to rememberstack_view_owner.
    • The query role rememberstack_query_<db> receives GRANT EXECUTE ON FUNCTION memory_v1.canonical_bounds and GRANT SELECT ON memory_v1.claims_canonical only; it gains no USAGE or EXECUTE on public.
    • memory_v1.canonical_bounds is SECURITY DEFINER owned by rememberstack_view_owner, with explicit SET search_path = public, pg_catalog. It performs no dynamic SQL and accesses no tables.
  • Session timezone:
    • memory_v1.canonical_bounds delegates directly to the T.0a public twins, which perform UTC calendar truncation via AT TIME ZONE 'UTC'. It introduces no session-calendar arithmetic.
  • View membership:
    • memory_v1.claims_canonical joins memory_v1.claims_visible_history with a 1:1 CROSS JOIN LATERAL against canonical_bounds, preserving identical row membership (excluding tombstoned versions and lineages).
  • Catalog contract:
    • catalog.py:443-527 declares claims_canonical with correct column types, nullable canon_start/canon_end, grain, fixtures, and indexes including ix_claims_canonical_window.
    • Authored comments in p9_27_0048 start with uppercase and end with periods, and are materialized onto columns via apply_view_ddl.
    • source_definitions.py:164 appends CLAIMS_CANONICAL_VIEW_DDL, and the surface manifest hash (0b9e8091...) recomputes deterministically from source without a database.
    • Deletion matrix in deletion_matrix.py:218, 269, 314, 367 and d48_deletion_matrix.json includes claims_canonical on all 4 targets matching claims_visible_history (lineage, version, claim, k_target).
  • Protocol roll honesty:
    • Ingest pipeline component versions, answer agent prompt, and library claims_as_of SQL are completely untouched. The protocol roll to Full-v23 is solely due to the surface manifest hash pin.
  • Migration hygiene:
    • Revision p9_27_0048 chains linearly from p9_26_0047, verified in test_migrations.py:129, 668.
    • CI upgrade gate is updated in .github/workflows/ci.yml:374.
    • Downgrade drops claims_canonical first, then canonical_bounds, leaving the public twins intact.

Merge Verdict

Request changes. While the core SQL implementation of memory_v1.canonical_bounds, memory_v1.claims_canonical, the query-space catalog, migration hygiene, and protocol hashing adhere closely to D107 §5 / WP-T.0b, the PR cannot be merged in its current state: run_shard.sh retains a broken default to full-v22 which fails on execution; placing canonical_bounds into FUNCTION_ALLOWLIST in grammar.py:119 creates misleading dead code while docs imply callers can invoke it on claim columns; and the acceptance test suite neither executes the shipped claims_as_of query nor tests view membership across non-live lineage states or boundary clock conditions. Fixing the sharding script default, cleaning up grammar allowlist/doc discrepancies, and executing the actual shipped query in test proofs will make this ready for merge.

@fazpu

fazpu commented Sep 4, 2026

Copy link
Copy Markdown
Member Author

Round-1 findings applied on 03f9ba5f (see triage on the Codex and Antigravity comments).

Fixed: sharded full-v23 default; claims_canonical now projects the public twins instead of a lateral SECURITY DEFINER SRF (ROWS 1 kept on the SRF for FROM canonical_bounds($1,$2,$3)); indexes_used no longer claims ix_claims_canonical_window; view comments on claims_visible_history / claims_live point at canonical overlap; dead FUNCTION_ALLOWLIST entry removed; shipped examples.claims_as_of executed in the batch-B proof; wrapper parametrized; downgrade revokes view-owner EXECUTE; surface hash / fingerprint regenerated.

Left: query-role EXPLAIN proving an index path (C3 remainder — the catalog is now honest that the view uses the parent claim indexes); tombstoned-lineage A/B (A3 — documented as a designed divergence, not equality). Dataset error strings still name the frozen v22 dataset pin (A6 wontfix).

@fazpu
fazpu force-pushed the feat/wp-t0b-query-space-canonical-bounds branch from 03f9ba5 to 67ada2c Compare September 6, 2026 20:47
@fazpu

fazpu commented Sep 6, 2026

Copy link
Copy Markdown
Member Author

PR 375 Round-Two Review: Canonical Bounds in Query Space (WP-T.0b)

Reviewed against: origin/main (commits 27811257, 67ada2c6, and 9b378306)
Relevant Docs & Designs Consulted: CLAUDE.md, plan/designs/temporal_clocks_design.md §5, plan/plans/temporal_clocks.md T.0b
Verdict: CHANGES REQUESTED (1 blocking defect in test suite)


Executive Summary & Findings Overview

ID Location Severity Category Summary
D-1 src/tests/surfaces/test_open_query_batch_f.py:964 High Correctness / Test Failure Stale hardcoded manifest hash 2fff3177... causes test failure against new hash 7d8ee75d...
D-2 src/tests/surfaces/test_retrieval_batch_b.py:632 Low Code Style Scoped import json inside test body instead of top-level imports

Root-Cause Analysis: Function Permissions in Owner-Rights Views

The Round-One Defect

In round 1 (commit 67ada2c6), memory_v1.claims_canonical was defined as:

SELECT h.*,
  claim_canonical_start(h.claim_valid_from, h.claim_valid_precision::claim_valid_precision) AS canon_start,
  claim_canonical_end(h.claim_valid_from, h.claim_valid_until, h.claim_valid_precision::claim_valid_precision) AS canon_end
FROM memory_v1.claims_visible_history AS h;

The previous review assumed that because the view is owned by rememberstack_view_owner, callers querying the view would inherit the owner's privileges for function execution.

Why that fails in PostgreSQL:
In PostgreSQL, owner-rights views operate with the view owner's privileges only for underlying table access. Any function called within the view's query expression is checked against the calling role's privileges (unless the function itself is declared SECURITY DEFINER). Because migration p9_02_0023_query_space_roles.py revoked EXECUTE ON ALL FUNCTIONS IN SCHEMA public FROM PUBLIC and does not grant EXECUTE on the private twins to rememberstack_query_*, any query run as the query role against claims_canonical failed with:

psycopg.errors.InsufficientPrivilege: permission denied for function claim_canonical_start

The round 1 test in test_retrieval_batch_b.py had masked this bug because it executed queries over corpus.engine.connect() as the database superuser rather than authenticating as the restricted rememberstack_query_* role.

The Round-Two Resolution in Commit 9b378306

The uncommitted fixes (now commit 9b378306) solved this by:

  1. Inlining the canonical expressions directly in claims_canonical:
    The view now joins public.claims AS c and embeds the raw CASE expressions of claim_canonical_start and claim_canonical_end. Because no user-defined function is called, the query role requires no EXECUTE privileges.
  2. Preserving private function ACLs:
    claim_canonical_start and claim_canonical_end remain inaccessible to rememberstack_query_*. Direct calls to public.claims or the twin functions fail with InsufficientPrivilege.
  3. Query-Role acceptance testing:
    test_retrieval_batch_b.py:567-583 now provisions an authentic TCP/socket connection as rememberstack_query_{database}, executes EXAMPLE_QUERIES["claims_as_of"] via QuerySandboxExecutor, and explicitly verifies that direct calls to public.claims, public.claim_canonical_start, and public.claim_canonical_end raise psycopg.errors.InsufficientPrivilege.

Detailed Audit Against Review Requirements

1. Frozen Migration-0023 Grants

  • Status: PASS
  • Verification: In p9_02_0023_query_space_roles.py:49-74, _INITIAL_PUBLIC_VIEWS freezes the 24 views authored up to revision 0022. Replacing the dynamic import from catalog import VIEW_CONTRACTS_BY_NAME prevents fresh migrations from attempting to alter or grant claims_canonical (which is not created until 0048) and preserves reverse-order downgrade behavior.

2. Migration 0048 Inline Canonical View Projections & Partial Index Eligibility

  • Status: PASS
  • Analysis:
    • claims_canonical inlines the exact UTC-truncating CASE expressions matching core/temporal.py:canonical_bounds and the 0047 SQL twins.
    • In p9_27_0048_query_space_canonical_bounds.py:158-164, ix_claims_canonical_window was altered to:
      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;
    • When open SQL queries canon_start < ($2::timestamptz + '1 microsecond'::interval), PostgreSQL's planner inlines claim_canonical_start into the index expression and proves via strict operator deduction (<) that canon_start IS NOT NULL. Thus, the partial index predicate is satisfied and the index is used directly as an Index Cond.

3. Private Function ACL Preservation

  • Status: PASS
  • Verification: public.claim_canonical_start and claim_canonical_end have EXECUTE granted only to rememberstack_view_owner (so memory_v1.canonical_bounds, a SECURITY DEFINER function, can evaluate them). The query role is denied direct execution, which is pinned by tests in test_retrieval_batch_b.py:612-620.

4. Query-Role Execution of Saved Examples & Meaningful Acceptance Tests

  • Status: PASS
  • Verification:
    • Shipped example query CLAIMS_AS_OF_SQL uses claims_canonical and counts unknown precision via WHERE u.claim_valid_precision = 'unknown' (fixing audit 4.21).
    • The acceptance test in test_retrieval_batch_b.py:564-637 tests window overlap, non-zero excluded unstamped claims, point queries (parameters=(point, point)), ACL denials, and verifies that ix_claims_canonical_window appears under Index Cond in EXPLAIN (FORMAT JSON).

5. Downgrade Metadata

  • Status: PASS
  • Verification: In p9_27_0048_query_space_canonical_bounds.py:205-238, downgrade() extracts and executes the original view comments for claims_visible_history and claims_live from MEMORY_V1_AUTHORED_DDL, drops claims_canonical and canonical_bounds, restores the 0047 partial index definition (WHERE claim_valid_precision <> 'unknown'), and revokes EXECUTE on the twin functions from rememberstack_view_owner.

6. Manifest & LoCoMo Protocol Consistency

  • Status: FAIL (see Defect D-1)
  • Analysis:
    • Query space manifest memory_v1_manifest.json:40130 and benchmarks/locomo/protocol.py:46 were rolled to Full-v23 with hash 7d8ee75d2a102485df10d96511f306e0f4e5c8d1d387b1cc9f271497480b84f9.
    • All protocol tests in test_locomo_protocol.py and test_locomo_runner.py pass.
    • However, test_open_query_batch_f.py:964 still expects the round-1 hash 2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870, causing a test failure.

Detailed Defects & Concrete Remediations

Defect D-1: Stale Surface Manifest Hash Assertion

  • File & Line: src/tests/surfaces/test_open_query_batch_f.py:962-965
  • Severity: High (breaks CI / test suite)
  • Reproduction:
    uv run pytest src/tests/surfaces/test_open_query_batch_f.py -k test_core_prose_is_authority_for_live_graph_and_claims_verbatim
    Output:
    AssertionError: assert '7d8ee75d2a10...71497480b84f9' == '2fff3177fd6a...bb3c36c752870'
    - 2fff3177fd6adb35c8f6a248db1d9c698cc716dc8461c818865bb3c36c752870
    + 7d8ee75d2a102485df10d96511f306e0f4e5c8d1d387b1cc9f271497480b84f9
    
  • Concrete Fix:
    Update the expected hash in src/tests/surfaces/test_open_query_batch_f.py:
        assert (
            load_manifest()["surface_manifest_hash"]
            == "7d8ee75d2a102485df10d96511f306e0f4e5c8d1d387b1cc9f271497480b84f9"
        )

Defect D-2: Inline import json Inside Test Body

  • File & Line: src/tests/surfaces/test_retrieval_batch_b.py:632
  • Severity: Low (Code cleanliness)
  • Description: import json is placed inside test_claims_canonical_unknown_count_and_overlap_match_engine_as_of right before serializing the execution plan.
  • Concrete Fix:
    Add import json to the top-level standard library imports in src/tests/surfaces/test_retrieval_batch_b.py and remove line 632.

Database Validation & Reproduction Record

In accordance with review instructions ("Test or reproduce where practical; do not claim database validation without running it"):

  1. Full Migration Chain Caveat:
    Running alembic upgrade head from base against local PostgreSQL 15 fails at revision p0_02_0001 because pg_textsearch is a specialized/PostgreSQL 19 extension available in the CI/container environment, not present on the host's standard PostgreSQL 15 instance. Therefore, full database lifecycle verification (test_migrations.py) could not be run against the host database.
  2. Executed Local SQL Verification (PostgreSQL 15):
    The following isolated database proofs were executed against localhost:5432:
    • Bug Reproduction: Tested commit 67ada2c6 view definition with rememberstack_query_* role. Replicated exact error: permission denied for function claim_canonical_start.
    • ACL Isolation: Tested commit 9b378306 inlined view with rememberstack_query_* role. Proved SELECT on memory_v1.claims_canonical succeeds while direct access to public.claims and public.claim_canonical_start raises InsufficientPrivilege.
    • Index Matching: Tested EXPLAIN query with canon_start < now(). Confirmed Bitmap Index Scan on ix_claims_canonical_window with Index Cond proving partial index eligibility.
    • Migration Lifecycle: Tested 0047 upgrade -> 0048 upgrade -> 0048 downgrade lifecycle. Confirmed ix_claims_canonical_window cleanly drops and restores to WHERE claim_valid_precision <> 'unknown'.
  3. Executed Unit Tests:
    • test_query_space_manifest.py: 15 passed in 3.52s.
    • test_locomo_protocol.py & test_locomo_runner.py: passed.
    • test_saved_queries_batch_e.py: passed.
    • test_query_sandbox_batch_b.py: 92 passed, 29 skipped in 14.93s.
    • test_open_query_batch_f.py: failed on line 964 (Defect D-1).

Merge Verdict

CHANGES REQUESTED
The underlying architecture, inlined SQL projections, security isolation, and query-role execution in 9b378306 are sound and resolve the round-1 security flaw. Once Defect D-1 in src/tests/surfaces/test_open_query_batch_f.py:964 is updated to match the rolled manifest hash, PR 375 is approved to merge.

….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.
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.
@fazpu

fazpu commented Sep 6, 2026

Copy link
Copy Markdown
Member Author

Round-three Antigravity found a real second-layer ACL issue: migration0023's per-schema default privilege revocation cannot remove PostgreSQL's global default PUBLIC function EXECUTE. Applied atddd2ea8f:0048 explicitly revokes PUBLIC EXECUTE on both private canonical twins; tests independently inspect both schema USAGE and function EXECUTE permissions. Downgrade retains the restriction rather than restoring an unintended grant. Application function owners and the explicit view-owner grants remain intact.

The review's direct-call failure claim did not reproduce on the actual migrated schema:0023 revokes public schema USAGE, and all PostgreSQL19 CI jobs at470f9921 passed, including direct-call denial. Its reduced fixture omitted that independent schema boundary. The new ACL assertions ensure denial is no longer masked by schema restrictions. The official PostgreSQL ALTER DEFAULT PRIVILEGES documentation explicitly confirms the per-schema limitation.

Round-three otherwise approved canonical arithmetic across timezones, row membership/tombstone filters, index use with one claims scan, and downgrade object/index restoration. Its isolated test reader twice held an idle transaction blocking its own DROP VIEW; only that completed temporary reader was released, with no repository source or test assertion changed. Full CI was independent of that probe.

Focused final Antigravity follow-up and CI onddd2ea8f are running. No merge until both complete.

@fazpu

fazpu commented Sep 6, 2026

Copy link
Copy Markdown
Member Author

Final Antigravity follow-up reviewedddd2ea8f: APPROVED / READY TO MERGE, no remaining findings. It independently confirmed the explicit private-function ACL fix, application-owner execution, published SECURITY DEFINER wrapper, schema and function denial, index use, retained restriction on downgrade and clean re-upgrade in a private PostgreSQL15 fixture.

The reviewer withdrew round-three's direct-call exploitability claim after reproducing the actual schema USAGE restriction. Its final validation was scoped to the role/canonical migration lifecycle and fixture, not a claim to run the entire Alembic chain locally. Full PostgreSQL19 CI remains the final integration gate. No repository changes were made by the reviewer.

@fazpu
fazpu merged commit e11115e into main Sep 6, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant