From e0eca8ff0288ce20e9a915af2be392a81aacadc1 Mon Sep 17 00:00:00 2001 From: Eldon Marks Date: Fri, 6 Nov 2026 07:47:00 -0400 Subject: [PATCH 1/2] Release 0.2.5 with transaction-scoped PostgreSQL locks --- AGENTS.md | 5 + CHANGELOG.md | 9 ++ PRD.md | 5 + SPEC.md | 12 +++ docs/md/security-review.md | 11 ++ docs/md/stability.md | 7 ++ docs/md/transactions.md | 22 ++++ jvspatial/__init__.py | 2 + jvspatial/db/postgres.py | 47 +++++++++ jvspatial/db/transaction.py | 21 ++++ jvspatial/version.py | 2 +- tests/db/test_transaction_locks.py | 164 +++++++++++++++++++++++++++++ 12 files changed, 306 insertions(+), 1 deletion(-) create mode 100644 tests/db/test_transaction_locks.py diff --git a/AGENTS.md b/AGENTS.md index 4101587..9679de7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -94,6 +94,11 @@ The in-memory matcher and PostgreSQL pushdown treat both missing and JSON `null` Composite keyset continuation includes every sort value and direction plus ID. Never apply LIMIT before residual filtering or unsupported ordering. A configured fallback scan budget raises on exhaustion rather than returning a partial result. Bulk cache entries require confirmed outcomes; ambiguous writes are invalidated. Preserve JSON path locks/atomic durability and streaming handle cleanup on cancellation. +Transaction record/advisory locks must remain on the held connection until +completion, with current RLS and the opening schema/tenant scope. Unsupported +adapters refuse. Shared locks are not permissions; callers still prove current +access, writer participation and a consistent lock order. + File-backed SQLite closes its prior connection when rebinding to another event loop; dropping it without `close()` leaks the `aiosqlite` worker thread and can keep the process alive. ### 12. Rich graph context diff --git a/CHANGELOG.md b/CHANGELOG.md index b95d135..c793612 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ## [Unreleased] +## [0.2.5] - 2026-11-06 + +### Added + +- Transaction-scoped record and advisory locks on PostgreSQL. Shared locks + admit concurrent peers while exclusive participants and record writes wait; + locking existing records no longer requires a no-op write. Other adapters + explicitly refuse these optional ordering guarantees. + ## [0.2.4] - 2026-11-01 ### Added diff --git a/PRD.md b/PRD.md index fe96899..7ea3fff 100644 --- a/PRD.md +++ b/PRD.md @@ -155,6 +155,11 @@ The library distinguishes three tiers; [docs/md/stability.md](docs/md/stability. The PRD ratifies this tiering. Promotion of a feature from experimental to stable, or demotion of an internal helper to public, is a product decision and must be reflected here as well as in `docs/md/stability.md`. +`Transaction` is a stable top-level export. Its optional `lock_record` and +`advisory_lock` methods provide shared/exclusive transaction ordering on supported +adapters; unsupported adapters explicitly refuse. Hosts retain access policy and +must qualify their writer participation and lock order. + The stable graph projection surface includes `GraphContext.project_graph`, `ProjectionRequest`, `ProjectionScope`, `ProjectionAccess`, `ProjectionSemantics`, `ProjectionContextConfig`, `ProjectionField`, `ProjectionEvidence`, diff --git a/SPEC.md b/SPEC.md index 22391c3..8bedc09 100644 --- a/SPEC.md +++ b/SPEC.md @@ -300,6 +300,18 @@ For a file-backed SQLite database reused on a different event loop, the adapter ### 4.3.1 Transaction read and cache contract +`Transaction.lock_record(collection, record_id, shared=False)` locks and returns +an existing raw record without updating it. A missing record returns `None` and +does not fence insertion. `Transaction.advisory_lock(namespace, key, shared=False)` +orders cooperating logical-key users, including keys without records. PostgreSQL +uses transaction-scoped SHARE/UPDATE row locks and shared/exclusive advisory +locks on the held connection; commit, rollback and cancellation cleanup release +them. Logical lock namespaces include the opening schema and tenant. Advisory +hash collisions only add contention. Neither method grants access or replaces +application authorization, consistent lock ordering or native RLS. Other adapters +raise `NotImplementedError` rather than silently substituting local locks. +Sources: `jvspatial/db/transaction.py`, `jvspatial/db/postgres.py`. + `Transaction` supplies `find_one`, `count`, `find_ids`, `find_many`, `find_iter` and `count_incident_edges` alongside CRUD. All fallback reads route through the transaction handle, not its outer database. PostgreSQL overrides native reads diff --git a/docs/md/security-review.md b/docs/md/security-review.md index 252c1e7..9ce7ee1 100644 --- a/docs/md/security-review.md +++ b/docs/md/security-review.md @@ -1,5 +1,16 @@ # jvspatial — Security Code Review +## 2026-11-06 transaction ordering primitives + +Record locks retain the held connection's RLS/tenant scope, parameterize IDs and +never update the locked document. Logical locks bind namespace/key values and +freeze schema/tenant at transaction opening; collisions add contention only. +Shared peers coexist while exclusive participants wait through completion. +Unsupported adapters refuse. These are coordination primitives, not authority: +hosts must prove writer participation, current access and consistent lock order. +Regression coverage exercises actual PostgreSQL shared/exclusive ordering, +missing records, closed handles, bound SQL and unsupported adapters. + ## 2026-10-11 stalled-worktree integration review Generic `application/octet-stream` results from libmagic remain authoritative: diff --git a/docs/md/stability.md b/docs/md/stability.md index 86c8757..53df6da 100644 --- a/docs/md/stability.md +++ b/docs/md/stability.md @@ -159,3 +159,10 @@ an issue describing the use case rather than importing it. Either: and we'll point you at it. Either way, the result is a more stable foundation for everyone. + +## Transaction ordering + +The top-level `Transaction` type is stable. Its optional `lock_record` and +`advisory_lock` methods currently support PostgreSQL and raise +`NotImplementedError` on other adapters. Shared/exclusive ordering lasts until +transaction completion and does not establish application authorization. diff --git a/docs/md/transactions.md b/docs/md/transactions.md index 077de63..b5f4b8d 100644 --- a/docs/md/transactions.md +++ b/docs/md/transactions.md @@ -96,6 +96,28 @@ connection with transaction-local settings. This supports an application's configured RLS policy; it does not create an access policy or replace application authorization. +## Shared and exclusive ordering + +`Transaction.lock_record(collection, record_id, shared=True)` reads an existing +record and holds a shared row lock without updating its payload or timestamps. +Shared peers coexist; `shared=False` and normal record writes wait. A missing +record returns `None`, and an absent key is not locked against insertion. +PostgreSQL retains the transaction's tenant scope and RLS for this read. + +`Transaction.advisory_lock(namespace, key, shared=True)` holds a cooperating +logical-key lock, including keys without records. Exclusive participants use +`shared=False`. The database, schema and opening tenant separate logical scopes; +hash collisions can add contention. Advisory locks do not fence unrelated SQL: +every writer to the logical state must acquire the same exclusive key. + +Both methods currently support PostgreSQL only. Other adapters raise +`NotImplementedError`; callers must fail closed if their operation requires this +ordering. Acquire keys/records in one consistent order and choose the required +mode before acquisition. Shared-to-exclusive upgrades can deadlock. Keep network +calls outside the transaction. Commit/rollback release locks; canceled waits +must leave through normal transaction rollback. Neither method supplies an +application permission, an atomic graph revision or a portable local-lock fallback. + ## Monitoring and limits The optional observable wrapper records metrics and failure-only ERROR logs diff --git a/jvspatial/__init__.py b/jvspatial/__init__.py index 03bc9be..b0fb7e1 100644 --- a/jvspatial/__init__.py +++ b/jvspatial/__init__.py @@ -94,6 +94,7 @@ LiteralBindingFact, create_database, ) +from .db.transaction import Transaction from .db.work_claim import claim_record, delete_claimed_record, release_claim # Observability primitives @@ -170,6 +171,7 @@ "Server", # Database & Cache "Database", + "Transaction", "InsertIfAbsentResult", "GraphBindingSummary", "LiteralBindingFact", diff --git a/jvspatial/db/postgres.py b/jvspatial/db/postgres.py index 020f465..d014183 100644 --- a/jvspatial/db/postgres.py +++ b/jvspatial/db/postgres.py @@ -2586,11 +2586,58 @@ def __init__(self, db: "PostgresDB", connection: Any, transaction: Any) -> None: self._operation_lock = _TaskReentrantLock() self._bootstrapped_collections: Set[str] = set() self._closing = False + # Freeze the tenant used when the held transaction was opened. Later + # ambient tenant changes cannot select a different logical lock scope. + self._lock_scope = (db.schema_name, current_tenant()) def _ensure_active(self) -> None: if self._closing or not self.is_active or self._connection is None: raise DatabaseError("PostgreSQL transaction is no longer active") + @_serialized_transaction_operation + async def lock_record( + self, collection: str, record_id: str, *, shared: bool = False + ) -> Optional[Dict[str, Any]]: + """Read and lock one exact ID on the held, tenant-scoped connection.""" + if not isinstance(record_id, str) or not record_id or type(shared) is not bool: + raise ValueError("A record ID and boolean shared mode are required") + col = _safe_collection(collection) + schema = _safe_collection(self._db.schema_name) + await self._db._bootstrap_collection( + collection, + connection=self._connection, + pending=self._bootstrapped_collections, + ) + mode = "SHARE" if shared else "UPDATE" + row = await self._connection.fetchrow( + f"SELECT data FROM {schema}.{col} WHERE id=$1 FOR {mode}", record_id + ) + return self._db._record_from_row(row) if row is not None else None + + @_serialized_transaction_operation + async def advisory_lock( + self, namespace: str, key: str, *, shared: bool = False + ) -> None: + """Order cooperating logical-key users across connections and workers. + + PostgreSQL scopes advisory locks to the database; schema and the opening + tenant are included in the bound namespace. Hash collisions can only + cause additional contention. Locks disappear on commit or rollback. + """ + if ( + not isinstance(namespace, str) + or not namespace + or not isinstance(key, str) + or not key + or type(shared) is not bool + ): + raise ValueError("A namespace, key and boolean shared mode are required") + function = "pg_advisory_xact_lock_shared" if shared else "pg_advisory_xact_lock" + scope = json.dumps([*self._lock_scope, namespace], separators=(",", ":")) + await self._connection.execute( + f"SELECT {function}(hashtext($1), hashtext($2))", scope, key + ) + @_serialized_transaction_operation async def save(self, collection: str, data: Dict[str, Any]) -> Dict[str, Any]: """Upsert ``data`` into ``collection`` within this transaction.""" diff --git a/jvspatial/db/transaction.py b/jvspatial/db/transaction.py index 29fe2db..9c916aa 100644 --- a/jvspatial/db/transaction.py +++ b/jvspatial/db/transaction.py @@ -38,6 +38,27 @@ def __init__(self, transaction_id: str): self.is_committed = False self.is_rolled_back = False + async def lock_record( + self, collection: str, record_id: str, *, shared: bool = False + ) -> Optional[Dict[str, Any]]: + """Lock an existing raw record until completion, without modifying it. + + Shared peers may coexist; exclusive locks and record writes wait. + Missing records return None and are not protected against insertion. + Unsupported adapters refuse rather than claiming portable ordering. + """ + raise NotImplementedError("This transaction does not support record locks") + + async def advisory_lock( + self, namespace: str, key: str, *, shared: bool = False + ) -> None: + """Hold a cooperating logical-key lock until commit or rollback. + + This does not lock records or grant application access. All logical + writers must participate; unsupported adapters explicitly refuse. + """ + raise NotImplementedError("This transaction does not support advisory locks") + @abstractmethod async def save(self, collection: str, data: Dict[str, Any]) -> Dict[str, Any]: """Save a record within this transaction. diff --git a/jvspatial/version.py b/jvspatial/version.py index 17dab20..4ac8b76 100644 --- a/jvspatial/version.py +++ b/jvspatial/version.py @@ -9,4 +9,4 @@ # - MAJOR: Breaking changes # - MINOR: New features or breaking changes while pre-1.0 # - PATCH: Bug fixes, backward compatible -__version__ = "0.2.4" +__version__ = "0.2.5" diff --git a/tests/db/test_transaction_locks.py b/tests/db/test_transaction_locks.py new file mode 100644 index 0000000..a9eef70 --- /dev/null +++ b/tests/db/test_transaction_locks.py @@ -0,0 +1,164 @@ +"""Shared transaction locks admit peers while retaining exclusive ordering.""" + +import asyncio +from unittest.mock import AsyncMock + +import pytest + +from tests.db.test_postgres_integration import pg_db as pg_db +from tests.db.test_postgres_transaction_reads import _transaction + +pytestmark = pytest.mark.asyncio + + +@pytest.mark.parametrize("shared", [False, True]) +async def test_row_lock_uses_held_connection_without_a_write(shared): + connection = AsyncMock() + connection.fetchrow.return_value = {"data": {"id": "record", "entity": "Item"}} + tx = _transaction(connection) + assert await tx.lock_record("node", "record", shared=shared) == { + "id": "record", + "entity": "Item", + } + sql, record_id = connection.fetchrow.await_args.args + assert record_id == "record" + assert sql.endswith("FOR SHARE" if shared else "FOR UPDATE") + connection.execute.assert_not_awaited() + tx._db._ensure_pool.assert_not_called() + connection.fetchrow.return_value = None + assert await tx.lock_record("node", "missing", shared=shared) is None + await tx.rollback() + with pytest.raises(Exception, match="no longer active"): + await tx.lock_record("node", "record", shared=shared) + + +@pytest.mark.parametrize("shared", [False, True]) +async def test_advisory_lock_is_bound_and_transaction_scoped(shared): + connection = AsyncMock() + tx = _transaction(connection) + await tx.advisory_lock("namespace'); SELECT 1;--", "key", shared=shared) + sql, scope, key = connection.execute.await_args.args + assert ( + "pg_advisory_xact_lock_shared" in sql + if shared + else "pg_advisory_xact_lock(" in sql + ) + assert "SELECT 1" not in sql + assert "test_schema" in scope and "namespace" in scope and key == "key" + connection.fetchrow.assert_not_awaited() + + +async def test_advisory_scope_retains_the_opening_tenant(): + import json + + from jvspatial.db.postgres import PostgresDB + + database = PostgresDB(dsn="postgresql://unused/unused") + connection = AsyncMock() + async with database.tenant("first"): + tx = _transaction(connection) + async with database.tenant("second"): + await tx.advisory_lock("namespace", "key", shared=True) + assert json.loads(connection.execute.await_args.args[1]) == [ + "test_schema", + "first", + "namespace", + ] + + +@pytest.mark.parametrize("mode", [None, 0, 1, "shared"]) +async def test_lock_modes_are_literal_booleans(mode): + connection = AsyncMock() + tx = _transaction(connection) + with pytest.raises(ValueError): + await tx.lock_record("node", "record", shared=mode) + with pytest.raises(ValueError): + await tx.advisory_lock("scope", "key", shared=mode) + connection.execute.assert_not_awaited() + connection.fetchrow.assert_not_awaited() + + +async def test_unsupported_transactions_refuse_lock_guarantees(): + from jvspatial.db.transaction import MongoDBTransaction + + tx = MongoDBTransaction("test", object(), object()) + with pytest.raises(NotImplementedError): + await tx.lock_record("node", "record", shared=True) + with pytest.raises(NotImplementedError): + await tx.advisory_lock("scope", "key", shared=True) + + +@pytest.mark.parametrize("kind", ["record", "advisory"]) +async def test_shared_peers_block_exclusive_until_both_commit(pg_db, kind): + await pg_db.save("node", {"id": "record", "entity": "Item"}) + first = await pg_db.begin_transaction() + second = await pg_db.begin_transaction() + writer = await pg_db.begin_transaction() + + async def lock(tx, shared): + if kind == "record": + return await tx.lock_record("node", "record", shared=shared) + return await tx.advisory_lock("test", "record", shared=shared) + + pending = None + try: + await asyncio.wait_for(lock(first, True), 2) + await asyncio.wait_for(lock(second, True), 2) + pending = asyncio.create_task(lock(writer, False)) + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(asyncio.shield(pending), 0.1) + await first.commit() + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(asyncio.shield(pending), 0.1) + await second.commit() + await asyncio.wait_for(pending, 2) + await writer.commit() + assert await pg_db.get("node", "record") == {"id": "record", "entity": "Item"} + finally: + if pending is not None and not pending.done(): + pending.cancel() + await asyncio.gather(pending, return_exceptions=True) + for tx in (writer, second, first): + await tx.rollback() + + +@pytest.mark.parametrize("kind", ["record", "advisory"]) +async def test_canceled_lock_wait_rolls_back_and_does_not_leak(pg_db, kind): + from jvspatial.db.transaction import transaction_context + + await pg_db.save("node", {"id": "record", "entity": "Item"}) + + async def lock(tx, shared): + if kind == "record": + await tx.lock_record("node", "record", shared=shared) + else: + await tx.advisory_lock("test", "record", shared=shared) + + holder = await pg_db.begin_transaction() + await lock(holder, False) + waiting = asyncio.Event() + handles = [] + + async def canceled_peer(): + async with transaction_context(pg_db) as tx: + handles.append(tx) + waiting.set() + await lock(tx, True) + + peer = asyncio.create_task(canceled_peer()) + try: + await asyncio.wait_for(waiting.wait(), 2) + with pytest.raises(asyncio.TimeoutError): + await asyncio.wait_for(asyncio.shield(peer), 0.1) + peer.cancel() + with pytest.raises(asyncio.CancelledError): + await peer + assert handles[0].is_rolled_back + await holder.commit() + async with transaction_context(pg_db) as fresh: + await asyncio.wait_for(lock(fresh, False), 2) + finally: + if not peer.done(): + peer.cancel() + await asyncio.gather(peer, return_exceptions=True) + await holder.rollback() From 90add53f11740452fd9aac504d09e907b8f64566 Mon Sep 17 00:00:00 2001 From: Eldon Marks Date: Fri, 6 Nov 2026 09:01:10 -0400 Subject: [PATCH 2/2] Expose numeric sort compiler coverage without changing query behavior --- CHANGELOG.md | 4 ++ PRD.md | 4 +- SPEC.md | 8 ++++ docs/md/security-review.md | 8 ++++ docs/md/stability.md | 4 ++ jvspatial/db/_cache.py | 5 ++ jvspatial/db/_observable.py | 5 ++ jvspatial/db/database.py | 11 +++++ jvspatial/db/postgres.py | 10 ++++ tests/db/test_numeric_sort_coverage.py | 65 ++++++++++++++++++++++++++ 10 files changed, 123 insertions(+), 1 deletion(-) create mode 100644 tests/db/test_numeric_sort_coverage.py diff --git a/CHANGELOG.md b/CHANGELOG.md index c793612..cbb5fb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 locking existing records no longer requires a no-op write. Other adapters explicitly refuse these optional ordering guarantees. +- Pure `Database.can_pushdown_numeric_sort` compiler coverage allows callers + to discover existing numeric ordering support without relying on adapter + classes. It does not execute a query or certify data types/access. + ## [0.2.4] - 2026-11-01 ### Added diff --git a/PRD.md b/PRD.md index 7ea3fff..b64908d 100644 --- a/PRD.md +++ b/PRD.md @@ -180,7 +180,9 @@ missing-preserving selected values, with a portable default) and optional `LiteralBindingFact` / `GraphBindingSummary` types. One-hop binding summaries report complete or capped primary storage facts; hosts retain rooted scope and current authorization. Unsupported adapters return `None`; transaction-bound -handles do not escape their connection. These are public stable additive APIs. +handles do not escape their connection. These are public stable additive APIs. `Database.can_pushdown_numeric_sort` +exposes pure compiler coverage for numeric/null ordering; hosts still prove +current value types and access. It does not change existing query behavior. ## 8. Decision Boundaries diff --git a/SPEC.md b/SPEC.md index 8bedc09..65e5a91 100644 --- a/SPEC.md +++ b/SPEC.md @@ -284,6 +284,14 @@ Node adjacency always lives in the edge collection (indexed on `source` / with `jvspatial migrate strip-node-edges` (`strip_node_edges()` on `PostgresDB` / `MongoDB` / `JsonDB`). +`Database.can_pushdown_numeric_sort(query, sort)` is a pure compiler-coverage +check. PostgreSQL returns true only when both the complete predicate and order +translate; the default returns false, and cache/observability wrappers delegate. +It executes no I/O, proves no record type or authorization, and promises no +index use. Callers must establish homogeneous number/null values for non-ID +sort keys and retain their own current audience, cursor and release checks. +Existing query and ordering behavior is unchanged. + Callers branching on capabilities should test the flag, not the adapter class. ### 4.3 Built-in adapters diff --git a/docs/md/security-review.md b/docs/md/security-review.md index 9ce7ee1..965b69a 100644 --- a/docs/md/security-review.md +++ b/docs/md/security-review.md @@ -332,3 +332,11 @@ All findings were cross-referenced between passes and verified against current c ## Conclusion All 20 issues in the May 2026 review were remediated at that time. See the September 2026 combined review above for later findings and fixes. Deployment readiness still depends on the operator's shared-store and infrastructure choices documented in `ROADMAP.md` §2. + +### Numeric ordering compiler coverage + +`Database.can_pushdown_numeric_sort` is a pure predicate/compiler check. It +executes no query, changes no SQL behavior, and certifies neither stored value +types nor application authority. The default refuses and wrappers delegate +without caching. Hosts must retain current audience and homogeneous numeric/null +proofs; unsupported predicates or ordering cannot become a partial native LIMIT. diff --git a/docs/md/stability.md b/docs/md/stability.md index 53df6da..02c489d 100644 --- a/docs/md/stability.md +++ b/docs/md/stability.md @@ -166,3 +166,7 @@ The top-level `Transaction` type is stable. Its optional `lock_record` and `advisory_lock` methods currently support PostgreSQL and raise `NotImplementedError` on other adapters. Shared/exclusive ordering lasts until transaction completion and does not establish application authorization. + +`Database.can_pushdown_numeric_sort` is a stable optional coverage check. +Unsupported adapters return false. A true result is neither data-type +validation nor an authorization result and does not promise indexed execution. diff --git a/jvspatial/db/_cache.py b/jvspatial/db/_cache.py index ee82c93..ef21458 100644 --- a/jvspatial/db/_cache.py +++ b/jvspatial/db/_cache.py @@ -248,6 +248,11 @@ def supports_native_projected_reads(self) -> bool: """Expose native projection support without promising a complete entity.""" return bool(getattr(self.inner, "supports_native_projected_reads", False)) + def can_pushdown_numeric_sort(self, query, sort) -> bool: + """Forward compiler coverage, never a cached data/authorization result.""" + checker = getattr(self.inner, "can_pushdown_numeric_sort", None) + return bool(checker(query, sort)) if callable(checker) else False + async def graph_edge_page( self, node_id: str, *, after: Optional[str] = None, limit: int = 50 ) -> List[Dict[str, Any]]: diff --git a/jvspatial/db/_observable.py b/jvspatial/db/_observable.py index 5445a1f..1a78a0f 100644 --- a/jvspatial/db/_observable.py +++ b/jvspatial/db/_observable.py @@ -357,6 +357,11 @@ def supports_native_projected_reads(self) -> bool: """Expose native projection support without promising a complete entity.""" return bool(getattr(self.inner, "supports_native_projected_reads", False)) + def can_pushdown_numeric_sort(self, query, sort) -> bool: + """Forward compiler coverage without recording a database operation.""" + checker = getattr(self.inner, "can_pushdown_numeric_sort", None) + return bool(checker(query, sort)) if callable(checker) else False + async def graph_edge_page( self, node_id: str, *, after: Optional[str] = None, limit: int = 50 ) -> List[Dict[str, Any]]: diff --git a/jvspatial/db/database.py b/jvspatial/db/database.py index 45f77c3..544ea11 100644 --- a/jvspatial/db/database.py +++ b/jvspatial/db/database.py @@ -416,6 +416,17 @@ def supports_native_graph_binding_summary(self) -> bool: """Whether the current adapter provides native graph fact summaries.""" return False + def can_pushdown_numeric_sort( + self, query: Dict[str, Any], sort: List[Tuple[str, int]] + ) -> bool: + """Whether this query/order can remain native for number/null keys. + + This is compiler coverage, not a data-type or permission proof. The + caller must establish homogeneous numeric/null values for non-ID + keys. Unsupported adapters refuse; no query is executed here. + """ + return False + async def graph_node_batch(self, ids: List[str]) -> Dict[str, Dict[str, Any]]: """Fetch raw projection nodes; wrappers bypass stale record caches.""" return await self.find_many("node", ids) diff --git a/jvspatial/db/postgres.py b/jvspatial/db/postgres.py index d014183..1f93cc6 100644 --- a/jvspatial/db/postgres.py +++ b/jvspatial/db/postgres.py @@ -363,6 +363,16 @@ class PostgresDB(Database): supports_native_projected_reads: bool = True supports_native_graph_binding_summary: bool = True + def can_pushdown_numeric_sort( + self, query: Dict[str, Any], sort: List[Tuple[str, int]] + ) -> bool: + """Report complete compiler coverage without fetching or granting data.""" + return ( + bool(sort) + and translate_query(query) is not None + and translate_sort(sort) is not None + ) + def __init__( self, dsn: Optional[str] = None, diff --git a/tests/db/test_numeric_sort_coverage.py b/tests/db/test_numeric_sort_coverage.py new file mode 100644 index 0000000..e0a1f97 --- /dev/null +++ b/tests/db/test_numeric_sort_coverage.py @@ -0,0 +1,65 @@ +"""Compiler coverage is explicit and never certifies data types or access.""" + +from unittest.mock import AsyncMock + +import pytest + +from jvspatial.db.jsondb import JsonDB +from jvspatial.db.postgres import PostgresDB +from tests.db.test_postgres_integration import pg_db as pg_db + + +def test_default_backend_refuses_numeric_pushdown_coverage(tmp_path): + database = JsonDB(str(tmp_path)) + assert not database.can_pushdown_numeric_sort({}, [("context.score", 1)]) + + +def test_postgres_coverage_requires_the_whole_query_and_order(): + database = PostgresDB(dsn="postgresql://unused/unused") + database._ensure_pool = AsyncMock(side_effect=AssertionError("No I/O permitted")) + assert database.can_pushdown_numeric_sort( + {"context.score": {"$type": "number"}}, [("context.score", 1), ("id", 1)] + ) + assert not database.can_pushdown_numeric_sort({}, [("context.my-score", 1)]) + assert not database.can_pushdown_numeric_sort( + {"context.score": {"$unsupported": 1}}, [("id", 1)] + ) + assert not database.can_pushdown_numeric_sort({}, []) + database._ensure_pool.assert_not_awaited() + + +def test_wrappers_forward_current_coverage_without_a_data_cache(tmp_path): + from jvspatial.db._cache import CachingDatabase + from jvspatial.db._observable import ObservableDatabase + + database = ObservableDatabase( + CachingDatabase(PostgresDB(dsn="postgresql://unused/unused")) + ) + assert database.can_pushdown_numeric_sort({}, [("context.score", -1), ("id", -1)]) + assert not database.can_pushdown_numeric_sort({}, [("context.my-score", 1)]) + database.inner.inner = JsonDB(str(tmp_path)) + assert not database.can_pushdown_numeric_sort({}, [("context.score", -1)]) + + +@pytest.mark.asyncio +async def test_covered_projection_preserves_numeric_top_n_and_nulls(pg_db): + for identifier, value in (("a", 10), ("b", 9), ("c", 2), ("d", None)): + await pg_db.save( + "node", {"id": identifier, "entity": "Item", "context": {"score": value}} + ) + await pg_db.save("node", {"id": "e", "entity": "Item", "context": {}}) + for direction, expected in ((1, ["c", "b"]), (-1, ["a", "b"])): + ordering = [("context.score", direction), ("id", direction)] + assert pg_db.can_pushdown_numeric_sort({"entity": "Item"}, ordering) + page = await pg_db.find_projected( + "node", + {"entity": "Item"}, + fields=["id", "context.score"], + sort=ordering, + limit=2, + ) + assert [row["id"] for row in page] == expected + all_rows = await pg_db.find_projected( + "node", {"entity": "Item"}, fields=["id"], sort=ordering + ) + assert set(row["id"] for row in all_rows[-2:]) == {"d", "e"}