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
9 changes: 9 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [0.2.6] - 2026-11-07

### Added

- Optional PostgreSQL binary text keyset reads and matching indexes preserve
Python text and ID ordering, with missing values last in either direction.
Unsupported predicates and out-of-contract text values signal a portable
fallback. The caller remains responsible for authorizing returned records.

## [0.2.5] - 2026-11-06

### Added
Expand Down
10 changes: 10 additions & 0 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,16 @@ No built-in migration framework. Adapters do not enforce schemas. Adding optiona
### 4.7 Bounded I/O and query execution

- Composite keysets validate sort fields/directions and append ID when absent.
- PostgreSQL also supports explicit binary text keysets through
`PostgresDB.find_binary_text_keyset` and
`PostgresDB.create_binary_text_keyset_indexes` (`db/postgres.py`). A read
takes a collection, entity, exact text scope, text field, direction,
optional (text or null, ID) cursor, and positive limit. UTF-8 text and IDs
follow binary order, with missing or null text last. Unsupported predicates,
non-UTF-8 databases, or scoped text outside the index contract (non-string
or longer than 1,024 bytes) return `None` for portable fallback. The read
uses the current tenant connection and returns storage candidates.

Continuation encodes every field and direction; old ID-only cursors remain
supported for ID-only sorts. Missing/null are last for SQL/in-memory ordering;
Mongo retains BSON ascending nulls-first behavior. Scalars should use a
Expand Down
142 changes: 142 additions & 0 deletions jvspatial/db/_binary_text_keyset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
"""PostgreSQL keyset ordering with the same text order as Python."""

import hashlib
import json

from ._postgres_translate import _path_literal, _safe_field_path, translate_query


def _expressions(field, scope_field):
if not all(_safe_field_path(path) for path in (field, scope_field)):
raise ValueError("Invalid text keyset field path")
value = f"(data #> '{_path_literal(field)}')"
title = f"(data #>> '{_path_literal(field)}') COLLATE \"C\""
scope = f"(data #> '{_path_literal(scope_field)}')"
# Keep unusually long legacy values out of the B-tree without blocking
# writes or silently changing how the caller sorts them.
malformed = (
f"(COALESCE(jsonb_typeof({value}) NOT IN ('string','null'), FALSE) "
f"OR COALESCE(octet_length({title}) > 1024, FALSE))"
)
return title, scope, malformed


async def create_indexes(database, collection, *, field, scope_field, entity):
"""Create the scoped text and fallback-detection indexes."""
from .postgres import _pg_string_literal, _safe_collection

title, scope, malformed = _expressions(field, scope_field)
schema, table = _safe_collection(database.schema_name), _safe_collection(collection)
key = hashlib.sha256(
f"{table}:{entity}:{scope_field}:{field}".encode()
).hexdigest()[:24]
entity_filter = f"entity={_pg_string_literal(entity)}"
await database._bootstrap_collection(collection)
async with database._acquire_conn() as connection:
async with connection.transaction():
await connection.execute(
"SELECT pg_advisory_xact_lock(hashtext($1), hashtext($2))",
schema,
key,
)
for direction in ("ASC", "DESC"):
await connection.execute(
f"CREATE INDEX IF NOT EXISTS text_page_{key}_{direction.lower()} "
f"ON {schema}.{table} "
f"({scope}, {title} {direction} NULLS LAST, "
f'id COLLATE "C" {direction}) WHERE {entity_filter} AND NOT {malformed}'
)
await connection.execute(
f"CREATE INDEX IF NOT EXISTS text_page_{key}_malformed "
f"ON {schema}.{table} ({scope}) WHERE {entity_filter} AND {malformed}"
)


async def read_page(
database,
collection,
query,
*,
field,
scope_field,
scope_value,
entity,
direction,
after,
limit,
):
"""Read a binary-ordered page or signal portable fallback."""
from .postgres import _pg_string_literal, _safe_collection

if (
direction not in (1, -1)
or type(limit) is not int
or limit <= 0
or not isinstance(scope_value, str)
or not isinstance(entity, str)
or (
after is not None
and (
not isinstance(after, tuple)
or len(after) != 2
or (after[0] is not None and not isinstance(after[0], str))
or not isinstance(after[1], str)
)
)
):
raise ValueError("Invalid binary text keyset request")
translated = translate_query(query)
if translated is None:
return None
title, scope, malformed = _expressions(field, scope_field)
schema, table = _safe_collection(database.schema_name), _safe_collection(collection)
predicate, values = translated
params = list(values)

def bind(value):
params.append(value)
return f"${len(params)}"

scope_where = f"entity={_pg_string_literal(entity)} AND {scope}=to_jsonb({bind(scope_value)}::text)"
where = f"{scope_where} AND ({predicate})" if predicate else scope_where
# Check the whole scope, including rows outside the caller's filter. A
# malformed title must never silently change the portable ordering.
invalid = f"SELECT 1 FROM {schema}.{table} WHERE {scope_where} AND {malformed}"
order = "ASC" if direction == 1 else "DESC"
op = ">" if direction == 1 else "<"
identifier = 'id COLLATE "C"'
order_by = f"{title} {order} NULLS LAST, {identifier} {order}"
where += f" AND NOT {malformed}"
where += " AND current_setting('server_encoding')='UTF8' AND NOT EXISTS (SELECT 1 FROM invalid)"
select = f"SELECT data, id FROM {schema}.{table} WHERE {where}"
cap = bind(limit)
if after is None:
page = f"SELECT data FROM {schema}.{table} WHERE {where} ORDER BY {order_by} LIMIT {cap}"
else:
value, record_id = after
tie = bind(record_id)
if value is None:
page = (
f"SELECT data FROM {schema}.{table} WHERE {where} AND {title} IS NULL "
f"AND {identifier} {op} {tie} ORDER BY {order_by} LIMIT {cap}"
)
else:
cursor = bind(value)
# Separate the null tail so the non-null branch can seek directly
# on the composite (text, ID) key, including on deep cursors.
page = (
f"SELECT data FROM (({select} AND ({title}, {identifier}) {op} "
f"({cursor}, {tie}) ORDER BY {order_by} LIMIT {cap}) UNION ALL "
f"({select} AND {title} IS NULL ORDER BY {order_by} LIMIT {cap})) "
f"AS page ORDER BY {order_by} LIMIT {cap}"
)
statement = (
f"WITH invalid AS MATERIALIZED ({invalid} LIMIT 1) "
f"SELECT (current_setting('server_encoding')<>'UTF8' OR EXISTS (SELECT 1 FROM invalid)) AS invalid, ARRAY({page}) AS rows"
)
await database._bootstrap_collection(collection)
async with database._acquire_conn() as connection:
row = await connection.fetchrow(statement, *params)
if row["invalid"]:
return None
return [json.loads(item) if isinstance(item, str) else item for item in row["rows"]]
11 changes: 11 additions & 0 deletions jvspatial/db/_cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,17 @@ async def find(
# find() is intentionally NOT cached. See module docstring.
return await self.inner.find(collection, query, limit=limit, sort=sort)

async def create_binary_text_keyset_indexes(self, collection, **kwargs):
"""Forward optional text index setup to the underlying adapter."""
writer = getattr(self.inner, "create_binary_text_keyset_indexes", None)
if callable(writer):
await writer(collection, **kwargs)

async def find_binary_text_keyset(self, collection, query, **kwargs):
"""Read text keysets without caching candidate rows."""
reader = getattr(self.inner, "find_binary_text_keyset", None)
return await reader(collection, query, **kwargs) if callable(reader) else None

async def summarize_graph_bindings(self, query, **kwargs):
"""Forward current graph facts without caching a summary as authority."""
reader = getattr(self.inner, "summarize_graph_bindings", None)
Expand Down
18 changes: 18 additions & 0 deletions jvspatial/db/_observable.py
Original file line number Diff line number Diff line change
Expand Up @@ -309,6 +309,24 @@ async def find(
result_count_extractor=lambda r: len(r) if isinstance(r, list) else 0,
)

async def create_binary_text_keyset_indexes(self, collection, **kwargs):
"""Forward optional text index setup to the underlying adapter."""
writer = getattr(self.inner, "create_binary_text_keyset_indexes", None)
if callable(writer):
await writer(collection, **kwargs)

async def find_binary_text_keyset(self, collection, query, **kwargs):
"""Read text keysets without caching candidate rows."""
reader = getattr(self.inner, "find_binary_text_keyset", None)
if not callable(reader):
return None
return await self._instrument(
"find_binary_text_keyset",
collection,
lambda: reader(collection, query, **kwargs),
result_count_extractor=lambda rows: len(rows) if rows is not None else 0,
)

async def summarize_graph_bindings(self, query, **kwargs):
"""Observe one logical graph fact read, preserving upstream recording."""
reader = getattr(self.inner, "summarize_graph_bindings", None)
Expand Down
12 changes: 12 additions & 0 deletions jvspatial/db/postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -1135,6 +1135,18 @@ async def find(
records = finalize_find_results(records, sort=sort, limit=limit)
return records

async def create_binary_text_keyset_indexes(self, collection, **kwargs):
"""Prepare indexes for explicit Python-compatible text keyset reads."""
from ._binary_text_keyset import create_indexes

await create_indexes(self, collection, **kwargs)

async def find_binary_text_keyset(self, collection, query, **kwargs):
"""Return a bounded ordered page, or None if ordering is unsupported."""
from ._binary_text_keyset import read_page

return await read_page(self, collection, query, **kwargs)

async def summarize_graph_bindings(
self,
query: Dict[str, Any],
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.5"
__version__ = "0.2.6"
73 changes: 73 additions & 0 deletions tests/db/test_postgres_binary_text_keyset.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
"""Explicit text keysets preserve portable ordering under PostgreSQL collation."""

import pytest

from tests.db.test_postgres_integration import pg_db as pg_db

pytestmark = pytest.mark.asyncio
KEY = {"field": "context.label", "scope_field": "context.parent", "entity": "Record"}


@pytest.mark.parametrize("direction", [1, -1])
async def test_binary_keyset_orders_unicode_ties_and_missing_last(pg_db, direction):
await pg_db.create_binary_text_keyset_indexes("node", **KEY)
labels = ["a", "Z", "Z", "é", "Ω", "😀", None, "", None]
expected = []
for i, label in enumerate(labels):
identifier = f"n.Record.{i}"
context = {"parent": "wanted"}
if i != 8:
context["label"] = label
await pg_db.save(
"node", {"id": identifier, "entity": "Record", "context": context}
)
expected.append((label, identifier))
await pg_db.save(
"node",
{
"id": "n.Record.foreign",
"entity": "Record",
"context": {"parent": "foreign", "label": 123},
},
)
reverse = direction == -1
present = sorted(
(item for item in expected if item[0] is not None), reverse=reverse
)
missing = sorted((item for item in expected if item[0] is None), reverse=reverse)
seen = []
cursor = None
for _ in range(6):
rows = await pg_db.find_binary_text_keyset(
"node",
{},
**KEY,
scope_value="wanted",
direction=direction,
after=cursor,
limit=2,
)
if not rows:
break
seen.extend((row["context"].get("label"), row["id"]) for row in rows)
cursor = seen[-1]
assert seen == present + missing


@pytest.mark.parametrize("bad_value", [42, "😀" * 400])
async def test_binary_keyset_falls_back_for_out_of_contract_values(pg_db, bad_value):
await pg_db.create_binary_text_keyset_indexes("node", **KEY)
await pg_db.save(
"node",
{
"id": "n.Record.unsupported",
"entity": "Record",
"context": {"parent": "wanted", "label": bad_value},
},
)
assert (
await pg_db.find_binary_text_keyset(
"node", {}, **KEY, scope_value="wanted", direction=1, after=None, limit=2
)
is None
)
Loading