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

## [Unreleased]

### Added

- Add public `IndexSpec` / `ManagedSchemaError` and opt-in strict managed
PostgreSQL mode. Persistent schema/index creation is reserved for host
provisioning; uniqueness verification remains mandatory. Existing adapter
defaults are preserved.
- Managed PostgreSQL catalogs are host-configurable through `index_catalog_table`
or `JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE`, defaulting to the neutral
`jvspatial_index_catalog` relation.

- PostgreSQL `index_creation="constraints"` / `JVSPATIAL_POSTGRES_INDEX_CREATION`
controls automatic performance-index DDL independently of unique constraints.
Existing indexes remain intact and explicit maintenance adapters can provision
reviewed indexes using the compatible `auto` mode.

- Walker traversal sessions emit class, step count and pause state with the host
provider, without automatic node identities or report contents.
- Authentication emits a content-free `auth.authenticate` span around the existing authentication boundary.
- Observed database operations emit content-free OpenTelemetry spans using the
host provider. PostgreSQL observations expose driver statement counts and
execution time on the shared acquisition path; connection callbacks are
removed before pool release.

### Fixed

- `constraints` mode also skips explicit binary-text keyset performance indexes.
- Authentication trace exceptions set ERROR status without exception content.
- Optional tracing tests skip when the OpenTelemetry API is absent.

- Database, traversal and HTTP trace errors record exception type/status without exception messages
or stack events that could contain query parameters.

## [0.2.9] - 2026-11-10

### Changed
Expand Down
4 changes: 4 additions & 0 deletions PRD.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,10 @@ 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`.

`IndexSpec` and `ManagedSchemaError` are stable top-level exports for opt-in
managed PostgreSQL hosts. Catalog approval and migrations remain host concerns;
unrelated consumers retain compatibility defaults.

`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
Expand Down
57 changes: 57 additions & 0 deletions SPEC.md
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,8 @@ These are *defaults* — subclasses or callers can override. Disabling protectio

Indexed fields (`@attribute(indexed=True)`) and compound indexes (`@attribute(compound_index=...)`) inform backend index creation (where supported).

PostgreSQL provisioning follows the [index policy](#48-postgresql-index-policy).

Single-field `attribute(index_direction=-1)` declarations reach adapters as
`[(field, -1)]`; ascending declarations retain the bare field string for name
compatibility (`jvspatial/core/context.py:1579`). PostgreSQL repairs a canonical
Expand Down Expand Up @@ -452,6 +454,44 @@ No built-in migration framework. Adapters do not enforce schemas. Adding optiona
`jvspatial/db/_observable.py:524`.


### 4.8 PostgreSQL index policy

PostgreSQL `index_creation="constraints"` / `JVSPATIAL_POSTGRES_INDEX_CREATION=constraints`
defers performance index DDL while preserving unique-index provisioning/repair
and fixed collection baseline indexes. Ordinary, sort-companion, whole-data GIN,
binary-text keyset and vector indexes are not created in this mode; existing
indexes are retained.
The compatible default is `auto`, also available as an explicit maintenance
adapter override. This is separate from `JVSPATIAL_AUTO_CREATE_INDEXES`, which
skips annotation-declared unique indexes as well as performance declarations.
The policy does not govern host-issued migration SQL (`jvspatial/db/postgres.py`).

#### Managed PostgreSQL index boundary

`PostgresDB(index_creation="managed")` separates opening connections from
persistent schema initialization. Model uniqueness is verified and cached; optional
filter, keyset and vector declarations execute no index DDL. Vector column shape
is verified; RLS and binding-projection installation require maintenance.
`IndexSpec` carries canonical compiler definitions, query coverage and stable
fingerprint names. Hosts own approved catalogs and provisioning. Compatibility
default remains `auto`. Sources: [indexes](jvspatial/db/indexes.py:1),
[adapter](jvspatial/db/postgres.py:425),
[keyset helper](jvspatial/db/_binary_text_keyset.py:27).

The applied catalog is selected by `PostgresDB(index_catalog_table=...)`, falling
back to `JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE` and then
`jvspatial_index_catalog`. It is an unqualified table in `schema_name`; both names
are validated with the adapter's safe identifier rules. The host provisions this
relation with `fingerprint text PRIMARY KEY`, `index_name text NOT NULL`, and
`definition_hash text NOT NULL` (additional host columns are permitted).
`fingerprint` is `IndexSpec.fingerprint`; `index_name` identifies the physical index
in that schema; `definition_hash` is `definition_digest(pg_get_indexdef(index_oid))`
from `jvspatial.db.indexes`. Only the host's maintenance role writes these receipts;
runtime requires SELECT. Verification checks the receipt, actual index validity
and readiness, and the current definition hash without provisioning the catalog.
Sources: `jvspatial/db/postgres.py` (`PostgresDB.__init__`, `verify_index_spec`).


## 5. Query Interface

### 5.1 Mongo-style operators
Expand Down Expand Up @@ -923,6 +963,23 @@ separate from total consumer-inclusive duration. These are driver/candidate
metrics, not physical protocol round trips or server rows scanned.
Source: `jvspatial/db/_observable.py`.

Observed non-streaming operations also create content-free database spans using
an application-installed OpenTelemetry provider. Attributes include operation,
backend, collection, success and available result/I/O counts. Exception events,
SQL text and parameters are not recorded; error type and status remain available.
Observed PostgreSQL calls using the shared acquisition helper report
`driver_statements` and `driver_duration_ms` from asyncpg query callbacks in
addition to pool wait. These measure driver executions, not physical protocol
round trips; direct transaction-connection operations outside that helper are
not covered by these two counters. Query logger callbacks are removed before
connections return to the pool. The authentication request boundary emits `auth.authenticate` without headers, tokens or exception content. No SDK or exporter is configured by the library.

`Walker.run()` traces the traversal class, protection step count and paused state
with a recording host provider, without automatically including node/walker IDs
or report values. Database, walker and HTTP helper errors omit exception messages
and stack events. Source: `jvspatial/core/entities/walker.py`,
`jvspatial/observability/tracing.py`.


### 14.3 GraphContext PerformanceMonitor

Expand Down
23 changes: 23 additions & 0 deletions docs/md/observability.md
Original file line number Diff line number Diff line change
Expand Up @@ -167,3 +167,26 @@ distinction between `CachingDatabase` (disabled) and `GraphContext` /

- [`stability.md`](stability.md) — `MetricsRecorder` Protocol is public.
- [`benchmarks.md`](benchmarks.md) — performance regression suite.

## Database timing spans

Observed non-streaming operations use the application's OpenTelemetry provider.
No SDK/exporter is created in the library. Database spans include bounded
operation/backend/collection attributes and numeric result/I/O measurements.
They exclude SQL text, parameters and exception messages. PostgreSQL's shared
connection acquisition path additionally emits `jvspatial.db.query.driver_statements`
and `jvspatial.db.query.driver_duration_ms`. These do not count wire round trips
and do not cover reads issued directly through held transaction connections.
Pool wait is separate from driver execution; summed concurrent timings are not
elapsed request time. Existing successful-operation logging remains silent.
Driver elapsed time includes client scheduling/network waits; use PostgreSQL
execution plans to distinguish server execution from a blocked application loop.
`decoded_chars` counts characters in JSON strings decoded while hydrating rows;
it is a size measurement, not UTF-8 bytes, and captures no record content.

`Walker.run()` emits a traversal span when the host installs a recording provider.
It records the class, protection step count and pause state. It does not pass
walker/node identities or reports into the tracing helper. Traversal and HTTP
helper errors retain error type/status without exception messages or stack events.
With no recording provider, traversal, authentication and observed database calls
skip proxy-span allocation and retain their existing execution/metrics behavior.
75 changes: 75 additions & 0 deletions docs/md/postgres-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,27 @@ accelerates containment-shaped predicates (`$all`); see

### Index policy

- **Managed performance indexes.** Set
`JVSPATIAL_POSTGRES_INDEX_CREATION=constraints` (or construct the adapter with
`index_creation="constraints"`) to defer ordinary `create_index` declarations,
their sort companions, binary-text keyset, whole-document GIN and vector index
creation. Existing
indexes are retained. Unique declarations still create/repair their constraints;
the collection primary key and fixed entity/tenant baseline remain provisioned.
Vector storage columns are still initialized, but their search indexes must be
provisioned explicitly. Invalid modes fail at adapter construction.
The compatible default is `auto`. Provision reviewed performance indexes with
a separate maintenance adapter explicitly configured with
`index_creation="auto"`; do not enable it in serving processes just to install
one index. This policy governs adapter-created indexes, not arbitrary SQL run
by a host's schema migrations.
Keep `JVSPATIAL_AUTO_CREATE_INDEXES=true` so annotation-declared uniqueness is
still requested. Disabling that graph-level flag skips unique declarations too.
On a fresh database, prepare required query indexes before serving populated
workloads. On an existing database this setting stops new automatic performance
DDL; it does not shrink or remove expensive existing indexes. Index removal
requires a separate query/constraint inventory and reviewed migration.

- **Per-class indexes lead with `entity`.** Every typed `find()` filters on
the `entity` column of a table shared by every class, so an index declared
with `attribute(indexed=True)` or `@compound_index(...)` is created as
Expand Down Expand Up @@ -386,3 +407,57 @@ precedence):
- [neon-deployment.md](neon-deployment.md) — Neon-specific notes
- [aurora-serverless-deployment.md](aurora-serverless-deployment.md) — Aurora SLv2
- [optimization.md](optimization.md) — cross-backend performance guidance

## Managed schema boundary

`PostgresDB(index_creation="managed")` is opt-in; unrelated consumers retain
`auto` by default. The host must provision relations and a reviewed catalog before
opening its serving adapter. Connection initialization performs no persistent DDL.
Nonunique model, pagination and vector-index declarations cannot build indexes.
Unique declarations call read-only `verify_index_spec`, checking valid/ready state
and the persisted definition hash before caching verification on that adapter.
Missing relations, required integrity, vector columns, RLS/projection provisioning
raise `ManagedSchemaError`. Vector column verification does not build ANN indexes.

Configure the applied-index catalog using the constructor or environment:

```python
db = PostgresDB(
dsn=runtime_dsn,
schema_name="public",
index_creation="managed",
index_catalog_table="host_index_catalog",
)
```

`index_catalog_table` overrides `JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE`; the
default is `jvspatial_index_catalog`. Supply an unqualified table name in the
adapter's `schema_name`, not SQL or a schema-qualified path. Both identifiers
are validated before verification queries. The host must provision at least:

```sql
CREATE TABLE public.host_index_catalog (
fingerprint text PRIMARY KEY,
index_name text NOT NULL,
definition_hash text NOT NULL
);
```

Additional host-owned columns are permitted. `fingerprint` is the approved
`IndexSpec.fingerprint`, `index_name` is the actual index name in the same schema,
and `definition_hash` is `jvspatial.db.indexes.definition_digest` applied to
PostgreSQL's `pg_get_indexdef(index_oid)` result. Record receipts only after the
host verifies and approves the physical definition. Runtime needs SELECT on this
table; reserve receipt writes for the maintenance role. The adapter neither
creates the catalog nor acknowledges a missing, invalid or changed index.

`IndexSpec` and `ManagedSchemaError` are public top-level exports. Specifications
carry logical identity, owner/version, physical keys/expressions (including order,
collation and operator class), predicates, method, uniqueness, correctness need
and query references. Expressions are trusted compiler/schema inputs, never raw
end-user SQL. Physical fingerprints deduplicate equivalent canonical inputs and
produce bounded names; hosts own approval, budgets and migration execution. The
adapter does not automatically migrate to a changed definition in managed mode.
Use distinct DML-only runtime credentials: ownership itself confers DDL authority.
Temporary staging tables used for bulk DML remain connection-local and bounded;
they do not create persistent schema or indexes.
20 changes: 20 additions & 0 deletions docs/md/security-review.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,17 @@ 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-11-05 content-free performance observations

Authentication timing wraps the existing authentication method without changing
method order, constant-time comparisons, token validation or RBAC. It records no
headers, request objects, tokens or exception content. Observed database spans
also suppress exception messages/events; generic error type/status and numeric
I/O counters remain. Asyncpg query callbacks never read SQL text/arguments and
are removed before pool release, including cancellation. The application owns
SDK/exporter configuration. Authentication and database privacy/cancellation
regressions exercise these boundaries; no credential policy changes.

## 2026-10-11 stalled-worktree integration review

Generic `application/octet-stream` results from libmagic remain authoritative:
Expand Down Expand Up @@ -340,3 +351,12 @@ 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.

### Managed catalog and authentication tracing follow-up

Managed index verification validates the schema and configurable catalog table
with the adapter's identifier allowlist before SQL interpolation. Catalog rows
are trusted host maintenance receipts, not tenant inputs; runtime needs read
access only. Authentication exceptions now set ERROR span status and exception
type without status descriptions, exception messages, stack events or credentials.
Regression tests cover unsafe identifiers and content-free error spans.
3 changes: 3 additions & 0 deletions docs/md/stability.md
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ are the canonical import path:
fall through to the (slower) default serial implementations. Custom
adapters must implement `insert_if_absent` or callers hit
`NotImplementedError`.
- **Managed PostgreSQL.** `IndexSpec` and `ManagedSchemaError` are public.
`PostgresDB.index_spec` compiles descriptions; managed adapters verify integrity
without persistent DDL. Host lifecycle metadata is an integration contract.
- **Cache.** `create_cache`.
- **Graph context for inference.** `GraphContext.project_graph`,
`ProjectionRequest`, `ProjectionScope`, `ProjectionAccess`,
Expand Down
4 changes: 4 additions & 0 deletions jvspatial/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,10 @@
from .db import (
Database,
GraphBindingSummary,
IndexSpec,
InsertIfAbsentResult,
LiteralBindingFact,
ManagedSchemaError,
create_database,
)
from .db.transaction import Transaction
Expand Down Expand Up @@ -170,6 +172,8 @@
# API
"Server",
# Database & Cache
"IndexSpec",
"ManagedSchemaError",
"Database",
"Transaction",
"InsertIfAbsentResult",
Expand Down
21 changes: 21 additions & 0 deletions jvspatial/api/components/auth_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,6 +291,27 @@ async def _normalize_user(self, user: Any) -> Any:
return user

async def _authenticate_request(self, request: Request) -> Optional[Any]:
from jvspatial.observability.tracing import (
Status,
StatusCode,
_tracing_active,
get_tracer,
)

if not _tracing_active():
return await self._authenticate_request_impl(request)
# Never attach headers, tokens, request objects or exception content.
with get_tracer("jvspatial.auth").start_as_current_span(
"auth.authenticate", record_exception=False, set_status_on_exception=False
) as span:
try:
return await self._authenticate_request_impl(request)
except BaseException as exc:
span.set_attribute("error.type", type(exc).__name__)
span.set_status(Status(StatusCode.ERROR))
raise

async def _authenticate_request_impl(self, request: Request) -> Optional[Any]:
"""Authenticate the incoming request using multiple methods.

Attempts authentication in priority order:
Expand Down
4 changes: 4 additions & 0 deletions jvspatial/core/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -1619,6 +1619,10 @@ def _scoped(index_def: Dict[str, Any], extra: Dict[str, Any]) -> Dict[str, Any]:
**extra,
)
except Exception as e:
from jvspatial.db.indexes import ManagedSchemaError

if isinstance(e, ManagedSchemaError):
raise
# Log error but continue with other indexes
logger.warning(
f"Failed to create index for {entity_class.__name__} "
Expand Down
14 changes: 14 additions & 0 deletions jvspatial/core/entities/walker.py
Original file line number Diff line number Diff line change
Expand Up @@ -847,6 +847,20 @@ async def run(self: "Walker") -> List[Any]:
Returns:
List of all reported items
"""
from jvspatial.observability.tracing import _tracing_active, walker_span

if not _tracing_active():
return await self._run_traversal()
# Invocation/node identities and reported values are deliberately absent.
with walker_span(type(self).__name__) as span:
try:
return await self._run_traversal()
finally:
span.set_attribute("walker.step_count", self._protection.step_count)
span.set_attribute("walker.paused", self._paused)

async def _run_traversal(self: "Walker") -> List[Any]:
"""Execute the existing traversal with its original protection scope."""
# Initialize protection state once per traversal session.
# ``start_if_needed`` is idempotent so ``resume()`` does not reset
# the step / visit / timer counters (audit §2.2 / SPEC §6.3).
Expand Down
3 changes: 3 additions & 0 deletions jvspatial/db/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
unregister_database_type,
)
from .graph_bindings import GraphBindingSummary, LiteralBindingFact
from .indexes import IndexSpec, ManagedSchemaError
from .jsondb import JsonDB
from .manager import DatabaseManager, get_database_manager, set_database_manager
from .query import escape_regex
Expand Down Expand Up @@ -60,6 +61,8 @@
_POSTGRES_AVAILABLE = False

__all__ = [
"IndexSpec",
"ManagedSchemaError",
"Database",
"GraphBindingSummary",
"LiteralBindingFact",
Expand Down
Loading
Loading