diff --git a/CHANGELOG.md b/CHANGELOG.md index c08ad59..63108d6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/PRD.md b/PRD.md index b64908d..15bbcaa 100644 --- a/PRD.md +++ b/PRD.md @@ -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 diff --git a/SPEC.md b/SPEC.md index bcd2629..ee1df1f 100644 --- a/SPEC.md +++ b/SPEC.md @@ -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 @@ -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 @@ -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 diff --git a/docs/md/observability.md b/docs/md/observability.md index 71e3646..2fa5031 100644 --- a/docs/md/observability.md +++ b/docs/md/observability.md @@ -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. diff --git a/docs/md/postgres-guide.md b/docs/md/postgres-guide.md index cc4c491..e9a2ba1 100644 --- a/docs/md/postgres-guide.md +++ b/docs/md/postgres-guide.md @@ -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 @@ -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. diff --git a/docs/md/security-review.md b/docs/md/security-review.md index 965b69a..80c36c4 100644 --- a/docs/md/security-review.md +++ b/docs/md/security-review.md @@ -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: @@ -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. diff --git a/docs/md/stability.md b/docs/md/stability.md index 02c489d..02a4102 100644 --- a/docs/md/stability.md +++ b/docs/md/stability.md @@ -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`, diff --git a/jvspatial/__init__.py b/jvspatial/__init__.py index b0fb7e1..deb2067 100644 --- a/jvspatial/__init__.py +++ b/jvspatial/__init__.py @@ -90,8 +90,10 @@ from .db import ( Database, GraphBindingSummary, + IndexSpec, InsertIfAbsentResult, LiteralBindingFact, + ManagedSchemaError, create_database, ) from .db.transaction import Transaction @@ -170,6 +172,8 @@ # API "Server", # Database & Cache + "IndexSpec", + "ManagedSchemaError", "Database", "Transaction", "InsertIfAbsentResult", diff --git a/jvspatial/api/components/auth_middleware.py b/jvspatial/api/components/auth_middleware.py index 9418d2e..e8ab3aa 100644 --- a/jvspatial/api/components/auth_middleware.py +++ b/jvspatial/api/components/auth_middleware.py @@ -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: diff --git a/jvspatial/core/context.py b/jvspatial/core/context.py index 78c6ded..f544296 100644 --- a/jvspatial/core/context.py +++ b/jvspatial/core/context.py @@ -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__} " diff --git a/jvspatial/core/entities/walker.py b/jvspatial/core/entities/walker.py index 2e48cd7..f87b776 100644 --- a/jvspatial/core/entities/walker.py +++ b/jvspatial/core/entities/walker.py @@ -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). diff --git a/jvspatial/db/__init__.py b/jvspatial/db/__init__.py index d582b11..ef8a727 100644 --- a/jvspatial/db/__init__.py +++ b/jvspatial/db/__init__.py @@ -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 @@ -60,6 +61,8 @@ _POSTGRES_AVAILABLE = False __all__ = [ + "IndexSpec", + "ManagedSchemaError", "Database", "GraphBindingSummary", "LiteralBindingFact", diff --git a/jvspatial/db/_binary_text_keyset.py b/jvspatial/db/_binary_text_keyset.py index e0f6505..6aeedaf 100644 --- a/jvspatial/db/_binary_text_keyset.py +++ b/jvspatial/db/_binary_text_keyset.py @@ -25,6 +25,8 @@ 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 + if getattr(database, "index_creation", "auto") != "auto": + return # Only an automatic/provisioning adapter builds performance indexes. title, scope, malformed = _expressions(field, scope_field) schema, table = _safe_collection(database.schema_name), _safe_collection(collection) key = hashlib.sha256( diff --git a/jvspatial/db/_observable.py b/jvspatial/db/_observable.py index c1abaf0..eedb77a 100644 --- a/jvspatial/db/_observable.py +++ b/jvspatial/db/_observable.py @@ -120,6 +120,33 @@ async def _instrument( coro_factory: Callable[[], Awaitable[Any]], *, result_count_extractor: Optional[Callable[[Any], int]] = None, + ) -> Any: + from jvspatial.observability.tracing import _tracing_active, db_span + + if not _tracing_active(): + return await self._instrument_call( + op, + collection, + coro_factory, + result_count_extractor=result_count_extractor, + ) + with db_span(op, collection=collection, backend=self._backend) as span: + return await self._instrument_call( + op, + collection, + coro_factory, + result_count_extractor=result_count_extractor, + span=span, + ) + + async def _instrument_call( + self, + op: str, + collection: str, + coro_factory: Callable[[], Awaitable[Any]], + *, + result_count_extractor: Optional[Callable[[Any], int]] = None, + span: Any = None, ) -> Any: """Run ``coro_factory()`` while recording metrics and failure logs. @@ -148,6 +175,22 @@ async def _instrument( result_count = result_count_extractor(result) except Exception: result_count = None + if span is not None: + for key, value in (_query_execution.get() or {}).items(): + if key in {"execution_mode", "partial_pushdown", "scanned_rows"}: + span.set_attribute(f"db.{key}", value) + span.set_attribute("db.success", success) + if result_count is not None: + span.set_attribute("db.result_count", result_count) + for key, value in (_io_metrics.get() or {}).items(): + if key in { + "pool_wait_ms", + "driver_statements", + "driver_duration_ms", + "decoded_bytes", + "decoded_chars", + }: + span.set_attribute(f"db.{key}", value) try: self._emit( op=op, @@ -218,8 +261,11 @@ def _emit( for field in ( "pool_wait_ms", "driver_attempts", + "driver_statements", + "driver_duration_ms", "retry_count", "decoded_bytes", + "decoded_chars", ): if field in query_plan: self.metrics.record_value( diff --git a/jvspatial/db/indexes.py b/jvspatial/db/indexes.py new file mode 100644 index 0000000..6c988cc --- /dev/null +++ b/jvspatial/db/indexes.py @@ -0,0 +1,137 @@ +"""Portable index descriptions with a deterministic PostgreSQL DDL boundary. + +Descriptions are trusted schema inputs, never query- or tenant-supplied SQL. +Hosts own catalog approval and migrations; database adapters own compilation. +""" + +from __future__ import annotations + +import hashlib +import json +import re +from dataclasses import asdict, dataclass, field + +from jvspatial.exceptions import DatabaseError + + +class ManagedSchemaError(DatabaseError): + """A verify-only adapter needs an operator-provisioned schema object.""" + + +def identifier(value: str) -> str: + """Validate and quote a PostgreSQL storage identifier.""" + if not isinstance(value, str) or not re.fullmatch( + r"[A-Za-z_][A-Za-z0-9_]{0,62}", value + ): + raise ValueError("Invalid storage identifier") + return '"' + value + '"' + + +def _canonical_tokens(expression: str, *, ordering=False): + tokens = re.findall( + r"'(?:''|[^'])*'|\"(?:\"\"|[^\"])*\"|[A-Za-z_][A-Za-z0-9_]*|\d+(?:\.\d+)?|#>>|#>|->>|->|::|>=|<=|<>|!=|[^\s]", + expression, + ) + tokens = [t if t.startswith(("'", '"')) else t.lower() for t in tokens] + if ordering: + if tokens[-3:] == ["asc", "nulls", "last"]: + tokens = tokens[:-3] + elif tokens[-1:] == ["asc"]: + tokens = tokens[:-1] + elif tokens[-1:] == ["desc"]: + tokens += ["nulls", "first"] + return tokens + + +@dataclass(frozen=True) +class IndexSpec: + """A physical index, independent of installations and request execution. + + ``keys`` and ``predicate`` are adapter/compiler-produced expressions. Apps + must use a host's typed proposal interface, not construct these expressions. + Ownership and query references do not change physical equivalence. + """ + + logical_id: str + owner: str + table: str + keys: tuple[str, ...] + schema: str = "public" + method: str = "btree" + predicate: str = "" + unique: bool = False + required: bool = False + version: str = "1" + queries: tuple[str, ...] = field(default_factory=tuple) + justification: str = "" + + def __post_init__(self): + """Validate index identity, method, and trusted schema expressions.""" + identifier(self.schema) + identifier(self.table) + if self.method not in { + "btree", + "gin", + "gist", + "hash", + "brin", + "hnsw", + "ivfflat", + }: + raise ValueError("Invalid index method") + if not self.keys or (self.unique and self.method != "btree"): + raise ValueError("Invalid index keys or uniqueness") + for expression in (*self.keys, self.predicate): + if not isinstance(expression, str) or any( + t in expression for t in (";", "--", "/*", "\x00") + ): + raise ValueError("Unsafe schema expression") + if not self.logical_id or not self.owner: + raise ValueError("Index identity and owner are required") + + @property + def fingerprint(self) -> str: + """Return a deterministic digest of the physical index definition.""" + physical = { + k: getattr(self, k) + for k in ("schema", "table", "method", "keys", "predicate", "unique") + } + physical["keys"] = [ + _canonical_tokens(k, ordering=self.method == "btree") for k in self.keys + ] + physical["predicate"] = _canonical_tokens(self.predicate) + return hashlib.sha256( + json.dumps(physical, sort_keys=True, separators=(",", ":")).encode() + ).hexdigest() + + @property + def name(self) -> str: + """Return the bounded physical name derived from this index fingerprint.""" + return f"ix_{self.table[:20]}_{self.fingerprint[:24]}" + + def create_sql(self, *, concurrently: bool = True) -> str: + """Compile the index declaration into a PostgreSQL CREATE statement.""" + return ( + f"CREATE {'UNIQUE ' if self.unique else ''}INDEX " + f"{'CONCURRENTLY ' if concurrently else ''}{identifier(self.name)} ON " + f"{identifier(self.schema)}.{identifier(self.table)} USING {self.method} " + f"({', '.join(self.keys)})" + + (f" WHERE {self.predicate}" if self.predicate else "") + ) + + def to_dict(self) -> dict: + """Serialize the physical definition and ownership metadata.""" + return asdict(self) + + @classmethod + def from_dict(cls, value: dict) -> "IndexSpec": + """Restore a validated declaration from serialized metadata.""" + payload = dict(value) + payload["keys"] = tuple(payload["keys"]) + payload["queries"] = tuple(payload.get("queries", ())) + return cls(**payload) + + +def definition_digest(definition: str) -> str: + """Fingerprint PostgreSQL's own normalized catalog definition.""" + return hashlib.sha256(definition.encode()).hexdigest() diff --git a/jvspatial/db/postgres.py b/jvspatial/db/postgres.py index 5ce68e3..0809abb 100644 --- a/jvspatial/db/postgres.py +++ b/jvspatial/db/postgres.py @@ -385,6 +385,8 @@ def __init__( command_timeout: Optional[float] = None, schema_name: str = "public", gin_index: Optional[str] = None, + index_creation: Optional[str] = None, + index_catalog_table: Optional[str] = None, fallback_scan_limit: Optional[int] = None, ) -> None: """Initialize the Postgres adapter. @@ -412,11 +414,26 @@ def __init__( The GIN only serves containment-shaped predicates (``$all``); typed ``find()`` equality / range / sort use functional B-trees, so large deployments should turn it off. + index_creation: ``"auto"`` (compatible default), ``"constraints"``, + or ``"managed"``. + Also read from ``JVSPATIAL_POSTGRES_INDEX_CREATION``. Constraints + mode provisions only unique declarations and fixed collection + baseline indexes. It skips ordinary, sort-companion, whole-data + GIN, binary-text keyset and vector indexes, retaining existing + indexes. Managed mode verifies pre-provisioned storage without + persistent schema/index DDL. Use a separate explicitly configured + adapter to provision performance indexes. + index_catalog_table: Unqualified applied-index catalog table in + ``schema_name``. Reads ``JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE`` + when omitted; defaults to ``jvspatial_index_catalog``. Managed + verification requires ``fingerprint``, ``index_name`` and + ``definition_hash`` text columns maintained by the host. Raises: ImportError: ``asyncpg`` is not installed. ValueError: ``pooler_mode`` is not ``"session"`` or ``"transaction"``, - or ``gin_index`` is not ``"full"`` or ``"off"``. + or ``gin_index``, ``index_creation`` or ``index_catalog_table`` + is invalid. """ if asyncpg is None: # pragma: no cover raise ImportError( @@ -464,6 +481,26 @@ def __init__( f"gin_index must be 'full' or 'off', got {self.gin_index!r}" ) self._gin_off_warned = False + self._managed_verified_indexes: Set[str] = set() + self.index_creation = ( + ( + index_creation + if index_creation is not None + else env("JVSPATIAL_POSTGRES_INDEX_CREATION", default="auto") + ) + .strip() + .lower() + ) + if self.index_creation not in ("auto", "constraints", "managed"): + raise ValueError("index_creation must be auto, constraints or managed") + self.index_catalog_table = _safe_collection( + index_catalog_table + if index_catalog_table is not None + else env( + "JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE", + default="jvspatial_index_catalog", + ) + ) self._pool: Optional["Pool"] = None self._pool_lock = asyncio.Lock() @@ -613,17 +650,39 @@ async def _acquire_conn(self) -> AsyncIterator[Any]: waiting = time.monotonic() async with pool.acquire() as conn: _record_io_metric("pool_wait_ms", (time.monotonic() - waiting) * 1000) - if tenant_id is None: - yield conn - return - # SET LOCAL requires a transaction; wrap the user's work in - # one and commit on success. - async with conn.transaction(): - await conn.execute( - "SELECT set_config('app.tenant_id', $1, true)", - tenant_id, - ) - yield conn + # Query logger deliberately never reads query text or parameters. + # Asyncpg invokes sync loggers with call_soon; capture the current + # mutable observation holder now so late callbacks retain ownership. + from .database import _io_metrics + + io_metrics = _io_metrics.get() + + def observe_query(record): + if io_metrics is not None: + io_metrics["driver_statements"] = ( + io_metrics.get("driver_statements", 0) + 1 + ) + io_metrics["driver_duration_ms"] = ( + io_metrics.get("driver_duration_ms", 0) + record.elapsed * 1000 + ) + + if io_metrics is not None: + conn.add_query_logger(observe_query) + try: + if tenant_id is None: + yield conn + return + # SET LOCAL requires a transaction; wrap the user's work in + # one and commit on success. + async with conn.transaction(): + await conn.execute( + "SELECT set_config('app.tenant_id', $1, true)", + tenant_id, + ) + yield conn + finally: + if io_metrics is not None: + conn.remove_query_logger(observe_query) # ---- RLS install (C6) -------------------------------------------------- @@ -660,6 +719,12 @@ async def enable_rls( unset, returning empty string. The policy then compares to NULL / empty as appropriate. """ + if self.index_creation == "managed": + from .indexes import ManagedSchemaError + + raise ManagedSchemaError( + "Tenant policy changes require schema provisioning" + ) await self._bootstrap_collection(collection) col = _safe_collection(collection) schema = _safe_collection(self.schema_name) @@ -745,13 +810,21 @@ async def _create_collection_schema_on_connection( """ col = _safe_collection(collection) schema = _safe_collection(self.schema_name) + if self.index_creation == "managed": + from .indexes import ManagedSchemaError + + if not await conn.fetchval( + "SELECT to_regclass($1)", f"{self.schema_name}.{collection}" + ): + raise ManagedSchemaError("Managed collection is not provisioned") + return gin_name = _postgres_index_name(col, "data_gin") entity_name = _postgres_index_name(col, "entity_idx") tenant_name = _postgres_index_name(col, "tenant_idx") gin_sql = ( f"CREATE INDEX IF NOT EXISTS {gin_name} " f"ON {schema}.{col} USING GIN (data jsonb_path_ops);" - if self.gin_index == "full" + if self.gin_index == "full" and self.index_creation == "auto" else "" ) # An asyncio lock only coordinates callers sharing this instance. @@ -844,6 +917,13 @@ def _record_from_row(row: Any) -> Dict[str, Any]: if row is None: return None # type: ignore[return-value] data = row["data"] + if isinstance(data, str): + from .database import _record_io_metric + + # O(1) size evidence for JSON decoding; never stringify a record + # or expose its contents merely to measure it. This is characters, + # not wire bytes (which can differ for non-ASCII data). + _record_io_metric("decoded_chars", len(data)) # asyncpg returns jsonb as already-decoded Python types when the # default codec is in use; if a caller plugged in a non-decoding # codec, fall back to json.loads. @@ -1165,6 +1245,12 @@ async def install_graph_binding_projection( on this adapter instance for matching requests. Unmatched, invalidated and tenant-filtered reads retain the native query. """ + if self.index_creation == "managed": + from .indexes import ManagedSchemaError + + raise ManagedSchemaError( + "Projection installation requires a reviewed maintenance plan" + ) from ._binding_projection_postgres import BindingProjection, install projection = BindingProjection( @@ -1908,51 +1994,9 @@ async def bulk_save_detailed( # ---- index management -------------------------------------------------- - async def create_index( - self, - collection: str, - field_or_fields: Union[str, List[Tuple[str, int]]], - unique: bool = False, - **kwargs: Any, - ) -> None: - """Create a functional index on JSONB field paths or top-level columns. - - Field paths use dot notation (``"context.user.id"``) and index - ``(data #>> '{context,user,id}')``; ``entity`` / ``id`` / - ``tenant_id`` index the real columns the query translator compares - against. A descending key is ``DESC NULLS LAST`` — the order - ``find(sort=...)`` emits — so sort + limit can walk the index. - ``unique=True`` adds ``CREATE UNIQUE INDEX``. - - Keyword options: + def _describe_index(self, collection, field_or_fields, *, unique=False, **kwargs): + from .indexes import IndexSpec - * ``entity`` — the entity a per-class index serves (passed by - ``GraphContext.ensure_indexes``). The real ``entity`` column then - leads the key (``entity_leading=True``, default): every typed - ``find()`` filters on it, in a table shared by every class. Such an - index is named ``_entity__idx`` so sibling classes - declaring the same fields share it. ``partial_by_entity=True`` - instead restricts it to ``WHERE entity = ''`` - (``___idx``; smaller, one per class). - ``drop_legacy=True`` also drops the unscoped pre-0.0.18 - ``__idx`` / ``_uniq`` index it replaces. - Generated names stay within PostgreSQL's 63-byte identifier limit; - overlong compound names retain a stable digest and index suffix. - * ``fulltext=True`` — a GIN index over ``to_tsvector('simple', ...)`` - of the fields in order (``___fts``, scoped to - ``entity`` when given), matching - ``{"$text": {"$search": ..., "$fields": []}}``. - * ``index_partial_filter_expression`` — partial index predicate in - the supported Mongo-style dialect. Raw ``where=`` SQL is rejected. - * ``method`` — ``btree`` (default), ``hash``, ``gin``, ``gist``, ``brin``. - - An existing index of the same name defined by the pre-0.0.18 rules - (JSONB paths for top-level columns, ``DESC`` without ``NULLS LAST``) - or a B-tree with different stored key ordering is rebuilt under a - temporary name and swapped in. Nullable JSONB sort companions remain - separately named by their ordering signature. - """ - await self._bootstrap_collection(collection) col = _safe_collection(collection) schema = _safe_collection(self.schema_name) @@ -2062,9 +2106,225 @@ async def create_index( else: scope = "" index_name = _postgres_index_name(f"{col}_{scope}{field_names}", suffix) - unique_sql = "UNIQUE " if unique and not fulltext else "" body = f"ON {schema}.{col} USING {method} ({', '.join(keys)}){where_clause}" + spec = IndexSpec( + logical_id=index_name, + owner="jvspatial", + schema=self.schema_name, + table=collection, + keys=tuple(keys), + method=method, + predicate=" AND ".join(where_parts), + unique=bool(unique and not fulltext), + required=bool(unique and not fulltext), + ) + return { + "col": col, + "schema": schema, + "index_name": index_name, + "body": body, + "fields": fields, + "scope": scope, + "fulltext": fulltext, + "method": method, + "want_indoption": want_indoption, + "where_clause": where_clause, + "entity_leading": entity_leading, + "field_names": field_names, + "spec": spec, + } + + def index_spec( + self, collection, field_or_fields, *, unique=False, keyset=False, **kwargs + ): + """Compile a physical declaration without connecting or performing DDL. + + ``keyset`` selects the exact JSONB ordering used by native pagination, + including its deterministic ID tie-breaker. It is an explicit separate + requirement, never an automatically provisioned companion. + """ + from dataclasses import replace + + description = self._describe_index( + collection, field_or_fields, unique=unique, **kwargs + ) + spec = description["spec"] + if keyset: + from ._postgres_translate import translate_sort + from .database import _keyset_sort_fields + + if unique or spec.method != "btree": + raise ValueError( + "Keyset specifications require nonunique btree declarations" + ) + keys = tuple( + translate_sort([field]) + for field in _keyset_sort_fields(description["fields"]) + ) + if description["entity_leading"]: + keys = ("entity",) + keys + spec = replace(spec, keys=keys) + return spec + + def binary_text_keyset_specs(self, collection, *, field, scope_field, entity): + """Describe the three bounded Python-compatible text paging indexes.""" + from ._binary_text_keyset import _expressions + from .indexes import IndexSpec + + _safe_collection(collection) + if not _SAFE_IDENT_RE.fullmatch(entity): + raise ValueError("Invalid entity discriminator") + title, scope, malformed = _expressions(field, scope_field) + specs = [] + for direction in ("ASC", "DESC"): + specs.append( + IndexSpec( + "text-page:" + direction, + "jvspatial.pagination", + collection, + ( + scope, + f"{title} {direction} NULLS LAST", + f'id COLLATE "C" {direction}', + ), + schema=self.schema_name, + predicate=f"entity='{entity}' AND NOT {malformed}", + ) + ) + specs.append( + IndexSpec( + "text-page:malformed", + "jvspatial.pagination", + collection, + (scope,), + schema=self.schema_name, + predicate=f"entity='{entity}' AND {malformed}", + ) + ) + return specs + + async def verify_index_spec(self, spec): + """Check a required index against its applied definition, once per adapter.""" + from .indexes import ManagedSchemaError, definition_digest + + schema = _safe_collection(self.schema_name) + catalog_table = _safe_collection(self.index_catalog_table) + catalog_relation = f'"{schema}"."{catalog_table}"' + if spec.fingerprint in self._managed_verified_indexes: + return + pool = await self._ensure_pool() + async with pool.acquire() as conn: + if not await conn.fetchval("SELECT to_regclass($1)", catalog_relation): + raise ManagedSchemaError("Managed index catalog is not provisioned") + row = await conn.fetchrow( + f"SELECT c.definition_hash, pg_get_indexdef(i.indexrelid) AS definition, " + f"i.indisvalid, i.indisready FROM {catalog_relation} c " + "JOIN pg_namespace n ON n.nspname=$1 JOIN pg_class r ON r.relnamespace=n.oid AND r.relname=c.index_name " + "JOIN pg_index i ON i.indexrelid=r.oid WHERE c.fingerprint=$2", + schema, + spec.fingerprint, + ) + if ( + not row + or not row["indisvalid"] + or not row["indisready"] + or definition_digest(row["definition"]) != row["definition_hash"] + ): + raise ManagedSchemaError("Required managed index is missing or changed") + self._managed_verified_indexes.add(spec.fingerprint) + + async def create_index( + self, + collection: str, + field_or_fields: Union[str, List[Tuple[str, int]]], + unique: bool = False, + **kwargs: Any, + ) -> None: + """Create a functional index on JSONB field paths or top-level columns. + + Field paths use dot notation (``"context.user.id"``) and index + ``(data #>> '{context,user,id}')``; ``entity`` / ``id`` / + ``tenant_id`` index the real columns the query translator compares + against. A descending key is ``DESC NULLS LAST`` — the order + ``find(sort=...)`` emits — so sort + limit can walk the index. + ``unique=True`` adds ``CREATE UNIQUE INDEX``. + + Keyword options: + + * ``entity`` — the entity a per-class index serves (passed by + ``GraphContext.ensure_indexes``). The real ``entity`` column then + leads the key (``entity_leading=True``, default): every typed + ``find()`` filters on it, in a table shared by every class. Such an + index is named ``_entity__idx`` so sibling classes + declaring the same fields share it. ``partial_by_entity=True`` + instead restricts it to ``WHERE entity = ''`` + (``___idx``; smaller, one per class). + ``drop_legacy=True`` also drops the unscoped pre-0.0.18 + ``__idx`` / ``_uniq`` index it replaces. + Generated names stay within PostgreSQL's 63-byte identifier limit; + overlong compound names retain a stable digest and index suffix. + * ``fulltext=True`` — a GIN index over ``to_tsvector('simple', ...)`` + of the fields in order (``___fts``, scoped to + ``entity`` when given), matching + ``{"$text": {"$search": ..., "$fields": []}}``. + * ``index_partial_filter_expression`` — partial index predicate in + the supported Mongo-style dialect. Raw ``where=`` SQL is rejected. + * ``method`` — ``btree`` (default), ``hash``, ``gin``, ``gist``, ``brin``. + + An existing index of the same name defined by the pre-0.0.18 rules + (JSONB paths for top-level columns, ``DESC`` without ``NULLS LAST``) + or a B-tree with different stored key ordering is rebuilt under a + temporary name and swapped in. Nullable JSONB sort companions remain + separately named by their ordering signature. + + In ``index_creation="constraints"`` mode non-unique declarations are + validated but do not run DDL. Unique indexes retain their enforcement + and repair behavior, without additional performance sort companions. + """ + description = self._describe_index( + collection, field_or_fields, unique=unique, **kwargs + ) + if self.index_creation == "managed": + if unique: + await self.verify_index_spec(description["spec"]) + return + ( + col, + schema, + index_name, + body, + fields, + scope, + fulltext, + method, + want_indoption, + ) = ( + description[key] + for key in ( + "col", + "schema", + "index_name", + "body", + "fields", + "scope", + "fulltext", + "method", + "want_indoption", + ) + ) + unique_sql = "UNIQUE " if unique and not fulltext else "" + where_clause = description["where_clause"] + entity_leading = description["entity_leading"] + field_names = description["field_names"] + + # Managed deployments provision performance indexes deliberately. Keep + # unique enforcement live; skipping ensure_indexes at the graph layer + # would also skip newly declared uniqueness constraints. + if self.index_creation == "constraints" and not (unique and not fulltext): + return + await self._bootstrap_collection(collection) + pool = await self._ensure_pool() async with pool.acquire() as conn: # Serialize same-name index creation/repair across cold workers. @@ -2075,7 +2335,7 @@ async def create_index( schema, f"index:{index_name}", ) - if not fulltext and method == "btree": + if self.index_creation == "auto" and not fulltext and method == "btree": from .database import _keyset_sort_fields sort_keys = translate_sort(_keyset_sort_fields(fields)) @@ -2360,6 +2620,18 @@ async def enable_vector_column( async with self._pool_lock: pool = await self._ensure_pool() async with pool.acquire() as conn: + if self.index_creation == "managed": + from .indexes import ManagedSchemaError + + actual = await conn.fetchval( + "SELECT format_type(a.atttypid,a.atttypmod) FROM pg_attribute a WHERE a.attrelid=to_regclass($1) AND a.attname=$2 AND NOT a.attisdropped", + f"{self.schema_name}.{collection}", + field_name, + ) + if actual != f"vector({dim})": + raise ManagedSchemaError("Managed vector column is not provisioned") + self._vector_columns.setdefault(collection, {})[field_name] = dim + return # Install extension if not present (no-op when already installed). await conn.execute("CREATE EXTENSION IF NOT EXISTS vector") # Add the column. ``ADD COLUMN IF NOT EXISTS`` is PG 9.6+; we @@ -2377,10 +2649,11 @@ async def enable_vector_column( params_clause = f" WITH (m = {m}, ef_construction = {ef_construction})" else: params_clause = "" - await conn.execute( - f"CREATE INDEX IF NOT EXISTS {index_name} ON {schema}.{col} " - f"USING {index} ({field_name} {ops}){params_clause}" - ) + if self.index_creation == "auto": + await conn.execute( + f"CREATE INDEX IF NOT EXISTS {index_name} ON {schema}.{col} " + f"USING {index} ({field_name} {ops}){params_clause}" + ) # Remember the column for save-path extraction. Mapping is # collection -> { field_name: dim }. self._vector_columns.setdefault(collection, {})[field_name] = dim diff --git a/jvspatial/env_adapter.py b/jvspatial/env_adapter.py index 33e6a4e..7652f57 100644 --- a/jvspatial/env_adapter.py +++ b/jvspatial/env_adapter.py @@ -269,6 +269,8 @@ def server_config_overrides_from_env() -> Dict[str, Any]: "JVSPATIAL_POSTGRES_MAX_POOL_SIZE", "JVSPATIAL_POSTGRES_POOLER_MODE", "JVSPATIAL_POSTGRES_COMMAND_TIMEOUT", + "JVSPATIAL_POSTGRES_INDEX_CREATION", + "JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE", "JVSPATIAL_DYNAMODB_TABLE_NAME", "JVSPATIAL_DYNAMODB_REGION", "JVSPATIAL_DYNAMODB_ENDPOINT_URL", diff --git a/jvspatial/observability/tracing.py b/jvspatial/observability/tracing.py index 969c218..65b20aa 100644 --- a/jvspatial/observability/tracing.py +++ b/jvspatial/observability/tracing.py @@ -90,6 +90,16 @@ def is_tracing_available() -> bool: return _OTEL_AVAILABLE +def _tracing_active() -> bool: + """Avoid allocating proxy spans when the host has no recording provider.""" + if not _OTEL_AVAILABLE: + return False + return not isinstance( + _otel_trace.get_tracer_provider(), + (_otel_trace.NoOpTracerProvider, _otel_trace.ProxyTracerProvider), + ) + + def get_tracer(name: str = "jvspatial") -> Any: """Return an OTel ``Tracer`` for emitting spans. @@ -188,6 +198,8 @@ def db_span( with tracer.start_as_current_span( span_name, kind=SpanKind.CLIENT if _OTEL_AVAILABLE else None, + record_exception=False, + set_status_on_exception=False, ) as span: if backend: span.set_attribute("db.system", backend) @@ -196,11 +208,9 @@ def db_span( span.set_attribute("db.collection.name", collection) try: yield span - except Exception as exc: - span.record_exception(exc) - span.set_status( - Status(StatusCode.ERROR, str(exc)) if _OTEL_AVAILABLE else None - ) + except BaseException as exc: + span.set_attribute("error.type", type(exc).__name__) + span.set_status(Status(StatusCode.ERROR) if _OTEL_AVAILABLE else None) raise @@ -233,6 +243,8 @@ def walker_span( with tracer.start_as_current_span( span_name, kind=SpanKind.INTERNAL if _OTEL_AVAILABLE else None, + record_exception=False, + set_status_on_exception=False, ) as span: span.set_attribute("walker.class", walker_class) if walker_id: @@ -241,11 +253,9 @@ def walker_span( span.set_attribute("walker.entry_node", entry_node_id) try: yield span - except Exception as exc: - span.record_exception(exc) - span.set_status( - Status(StatusCode.ERROR, str(exc)) if _OTEL_AVAILABLE else None - ) + except BaseException as exc: + span.set_attribute("error.type", type(exc).__name__) + span.set_status(Status(StatusCode.ERROR) if _OTEL_AVAILABLE else None) raise @@ -273,16 +283,16 @@ def http_span( with tracer.start_as_current_span( span_name, kind=SpanKind.SERVER if _OTEL_AVAILABLE else None, + record_exception=False, + set_status_on_exception=False, ) as span: span.set_attribute("http.method", method) span.set_attribute("http.route", path) try: yield span - except Exception as exc: - span.record_exception(exc) - span.set_status( - Status(StatusCode.ERROR, str(exc)) if _OTEL_AVAILABLE else None - ) + except BaseException as exc: + span.set_attribute("error.type", type(exc).__name__) + span.set_status(Status(StatusCode.ERROR) if _OTEL_AVAILABLE else None) raise diff --git a/tests/db/test_postgres_index_policy.py b/tests/db/test_postgres_index_policy.py new file mode 100644 index 0000000..312f18f --- /dev/null +++ b/tests/db/test_postgres_index_policy.py @@ -0,0 +1,287 @@ +"""Managed index creation preserves constraints without growing performance DDL.""" + +import os +import uuid +from unittest.mock import AsyncMock, MagicMock + +import pytest + +asyncpg = pytest.importorskip("asyncpg") + +from jvspatial.db.postgres import PostgresDB + + +def test_policy_defaults_and_explicit_override(monkeypatch): + """Keep compatible defaults while allowing explicit policy selection.""" + monkeypatch.delenv("JVSPATIAL_POSTGRES_INDEX_CREATION", raising=False) + assert PostgresDB().index_creation == "auto" + monkeypatch.setenv("JVSPATIAL_POSTGRES_INDEX_CREATION", "constraints") + assert PostgresDB().index_creation == "constraints" + assert PostgresDB(index_creation="auto").index_creation == "auto" + + +@pytest.mark.parametrize("value", ["off", "false", "unknown", ""]) +def test_invalid_explicit_policy_is_rejected(value): + """Reject misspelled policies rather than silently enabling DDL.""" + with pytest.raises(ValueError, match="index_creation"): + PostgresDB(index_creation=value) + + +def test_catalog_defaults_env_and_explicit_override(monkeypatch): + """Select a neutral catalog with constructor precedence over environment.""" + monkeypatch.delenv("JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE", raising=False) + assert PostgresDB().index_catalog_table == "jvspatial_index_catalog" + monkeypatch.setenv("JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE", "host_index_catalog") + assert PostgresDB().index_catalog_table == "host_index_catalog" + assert ( + PostgresDB(index_catalog_table="other_catalog").index_catalog_table + == "other_catalog" + ) + monkeypatch.setenv("JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE", "") + assert PostgresDB().index_catalog_table == "jvspatial_index_catalog" + with pytest.raises(ValueError): + PostgresDB(index_catalog_table="") + + +@pytest.mark.parametrize("name", ["a.b", 'bad"name', "bad;name", "x" * 64]) +def test_invalid_catalog_identifiers_are_rejected(monkeypatch, name): + """Reject catalog names that cannot safely appear in SQL identifiers.""" + with pytest.raises(ValueError): + PostgresDB(index_catalog_table=name) + monkeypatch.setenv("JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE", name) + with pytest.raises(ValueError): + PostgresDB() + + +async def test_managed_verification_validates_schema_before_acquiring_connection(): + """Validate schema names before opening a connection or consulting receipts.""" + from jvspatial import IndexSpec + + db = PostgresDB(schema_name='unsafe";schema', index_creation="managed") + db._ensure_pool = AsyncMock() + with pytest.raises(ValueError): + await db.verify_index_spec(IndexSpec("item:id", "test", "object", ("id",))) + db._ensure_pool.assert_not_awaited() + + +@pytest.mark.parametrize("mode", ["constraints", "managed"]) +async def test_text_keyset_performance_indexes_do_not_acquire_connections(mode): + """Performance helpers must honor both restricted index policies.""" + db = PostgresDB(index_creation=mode) + db._bootstrap_collection = AsyncMock() + db._ensure_pool = AsyncMock() + await db.create_binary_text_keyset_indexes( + "node", field="context.title", scope_field="context.parent", entity="Record" + ) + db._bootstrap_collection.assert_not_awaited() + db._ensure_pool.assert_not_awaited() + + +async def test_performance_declarations_do_not_acquire_connections(): + """Skip nonunique declarations without touching database connections.""" + db = PostgresDB(index_creation="constraints") + db._bootstrap_collection = AsyncMock() + db._ensure_pool = AsyncMock() + await db.create_index("object", "context.description") + await db.create_index("object", "context.description", fulltext=True, unique=True) + db._bootstrap_collection.assert_not_awaited() + db._ensure_pool.assert_not_awaited() + with pytest.raises(ValueError): + await db.create_index("unsafe;collection", "context.description") + + +async def test_vector_storage_can_be_prepared_without_an_automatic_index(): + """Keep required vector storage separate from optional search indexes.""" + db = PostgresDB(index_creation="constraints") + db._bootstrap_collection = AsyncMock() + conn = AsyncMock() + pool = MagicMock() + pool.acquire.return_value.__aenter__.return_value = conn + db._ensure_pool = AsyncMock(return_value=pool) + await db.enable_vector_column("node", "embedding", dim=3) + sql = [call.args[0] for call in conn.execute.await_args_list] + assert any("ADD COLUMN" in statement for statement in sql) + assert not any("CREATE INDEX" in statement for statement in sql) + assert db._vector_columns == {"node": {"embedding": 3}} + + +@pytest.fixture +async def managed_pg(): + """Isolate live policy checks within a disposable schema.""" + dsn = os.getenv("JVSPATIAL_POSTGRES_TEST_DSN") + if not dsn: + pytest.skip("Set JVSPATIAL_POSTGRES_TEST_DSN to a disposable PostgreSQL") + admin = await asyncpg.connect(dsn) + schema = "test_index_policy_" + uuid.uuid4().hex + await admin.execute(f"CREATE SCHEMA {schema}") + db = PostgresDB(dsn=dsn, schema_name=schema, index_creation="constraints") + try: + yield db, admin, schema + finally: + await db.close() + await admin.execute(f"DROP SCHEMA {schema} CASCADE") + await admin.close() + + +async def _indexes(admin, schema): + return await admin.fetch( + "SELECT indexname, indexdef FROM pg_indexes WHERE schemaname=$1 " + "ORDER BY indexname", + schema, + ) + + +@pytest.mark.asyncio(loop_scope="module") +async def test_new_declarations_do_not_grow_indexes_but_uniqueness_survives(managed_pg): + """Retain baseline indexes and unique enforcement without performance DDL.""" + db, admin, schema = managed_pg + await db.save("object", {"id": "a", "entity": "Item", "context": {"key": "same"}}) + baseline = await _indexes(admin, schema) + assert len(baseline) == 3 # primary key and fixed entity/tenant baseline + assert not any("USING gin" in row["indexdef"] for row in baseline) + for i in range(25): + await db.create_index("object", f"context.field_{i}", entity="Item") + assert await _indexes(admin, schema) == baseline + + await db.create_index("object", "context.key", entity="Item", unique=True) + constrained = await _indexes(admin, schema) + assert len(constrained) == len(baseline) + 1 + assert not any("_sort_" in row["indexname"] for row in constrained) + with pytest.raises(asyncpg.UniqueViolationError): + await db.save( + "object", {"id": "b", "entity": "Item", "context": {"key": "same"}} + ) + assert await db.get("object", "a") is not None + assert await db.get("object", "b") is None + + +@pytest.mark.asyncio(loop_scope="module") +async def test_existing_indexes_remain_and_explicit_provisioning_still_works( + managed_pg, +): + """A restricted serving adapter must retain maintenance-provisioned indexes.""" + db, admin, schema = managed_pg + provisioner = PostgresDB(dsn=db.dsn, schema_name=schema, index_creation="auto") + try: + await provisioner.create_index( + "object", "context.created_at", entity="Item", partial_by_entity=True + ) + finally: + await provisioner.close() + before = await _indexes(admin, schema) + assert any("WHERE" in row["indexdef"] for row in before) + await db.create_index("object", "context.other", entity="Other") + await db.save("object", {"id": "a", "entity": "Item", "context": {}}) + assert await _indexes(admin, schema) == before + + +@pytest.mark.asyncio(loop_scope="module") +async def test_failed_unique_provision_does_not_modify_existing_indexes(managed_pg): + """Duplicate-key failures must leave the previous catalog intact.""" + db, admin, schema = managed_pg + for key in ("a", "b"): + await db.save( + "object", {"id": key, "entity": "Item", "context": {"key": "same"}} + ) + before = await _indexes(admin, schema) + with pytest.raises(asyncpg.UniqueViolationError): + await db.create_index("object", "context.key", entity="Item", unique=True) + assert await _indexes(admin, schema) == before + + +@pytest.mark.parametrize("catalog_table", ["jvspatial_index_catalog", "HostCatalog"]) +@pytest.mark.asyncio(loop_scope="module") +async def test_managed_verification_uses_host_catalog_and_checks_definition( + managed_pg, catalog_table +): + """Verify default and custom receipts against real PostgreSQL definitions.""" + from jvspatial import IndexSpec, ManagedSchemaError + from jvspatial.db.indexes import definition_digest + + provisioner, admin, schema = managed_pg + await provisioner.save("object", {"id": "a", "entity": "Item", "context": {}}) + spec = IndexSpec( + "item:key", + "test", + "object", + ("(data #>> '{context,key}')",), + schema=schema, + unique=True, + required=True, + ) + db = PostgresDB( + dsn=provisioner.dsn, + schema_name=schema, + index_creation="managed", + index_catalog_table=catalog_table, + ) + try: + with pytest.raises(ManagedSchemaError, match="catalog"): + await db.verify_index_spec(spec) + await admin.execute( + f'CREATE TABLE "{schema}"."{catalog_table}" ' + "(fingerprint text PRIMARY KEY, index_name text NOT NULL, definition_hash text NOT NULL)" + ) + await admin.execute(spec.create_sql()) + definition = await admin.fetchval( + "SELECT pg_get_indexdef(to_regclass($1))", f'"{schema}"."{spec.name}"' + ) + await admin.execute( + f'INSERT INTO "{schema}"."{catalog_table}" VALUES ($1,$2,$3)', + spec.fingerprint, + spec.name, + "incorrect-hash", + ) + with pytest.raises(ManagedSchemaError, match="missing or changed"): + await db.verify_index_spec(spec) + await admin.execute( + f'UPDATE "{schema}"."{catalog_table}" SET definition_hash=$1', + definition_digest(definition), + ) + before = await _indexes(admin, schema) + await db.verify_index_spec(spec) + assert await _indexes(admin, schema) == before + db._managed_verified_indexes.clear() + await admin.execute(f'DROP INDEX "{schema}"."{spec.name}"') + with pytest.raises(ManagedSchemaError, match="missing or changed"): + await db.verify_index_spec(spec) + finally: + await db.close() + + +def test_managed_fingerprints_preserve_physical_semantics(): + """Canonical identities must retain ordering, collation and expression meaning.""" + from dataclasses import replace + + from jvspatial import IndexSpec + + spec = IndexSpec("a", "owner", "object", ("id ASC NULLS LAST",)) + assert ( + spec.fingerprint + == replace(spec, logical_id="b", owner="other", keys=("id",)).fingerprint + ) + assert spec.fingerprint != replace(spec, keys=("id DESC NULLS LAST",)).fingerprint + assert spec.fingerprint != replace(spec, keys=('id COLLATE "C"',)).fingerprint + assert len(spec.name.encode()) <= 63 + assert replace(spec, keys=("lower(id)",)).fingerprint != spec.fingerprint + assert ( + replace(spec, predicate="entity='a b'").fingerprint + != replace(spec, predicate="entity='ab'").fingerprint + ) + + +async def test_managed_helpers_never_provision_optional_storage(): + """Managed helpers verify or refuse storage changes without index DDL.""" + from jvspatial import ManagedSchemaError + + db = PostgresDB(index_creation="managed") + db._bootstrap_collection = AsyncMock() + db._ensure_pool = AsyncMock() + await db.create_index("object", "context.anything") + await db.create_binary_text_keyset_indexes( + "node", field="context.title", scope_field="context.track_id", entity="Entry" + ) + db._ensure_pool.assert_not_awaited() + with pytest.raises(ManagedSchemaError): + await db.enable_rls("node") + db._bootstrap_collection.assert_not_awaited() diff --git a/tests/db/test_postgres_integration.py b/tests/db/test_postgres_integration.py index fbaab19..415e9a9 100644 --- a/tests/db/test_postgres_integration.py +++ b/tests/db/test_postgres_integration.py @@ -928,3 +928,43 @@ async def test_node_and_edge_commit_together(self, pg_db: "PostgresDB") -> None: assert note_id in nodes edges = await pg_db.find("edge", {}) assert len(edges) == 1 + + +async def test_observed_driver_work_is_numeric_and_loggers_are_removed(pg_db): + from jvspatial.db._observable import ObservableDatabase + from jvspatial.db.database import _io_metrics + + class Recorder: + def __init__(self): + self.values = [] + + def record_value(self, name, value, **labels): + self.values.append((name, value)) + + def record_duration(self, *args, **kwargs): + pass + + def increment_counter(self, *args, **kwargs): + pass + + recorder = Recorder() + observed = ObservableDatabase(pg_db, metrics=recorder) + await observed.save( + "node", {"id": "observed-record", "entity": "Record", "context": {}} + ) + recorder.values.clear() + assert await observed.find("node", {"id": "observed-record"}) + numeric = dict(recorder.values) + assert numeric["jvspatial.db.query.driver_statements"] >= 1 + assert numeric["jvspatial.db.query.driver_duration_ms"] >= 0 + assert numeric["jvspatial.db.query.pool_wait_ms"] >= 0 + assert numeric["jvspatial.db.query.decoded_chars"] > 0 + token = _io_metrics.set({}) + try: + with pytest.raises(asyncio.CancelledError): + async with pg_db._acquire_conn(): + raise asyncio.CancelledError + finally: + _io_metrics.reset(token) + async with pg_db._acquire_conn() as connection: + assert not connection._con._query_loggers diff --git a/tests/observability/test_database_spans.py b/tests/observability/test_database_spans.py new file mode 100644 index 0000000..b039aff --- /dev/null +++ b/tests/observability/test_database_spans.py @@ -0,0 +1,146 @@ +"""Database observations expose timing, never query parameters or errors.""" + +import pytest + + +@pytest.mark.asyncio +async def test_observed_database_spans_are_content_free(tmp_path, monkeypatch): + """Trace operation outcomes without query values or exception content.""" + pytest.importorskip("opentelemetry.sdk.trace") + from opentelemetry import trace + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import SimpleSpanProcessor + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) + + from jvspatial.db import create_database + from jvspatial.observability import tracing + + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + monkeypatch.setattr(trace, "_TRACER_PROVIDER", provider) + monkeypatch.setattr(tracing, "get_tracer", lambda name: provider.get_tracer(name)) + database = create_database("json", base_path=str(tmp_path), observe=True) + await database.find("node", {"context.title": "private-query-value"}) + + async def fail(): + raise ValueError("private-query-value") + + with pytest.raises(ValueError): + await database._instrument("find", "node", fail) + spans = exporter.get_finished_spans() + assert len(spans) == 2 + assert spans[0].attributes["db.success"] is True + assert spans[1].attributes["error.type"] == "ValueError" + assert not spans[1].events + assert "private-query-value" not in str( + [(s.attributes, s.events, s.status.description) for s in spans] + ) + provider.shutdown() + + +@pytest.mark.asyncio +async def test_unconfigured_tracing_keeps_metrics_without_proxy_spans( + tmp_path, monkeypatch +): + """Skip proxy spans when the host has not installed a tracer provider.""" + trace = pytest.importorskip("opentelemetry.trace") + + from jvspatial.db import create_database + from jvspatial.observability import tracing + + monkeypatch.setattr(trace, "_TRACER_PROVIDER", trace.NoOpTracerProvider()) + + def unexpected_tracer(*args: object, **kwargs): + raise AssertionError("No SDK should require no proxy span allocation") + + monkeypatch.setattr(tracing, "get_tracer", unexpected_tracer) + database = create_database("json", base_path=str(tmp_path), observe=True) + assert await database.find("node", {}) == [] + + +@pytest.mark.asyncio +async def test_walker_run_traces_counts_without_reports_or_exception_content( + monkeypatch, +): + """Trace bounded traversal counts while keeping reports and errors private.""" + pytest.importorskip("opentelemetry.sdk.trace") + from opentelemetry import trace + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import SimpleSpanProcessor + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) + + from jvspatial.core import Walker + + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + monkeypatch.setattr(trace, "_TRACER_PROVIDER", provider) + walker = Walker() + assert await walker.run() == [] + + async def fail(self): + raise ValueError("private-report-value") + + monkeypatch.setattr(Walker, "_run_traversal", fail) + with pytest.raises(ValueError): + await walker.run() + spans = exporter.get_finished_spans() + assert len(spans) == 2 + assert spans[0].attributes["walker.step_count"] == 0 + assert spans[1].attributes["error.type"] == "ValueError" + assert all(not s.events for s in spans) + assert "private-report-value" not in str( + [(s.attributes, s.status.description) for s in spans] + ) + assert all( + "walker.id" not in s.attributes and "walker.entry_node" not in s.attributes + for s in spans + ) + provider.shutdown() + + +@pytest.mark.asyncio +async def test_authentication_span_marks_errors_without_exception_content(monkeypatch): + """Authentication failures must set ERROR status without sensitive details.""" + pytest.importorskip("opentelemetry.sdk.trace") + from unittest.mock import MagicMock + + from opentelemetry import trace + from opentelemetry.sdk.trace import TracerProvider + from opentelemetry.sdk.trace.export import SimpleSpanProcessor + from opentelemetry.sdk.trace.export.in_memory_span_exporter import ( + InMemorySpanExporter, + ) + from starlette.requests import Request + + from jvspatial.api.auth.config import AuthConfig + from jvspatial.api.components.auth_middleware import AuthenticationMiddleware + + exporter = InMemorySpanExporter() + provider = TracerProvider() + provider.add_span_processor(SimpleSpanProcessor(exporter)) + monkeypatch.setattr(trace, "_TRACER_PROVIDER", provider) + middleware = AuthenticationMiddleware(MagicMock(), AuthConfig(), server=MagicMock()) + + async def fail(request): + raise ValueError("private-authentication-value") + + monkeypatch.setattr(middleware, "_authenticate_request_impl", fail) + try: + with pytest.raises(ValueError): + await middleware._authenticate_request(Request({"type": "http"})) + (span,) = exporter.get_finished_spans() + assert span.name == "auth.authenticate" + assert span.attributes["error.type"] == "ValueError" + assert span.status.status_code.name == "ERROR" + assert not span.events + assert "private-authentication-value" not in str( + (span.attributes, span.events, span.status.description) + ) + finally: + provider.shutdown() diff --git a/tests/test_env_adapter_postgres.py b/tests/test_env_adapter_postgres.py index faae296..e9a5414 100644 --- a/tests/test_env_adapter_postgres.py +++ b/tests/test_env_adapter_postgres.py @@ -24,6 +24,7 @@ def _clear_postgres_env(monkeypatch: pytest.MonkeyPatch) -> None: def test_postgres_env_maps_into_database_group( monkeypatch: pytest.MonkeyPatch, ) -> None: + """Expose PostgreSQL connection settings through the database config group.""" monkeypatch.setenv("JVSPATIAL_DB_TYPE", "postgres") monkeypatch.setenv("JVSPATIAL_POSTGRES_DSN", "postgresql://u:p@host:5432/db") monkeypatch.setenv("JVSPATIAL_POSTGRES_MIN_POOL_SIZE", "1") @@ -40,6 +41,7 @@ def test_postgres_env_maps_into_database_group( def test_postgres_keys_absent_when_unset(monkeypatch: pytest.MonkeyPatch) -> None: + """Leave PostgreSQL options unset for other adapter configurations.""" monkeypatch.setenv("JVSPATIAL_DB_TYPE", "json") db = server_config_overrides_from_env().get("database", {}) @@ -51,3 +53,10 @@ def test_postgres_keys_absent_when_unset(monkeypatch: pytest.MonkeyPatch) -> Non "postgres_pooler_mode", ): assert key not in db + + +def test_managed_catalog_env_is_recognized_in_strict_mode(monkeypatch): + """Recognize the adapter's catalog option under strict environment validation.""" + monkeypatch.setenv("JVSPATIAL_STRICT_ENV_ALLOWLIST", "true") + monkeypatch.setenv("JVSPATIAL_POSTGRES_INDEX_CATALOG_TABLE", "host_catalog") + server_config_overrides_from_env()