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 ``