Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,19 @@ 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.

- 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
Expand Down
9 changes: 8 additions & 1 deletion PRD.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`,
Expand All @@ -175,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

Expand Down
20 changes: 20 additions & 0 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -300,6 +308,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
Expand Down
19 changes: 19 additions & 0 deletions docs/md/security-review.md
Original file line number Diff line number Diff line change
@@ -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:
Expand Down Expand Up @@ -321,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.
11 changes: 11 additions & 0 deletions docs/md/stability.md
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,14 @@ 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.

`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.
22 changes: 22 additions & 0 deletions docs/md/transactions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions jvspatial/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -170,6 +171,7 @@
"Server",
# Database & Cache
"Database",
"Transaction",
"InsertIfAbsentResult",
"GraphBindingSummary",
"LiteralBindingFact",
Expand Down
5 changes: 5 additions & 0 deletions jvspatial/db/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]:
Expand Down
5 changes: 5 additions & 0 deletions jvspatial/db/_observable.py
Original file line number Diff line number Diff line change
Expand Up @@ -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]]:
Expand Down
11 changes: 11 additions & 0 deletions jvspatial/db/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
57 changes: 57 additions & 0 deletions jvspatial/db/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -2586,11 +2596,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."""
Expand Down
21 changes: 21 additions & 0 deletions jvspatial/db/transaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion jvspatial/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
65 changes: 65 additions & 0 deletions tests/db/test_numeric_sort_coverage.py
Original file line number Diff line number Diff line change
@@ -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"}
Loading
Loading