diff --git a/README.md b/README.md index 421dcf4..84fe362 100644 --- a/README.md +++ b/README.md @@ -58,12 +58,42 @@ failure tests. Each database test owns a unique schema. ## Population indexes -`ddp_lib.population_indexes` provides the index identity, restoration and ANALYZE -helpers used by Core API and Sync. Callers supply their population document and -connector factory; the module does not import either service's application code. -PostgreSQL operations require psycopg2 in the consuming service. Importing the -module and parsing index identities do not require the database driver. +Core API and Sync use `ddp_lib.dataset_indexes`, `secondary_indexes`, +`index_metadata` and `index_hooks` to save and restore dataset indexes. +PostgreSQL catalog and session helpers live in `ddp_lib.postgres_indexes`. +`population_indexes` is only for older identity helpers. + +Import `IndexCreationMode` from `ddp_lib.enums`. Pass the string value, +not the enum member: + +`DatasetIndexes.reconcile(target, mode=IndexCreationMode.ONLINE.value)` + +This is the default. Ordinary tables and materialized views use +`CREATE INDEX CONCURRENTLY`. + +After the data job commits, call +`reconcile(target, mode=IndexCreationMode.POST_LOAD.value)`. +That uses a normal `CREATE INDEX` and can block writes on the table. +Use it only in a maintenance window. Post-load does not create a +checkpoint; it fails if none exists. + +`repair(target)` uses post-load only when a committed checkpoint is +already there. Manual repair without one stays online. An unfinished +data job must finish first. Online CREATE still uses `CONCURRENTLY` +even if an older checkpoint exists. + +Partitioned parent tables always use ordinary DDL. Their child indexes +must be valid and ready. DROP and ownership rules are the same in both +modes. + +Each connection, including one you pass in, sets `INDEX_LOCK_TIMEOUT` +(default `5s`) and `INDEX_STATEMENT_TIMEOUT` (default `30min`) before +DDL. Use PostgreSQL duration syntax. A timeout keeps the saved request +and does not mark the data job as successful. Run `python -m unittest discover -s tests -p test_population_indexes.py -v` for the identity contracts. Core's `ddp-sync/tests/test_population_indexes.py` covers the database lifecycle through both API and Sync. +Run `python -m unittest discover -s tests -p test_index_creation_modes.py -v` +with `QUEUE_TEST_POSTGRES_DSN` and `QUEUE_TEST_MONGO_URI` pointing to disposable +databases for I04 old-snapshot, invalid-owned-index, mode and timeout acceptance. diff --git a/ddp_lib/dataset_indexes.py b/ddp_lib/dataset_indexes.py new file mode 100644 index 0000000..a25d1b4 --- /dev/null +++ b/ddp_lib/dataset_indexes.py @@ -0,0 +1,430 @@ +"""Client-neutral target registry and lifecycle integration for Core datasets.""" +from contextlib import contextmanager +from dataclasses import dataclass +from hashlib import sha256 +import json +import re + +from ddp_lib import secondary_indexes as lifecycle +from ddp_lib.enums import IndexCreationMode +from ddp_lib.index_metadata import save_intent, delete_intent, IndexConflict +from ddp_lib.index_sql import parse_index, quote +from ddp_lib.postgres_indexes import advisory_lock, dataset_session, inspect_index + +KINDS = {'REFERENCE': 'references', 'POPULATION': 'populations', 'CLEANED_TABLE': 'cleaned_tables'} +DEPENDENCIES = {'tables_ids': 'REFERENCE', 'population_ids': 'POPULATION', 'cleaned_table_ids': 'CLEANED_TABLE'} + + +@dataclass +class Dataset: + kind: str + collection: object + document: dict + schema: str + table: str + + @property + def id(self): + return self.document['_id'] + + +def source_entries(dataset, physical=()): + """Turn a reference table's saved index list into indexes DDP should keep. + + The name can change. The identity is the column list, in order, plus unique or not. + An older index can be kept only when it has the same columns and is not a secondary index. + An older index without a DDP stamp still needs an explicit adoption. + """ + # Populations and cleaned tables do not use this list. + if dataset.kind != "REFERENCE": + return [] + policies = dataset.document.get("source_indexes") + if policies is None: + policies = [] + if not isinstance(policies, list): + raise ValueError("Source index policy must be a list; review source metadata") + candidates, names = {}, {} + # Names already saved as secondary indexes. A source index must not reuse one. + excluded = {e["index_name"] for e in dataset.document.get("secondary_indexes", [])} + for policy in policies: + if not isinstance(policy, dict): + raise ValueError("Source index definition must be an object") + # source_idxtype only records the old Informix index type. It is not used here. + unsupported = set(policy) - { + "name", + "columns", + "unique", + "primary", + "source_idxtype", + } + if unsupported: + raise ValueError( + "Unsupported source index fields: " + ", ".join(sorted(unsupported)) + ) + if any( + key in policy and not isinstance(policy[key], bool) + for key in ("unique", "primary") + ): + raise ValueError("Source index unique/primary flags must be booleans") + # PostgreSQL already owns the primary key. + if policy.get("primary"): + continue + columns = policy.get("columns") + if ( + not isinstance(columns, list) + or not columns + or any(not isinstance(c, str) or not c.strip() for c in columns) + ): + raise ValueError( + "Source index policy has unsupported keys; review source metadata" + ) + for column in columns: + quote(column) # Check the column name. Do not change its text. + unique = bool(policy.get("unique")) + + # Build a lowercase index name: idx___. + slug = lambda s: re.sub("_+", "_", re.sub("[^a-z0-9_]+", "_", s.lower())).strip( + "_" + ) + name = "idx_" + "_".join( + [slug(dataset.schema), slug(dataset.table)] + [slug(c) for c in columns] + ) + if unique: + name += "_uniq" + identity = json.dumps([dataset.kind, str(dataset.id), columns, unique]) + candidates[identity] = (name, columns, unique) + names.setdefault(name, set()).add(identity) + result = [] + used = set() + for identity, (name, columns, unique) in candidates.items(): + # PostgreSQL allows 63 bytes. Shared short names get a fixed ending too. + if len(name.encode()) > 63 or len(names[name]) > 1: + name = name[:49] + "_" + sha256(identity.encode()).hexdigest()[:12] + sql = ( + "CREATE " + + ("UNIQUE " if unique else "") + + "INDEX " + + quote(name) + + " ON " + + quote(dataset.schema) + + "." + + quote(dataset.table) + + " (" + + ", ".join(quote(c) for c in columns) + + ")" + ) + entry = { + "id": "source:" + sha256(identity.encode()).hexdigest(), + "index_name": name, + "sql": sql, + "desired_state": "present", + "adopt": False, + "revision": 1, + } + definition = parse_index(sql) + if name in excluded: + raise IndexConflict( + f"Source index name {name!r} is already owned by secondary intent" + ) + # Keep an existing index only when the columns match and it is not a constraint. + # A DDP stamp is accepted only when this same source entry owns it. + matches = [ + p + for p in physical + if p.index_name not in excluded | used + and not p.primary + and not p.constraint_owned + and (p.schema, p.table) == (dataset.schema, dataset.table) + and lifecycle.catalog_signature(p, definition) == definition.signature + and ( + not any( + line.startswith("[ddp-index:v1:") + for line in (p.comment or "").splitlines() + ) + or lifecycle.owns(entry, p) + ) + ] + # Use the new name when it exists. Otherwise use a ready older index with the same columns. + actual = next( + iter( + sorted( + matches, + key=lambda p: ( + p.index_name != name, + not (p.valid and p.ready), + p.index_name, + ), + ) + ), + None, + ) + if actual: + name = actual.index_name + sql = definition.render(name=name, concurrently=False) + else: + # Temporary removal must not forget a previously bound source name. + # Current policy identities win: this cannot resurrect deleted policy. + recovery = dataset.document.get("index_reload") or {} + if (recovery.get("schema"), recovery.get("table")) == ( + dataset.schema, + dataset.table, + ): + saved = next( + (e for e in recovery.get("sources", []) if e["id"] == entry["id"]), + None, + ) + if ( + saved + and parse_index(saved["sql"]).signature == definition.signature + ): + name = saved["index_name"] + sql = definition.render(name=name, concurrently=False) + if name in excluded: + raise IndexConflict( + "Recovered source index name is owned by secondary intent" + ) + if name in used: + raise IndexConflict("Source index names collide; review source policy") + used.add(name) + result.append(dict(entry, index_name=name, sql=sql)) + return result + + +class DatasetIndexes: + def __init__(self, database, connector_factory, resolve_reference): + self.database = database + self.connector_factory = connector_factory + self.resolve_reference = resolve_reference + + def get(self, kind, dataset_id, *, reference_schema=None): + if not isinstance(dataset_id, str) or not dataset_id: + raise ValueError('dataset_id must be a non-empty string') + kind = str(kind).upper().replace(' ', '_') + if kind not in KINDS: + raise ValueError('dataset_type must be REFERENCE, POPULATION or CLEANED_TABLE') + collection = self.database[KINDS[kind]] + doc = collection.find_one({'_id': dataset_id}) + if not doc: + raise LookupError('Dataset not found') + if kind == 'REFERENCE' and reference_schema and not doc.get('data_mart_schema'): + doc['data_mart_schema'] = reference_schema + schema = self.resolve_reference(doc) if kind == 'REFERENCE' else doc.get('schema') + table = doc.get('table_name') + quote(schema) + quote(table) + target = Dataset(kind, collection, doc, schema, table) + owners = [] + for candidate_kind, name in KINDS.items(): + key = 'data_mart_schema' if candidate_kind == 'REFERENCE' else 'schema' + owners.extend((name, d['_id']) for d in self.database[name].find({key: schema, 'table_name': table})) + # A legacy reference identity may still be in the worker result buffer. + # Its verified identity is already authoritative + # for this attempt even before the ordinary result is projected. + if (collection.name, dataset_id) not in owners: + owners.append((collection.name, dataset_id)) + if len(owners) != 1: + raise IndexConflict('Duplicate or unresolved physical dataset owners; run the KAN-20 migration audit') + return target + + def inputs(self, document): + targets = {} + for field, kind in DEPENDENCIES.items(): + for identifier in document.get(field) or []: + target = self.get(kind, identifier) + targets[(kind, identifier)] = target + return list(targets.values()) + + def population_targets(self, population_id): + target = self.get('POPULATION', population_id) + return [target] + self.inputs(target.document) + + def resolve(self, schema, table, allowed): + matches = [d for d in allowed if (d.schema, d.table) == (schema, table)] + if len(matches) != 1: + raise ValueError('SQL target must be exactly one registered dataset dependency') + return matches[0] + + def factory(self, target): + return self.connector_factory(target.schema).get_connection + + @contextmanager + def guard(self, target, connection=None): + if connection is not None: + if not connection.autocommit: + raise ValueError('Index DDL requires a dedicated autocommit connection') + with advisory_lock(connection, f'ddp-index:v1:dataset:{target.collection.full_name}:{target.id}'): + with advisory_lock(connection, f'ddp-index:v1:relation:{target.schema}:{target.table}'): + yield connection + return + with dataset_session(self.factory(target), target.collection.full_name, target.id, + target.schema, target.table) as connection: + yield connection + + def source_policy(self, target, connection): + from ddp_lib.postgres_indexes import list_indexes + with connection.cursor() as cursor: + physical = list_indexes(cursor, target.schema, target.table) + return source_entries(target, physical) + + def validate_source_policy(self, target, connection): + """Reject unsupported saved keys before the data writer changes live data.""" + entries = source_entries(target) + # Check definitions on an empty temporary table, without touching live rows. + with connection.cursor() as cursor: + for entry in entries: + lifecycle.canonical_signature(cursor, parse_index(entry['sql']), target.schema, target.table) + + def prepare_reload(self, target, connection, token): + """Prepare temporary removal on the caller's publication transaction. + + The data writer already holds the dataset guard. Rollback must cover + these DROPs, the replacement rows, and its SQL publication receipt. + """ + from ddp_lib.reload_indexes import prepare_reload + + with self.guard(target): + return prepare_reload(self, target, connection, token) + + def reconcile(self, target, connection=None, *, finish=True, mode=IndexCreationMode.ONLINE.value): + """Verify indexes online, or restore them in a post-load maintenance window. + + Post-load CREATE may block target writes. It requires an existing data + commit checkpoint; selecting this mode never creates that checkpoint. + """ + if mode not in {item.value for item in IndexCreationMode}: + raise ValueError('Index creation mode must be an IndexCreationMode value') + # Keep the already resolved KAN-11 identity across lease expiry after a + # reserved SQL commit; ordinary identity backfill may still be buffered. + from dataclasses import replace + + document = target.collection.find_one({"_id": target.id}) + schema_field = "data_mart_schema" if target.kind == "REFERENCE" else "schema" + try: + with self.guard(target, connection) as connection: + # Borrowed connections must also lock before reading the mode's + # checkpoint: a data attempt may have started since get(). + document = target.collection.find_one({"_id": target.id}) + if ( + not document + or document.get("table_name") != target.table + or document.get(schema_field, target.schema) != target.schema + ): + raise IndexConflict("Dataset identity changed; retry") + target = replace(target, document=document) + if mode == IndexCreationMode.POST_LOAD.value and not ( + document.get("index_data_ready") is True + and document.get("index_data_token") + ): + raise lifecycle.IndexRepairError( + "Post-load indexes require a committed data checkpoint" + ) + return lifecycle.reconcile( + target.collection, + target.id, + target.schema, + target.table, + self.factory(target), + connection, + concurrently=mode == IndexCreationMode.ONLINE.value, + source_entries=self.source_policy(target, connection), + finish=finish, + ) + except Exception as exc: + target.collection.update_one( + { + "_id": target.id, + "index_data_token": (document or {}).get("index_data_token"), + }, + { + "$set": { + "index_repair_pending": True, + "index_repair_error": str(exc), + "indexes_applied": False, + } + }, + ) + raise + + def repair(self, target): + """Retry committed data in post-load mode; manual repair stays online.""" + with self.guard(target) as connection: + document = target.collection.find_one({"_id": target.id}) or {} + if document.get("index_data_ready") is False: + raise lifecycle.IndexRepairError( + "The current data attempt has not committed; resume its data job" + ) + mode = ( + IndexCreationMode.POST_LOAD.value + if ( + document.get("index_data_ready") is True + and document.get("index_data_token") + ) + else IndexCreationMode.ONLINE.value + ) + return self.reconcile(target, connection, mode=mode) + + def create(self, target, sql, origin, *, adopt=False, require_concurrently=False): + definition = parse_index(sql) + if require_concurrently and not definition.concurrently: + raise ValueError('Rule CREATE requests must specify CONCURRENTLY') + if (definition.schema, definition.table) != (target.schema, target.table): + raise ValueError('SQL target does not match selected dataset') + with self.guard(target) as connection: + names = {e['index_name'] for e in self.source_policy(target, connection)} + with connection.cursor() as cursor: + physical = inspect_index(cursor, target.schema, definition.index_name) + if definition.index_name in names: + raise IndexConflict('Source-managed indexes are read-only') + if physical and (physical.primary or physical.constraint_owned): + raise IndexConflict( + f"Constraint-owned index '{definition.index_name}' is read-only" + ) + entry = save_intent(target.collection, target.id, target.schema, target.table, sql, origin, adopt) + result = self.reconcile(target) + return {'index': entry, **result.to_dict()} + + def delete(self, target, name): + with self.guard(target) as connection: + names = {e['index_name'] for e in self.source_policy(target, connection)} + if name in names: + raise IndexConflict('Source-managed indexes are read-only') + entry = delete_intent(target.collection, target.id, target.schema, name) + result = self.reconcile(target) + return {'index': entry, **result.to_dict()} + + def listing(self, target): + with self.guard(target) as connection: + return lifecycle.listing(target.collection, target.id, target.schema, target.table, + connection, self.source_policy(target, connection)) + + def register_legacy_population(self, population_id): + """Convert requests to target ownership once; an existing tombstone wins. + + Existing physical objects still require explicit, verified adoption. + Legacy arrays never authorize taking over an unstamped catalog object. + """ + targets = self.population_targets(population_id) + population = targets[0] + docs = list(population.document.get('query_indexes') or []) + for column in population.document.get('indexes') or []: + name = f'idx_{population.schema}_{population.table}_{column}'.encode()[:63].decode('utf8', errors='ignore') + docs.append({'sql': f'CREATE INDEX {quote(name)} ON {quote(population.schema)}.{quote(population.table)} ({quote(column)})'}) + for old in docs: + sql = old.get('sql') or old.get('normalized_sql') + parsed = parse_index(sql) + for key in ('schema', 'table', 'index_name'): + if old.get(key) is not None and old[key] != getattr(parsed, key): + raise ValueError('Legacy index metadata does not match its explicit SQL target') + # A registered request follows its dataset through a rename. The + # original SQL remains evidence and is rebound only for execution. + registered = [t for t in targets if any( + e.get('sql') == sql and e.get('index_name') == parsed.index_name + for e in (t.collection.find_one({'_id': t.id}) or {}).get('secondary_indexes', []))] + if registered: + continue + target = self.resolve(parsed.schema, parsed.table, targets) + fresh = target.collection.find_one({'_id': target.id}) + if any(e['index_name'] == parsed.index_name for e in fresh.get('secondary_indexes', [])): + continue + save_intent(target.collection, target.id, target.schema, target.table, sql, + {'type': 'population', 'id': population_id}, only_if_missing=True) diff --git a/ddp_lib/document.py b/ddp_lib/document.py index 7761ede..3f3b862 100644 --- a/ddp_lib/document.py +++ b/ddp_lib/document.py @@ -1,3 +1,5 @@ +from ddp_lib.index_metadata import DATASET_COLLECTIONS, DEFAULTS, editable_fields, dataset_update +from copy import deepcopy import inject from flask_pymongo import PyMongo from flask import g @@ -33,12 +35,19 @@ def db(self): def save(self): if not self._id: self._id = generate_id() - self._id = self.db().save(self.to_dict()) + if self.__TABLE__ in DATASET_COLLECTIONS: + self.db().update_one({"_id": self._id}, dataset_update( + editable_fields(self.__TABLE__, self.to_dict())), upsert=True) + else: + self._id = self.db().save(self.to_dict()) return self def save_all(self, items, **kwargs): kwargs = kwargs or {} items = [{"_id": generate_id(), **item, **kwargs} for item in items] + if self.__TABLE__ in DATASET_COLLECTIONS: + items = [dict(editable_fields(self.__TABLE__, item), _id=item["_id"], + **deepcopy(DEFAULTS)) for item in items] self.db().insert_many(items) return items @@ -81,7 +90,9 @@ def delete_all(cls, query): cls().db().delete_many(query) def update(self, data: dict): - self.db().update_one({"_id": self._id}, {"$set": data}) + fields = editable_fields(self.__TABLE__, data) + if fields: + self.db().update_one({"_id": self._id}, {"$set": fields}) # for k, v in data.items(): # self.__setattr__(k, v) # return self diff --git a/ddp_lib/enums.py b/ddp_lib/enums.py index 6b5604b..7fde987 100644 --- a/ddp_lib/enums.py +++ b/ddp_lib/enums.py @@ -1,5 +1,10 @@ from enum import Enum +class IndexCreationMode(Enum): + ONLINE = 'online' # CREATE INDEX CONCURRENTLY; the table stays writable + POST_LOAD = 'post_load' # CREATE INDEX after a data commit; can block writes + + class UserRoleEnum(Enum): ADMIN = 'ADMIN' DATA_OWNER = 'DATA_OWNER' @@ -162,6 +167,7 @@ class SyncStatus(Enum): class QueuedJobAction(Enum): + RECONCILE_INDEXES = "RECONCILE_INDEXES" FULL_REBUILD = "FULL_REBUILD" FULL_REFRESH = "FULL_REFRESH" FULL_SYNC = "FULL_SYNC" diff --git a/ddp_lib/index_hooks.py b/ddp_lib/index_hooks.py new file mode 100644 index 0000000..988dd8b --- /dev/null +++ b/ddp_lib/index_hooks.py @@ -0,0 +1,62 @@ +"""Small hooks around existing data writers; never implements their refresh SQL.""" +from contextvars import ContextVar +from functools import wraps +from uuid import uuid4 + +from ddp_lib.enums import IndexCreationMode +from ddp_lib.index_metadata import begin_data, data_committed +from ddp_lib.secondary_indexes import IndexRepairError + +_attempts = ContextVar('ddp_index_data_attempts', default=None) + + +def guarded_data(registry_factory, kind, *, document_arg=0, execution_factory=None, close_on_failure=(), restore_after=False): + def decorate(function): + @wraps(function) + def wrapped(*args, **kwargs): + registry = registry_factory() + document = args[document_arg] + target = None + entered = False + try: + target = registry.get(kind, document.id) + with registry.guard(target) as connection: + entered = True + execution = execution_factory() if execution_factory else None + if execution: + execution.job.assert_owned() + # Stop invalid saved policies before starting the data write. + registry.validate_source_policy(target, connection) + token = execution.job.attempt_id if execution else uuid4().hex + begin_data(target.collection, target.id, token, + owner=execution.job.attempt_id if execution else None) + previous = _attempts.get() or {} + context = _attempts.set(dict(previous, **{str(target.id): (token, target)})) + try: + result = function(*args, **kwargs) + if restore_after: + committed(registry, kind, document) + registry.reconcile(target, mode=IndexCreationMode.POST_LOAD.value) + return result + finally: + _attempts.reset(context) + except Exception as exc: + if target is not None: + target.collection.update_one({'_id': target.id, 'index_data_token': locals().get('token')}, {'$set': { + 'index_repair_pending': True, 'index_repair_error': str(exc)}}) + if not entered: + for position in close_on_failure: + if len(args) > position and args[position] is not None: + args[position].close() + raise + return wrapped + return decorate + + +def committed(registry, kind, document): + attempt = (_attempts.get() or {}).get(str(document.id)) + if attempt is None: + raise IndexRepairError('Missing data-writing attempt checkpoint') + token, target = attempt + data_committed(target.collection, target.id, token) + return target diff --git a/ddp_lib/index_metadata.py b/ddp_lib/index_metadata.py new file mode 100644 index 0000000..f7310fa --- /dev/null +++ b/ddp_lib/index_metadata.py @@ -0,0 +1,134 @@ +"""Dataset-owned intent, compare-and-swap writes, and data-attempt checkpoints.""" +from copy import deepcopy +from datetime import datetime, timezone +from uuid import uuid4 + +from ddp_lib.index_sql import parse_index + +DATASET_COLLECTIONS = frozenset({'references', 'populations', 'cleaned_tables'}) +PROTECTED = frozenset({'_id', 'secondary_indexes', 'secondary_indexes_revision', + 'index_repair_pending', 'index_repair_error', 'index_data_ready', + 'index_data_token', 'index_repair_stage', 'index_reload'}) +DEFAULTS = {'secondary_indexes': [], 'secondary_indexes_revision': 0, + 'index_repair_pending': False, 'index_repair_error': None} + + +class IndexConflict(ValueError): + pass + + +def now(): + return datetime.now(timezone.utc).isoformat() + + +def editable_fields(collection, fields): + if collection not in DATASET_COLLECTIONS: + return dict(fields) + return {k: v for k, v in fields.items() if k.split('.', 1)[0] not in PROTECTED} + + +def dataset_update(fields): + return {'$set': fields, '$setOnInsert': deepcopy(DEFAULTS)} + + +def expected_revision(doc): + return doc['secondary_indexes_revision'] if 'secondary_indexes_revision' in doc else {'$exists': False} + + +def mutate(collection, dataset_id, change, *, pending=False): + for _ in range(8): + doc = collection.find_one({'_id': dataset_id}) + if not doc: + raise LookupError('Index target dataset does not exist') + entries = deepcopy(doc.get('secondary_indexes') or []) + result = change(entries) + if result is None: + return None + if entries == (doc.get('secondary_indexes') or []): + return result + fields = {'secondary_indexes': entries, + 'secondary_indexes_revision': doc.get('secondary_indexes_revision', 0) + 1} + if pending: + fields.update(index_repair_pending=True, indexes_applied=False) + changed = collection.update_one({'_id': dataset_id, + 'secondary_indexes_revision': expected_revision(doc)}, {'$set': fields}) + if changed.matched_count: + return result + raise IndexConflict('Index metadata changed concurrently; retry the operation') + + +def save_intent(collection, dataset_id, schema, table, raw_sql, origin=None, adopt=False, *, only_if_missing=False): + definition = parse_index(raw_sql) + if (definition.schema, definition.table) != (schema, table): + raise ValueError('Index SQL must target the selected dataset') + if not isinstance(adopt, bool): + raise ValueError('adopt must be a boolean') + def change(entries): + entry = next((e for e in entries if e['index_name'] == definition.index_name), None) + if entry and only_if_missing: + return entry + if entry and entry['desired_state'] == 'present': + if parse_index(entry['sql']).signature != definition.signature: + raise IndexConflict('Index name already has a different desired definition') + # Explicit adoption of an unowned request is a new revision. + if not adopt or entry.get('adopt'): + return entry + if entry is None: + entry = {'id': uuid4().hex, 'revision': 0, 'created_at': now()} + entries.append(entry) + entry.update(schema=schema, table=table, index_name=definition.index_name, + sql=raw_sql, desired_state='present', status='pending', + revision=entry['revision'] + 1, updated_at=now(), origin=origin or {}, adopt=adopt) + entry.pop('last_error', None) + entry.pop('signature', None) + return entry + return mutate(collection, dataset_id, change, pending=True) + + +def delete_intent(collection, dataset_id, schema, index_name): + def change(entries): + entry = next((e for e in entries if e['index_name'] == index_name), None) + if entry is None: + raise IndexConflict('Only managed secondary indexes may be deleted') + if entry['desired_state'] == 'absent': + return entry + entry.update(desired_state='absent', status='pending', revision=entry['revision'] + 1, + updated_at=now()) + return entry + return mutate(collection, dataset_id, change, pending=True) + + +def record_result(collection, dataset_id, index_id, revision, result): + def change(entries): + entry = next((e for e in entries if e['id'] == index_id and e['revision'] == revision), None) + if entry is None: + return None + allowed = {'status', 'signature', 'last_error', 'schema', 'table'} + entry.update({k: v for k, v in result.items() if k in allowed}) + entry['last_run_at'] = now() + if result.get('status') in {'created', 'deleted'}: + entry.pop('last_error', None) + # Adoption authorizes one checked object, not all future replacements. + entry['adopt'] = False + return True + return bool(mutate(collection, dataset_id, change)) + + +def begin_data(collection, dataset_id, token, *, owner=None): + query = {'_id': dataset_id} + if owner: + query['queue_attempt'] = owner + if not collection.update_one(query, {'$set': { + 'index_data_token': token, 'index_data_ready': False, + 'index_repair_pending': True, 'indexes_applied': False, + 'index_repair_stage': 'writing', + }}).matched_count: + raise IndexConflict('Data attempt no longer owns this dataset') + + +def data_committed(collection, dataset_id, token): + if not collection.update_one({'_id': dataset_id, 'index_data_token': token}, {'$set': { + 'index_data_ready': True, 'index_repair_pending': True, + 'index_repair_stage': 'indexing', + }}).matched_count: + raise IndexConflict('Data checkpoint belongs to a newer attempt') diff --git a/ddp_lib/index_sql.py b/ddp_lib/index_sql.py new file mode 100644 index 0000000..9ee8589 --- /dev/null +++ b/ddp_lib/index_sql.py @@ -0,0 +1,130 @@ +"""Strict PostgreSQL index requests; raw expression text is never rewritten.""" + +from dataclasses import dataclass +import json + +from pglast import ast, parse_sql, scan + + +def quote(value): + if ( + not isinstance(value, str) + or not value + or "\x00" in value + or len(value.encode("utf8")) > 63 + ): + raise ValueError("PostgreSQL identifiers must contain 1–63 UTF-8 bytes") + return '"' + value.replace('"', '""') + '"' + + +@dataclass(frozen=True) +class IndexDefinition: + schema: str + table: str + index_name: str + unique: bool + only: bool + concurrently: bool + body: str + signature: dict + + def render( + self, schema=None, table=None, *, concurrently=None, name=None, only=None + ): + concurrent = self.concurrently if concurrently is None else concurrently + scope = self.only if only is None else only + return ( + "CREATE " + + ("UNIQUE " if self.unique else "") + + "INDEX " + + ("CONCURRENTLY " if concurrent else "") + + quote(name or self.index_name) + + " ON " + + ("ONLY " if scope else "") + + quote(schema or self.schema) + + "." + + quote(table or self.table) + + " " + + self.body + ) + + +def _structure(value): + if isinstance(value, dict): + return { + k: _structure(v) + for k, v in value.items() + if k not in {"location", "stmt_location", "stmt_len"} + } + if isinstance(value, (tuple, list)): + return [_structure(v) for v in value] + return value + + +def parse_index(statement): + """Read one CREATE INDEX and keep the column expression exactly as written.""" + if not isinstance(statement, str) or not statement.strip(): + raise ValueError("A CREATE INDEX statement is required") + try: + # scan splits the text into words and records where each word starts. + tokens = scan(statement) + # The PostgreSQL parser truncates long identifiers. Reject BEFORE parsing. + for token in tokens: + if token.name in {"IDENT", "UIDENT"}: + raw = statement[token.start : token.end + 1] + # UIDENT is a quoted name written with a Unicode escape, such as U&"\00E9". + if token.name == "UIDENT": + raise ValueError( + "Use literal UTF-8 quoted identifiers instead of Unicode escapes" + ) + # A quoted token still includes its quotes. "" inside the name is one ". + name = raw[1:-1].replace('""', '"') if raw.startswith('"') else raw + quote(name) + # parse_sql builds the statement tree. One SQL string can hold several statements. + parsed = parse_sql(statement) + except Exception as exc: + raise ValueError(f"Invalid CREATE INDEX: {exc}") from exc + # ast.IndexStmt means the statement is CREATE INDEX. Anything else is rejected. + if len(parsed) != 1 or not isinstance(parsed[0].stmt, ast.IndexStmt): + raise ValueError("Exactly one CREATE INDEX statement is required") + node = parsed[0].stmt + rel = node.relation + # catalogname is set for database.schema.table. The target must be schema.table only. + if not node.idxname or not rel.schemaname or rel.catalogname: + raise ValueError("A named index on an explicit schema.table target is required") + for name in (node.idxname, rel.schemaname, rel.relname): + quote(name) + # rel.location is the start of the schema name. The next tokens are schema, ".", table. + target_tokens = [t for t in tokens if t.start >= rel.location] + if len(target_tokens) < 4 or target_tokens[1].name != "ASCII_46": + raise ValueError("Expected a schema-qualified index target") + # Keep the original text after the table name, such as "(status)". Do not rebuild it. + body = statement[target_tokens[2].end + 1 :].strip().rstrip(";").rstrip() + structure = node() + # Drop fields that change when the same index is renamed, moved, or recreated. + ignored = { + "idxname", + "relation", + "concurrent", + "if_not_exists", + "idxcomment", + "oldNumber", + "oldCreateSubid", + "oldFirstRelfilelocatorSubid", + } + signature = _structure({k: v for k, v in structure.items() if k not in ignored}) + # ONLY lives on the table node, which was dropped above. inh is false when ONLY is set. + signature["only"] = not rel.inh + # Force JSON types, so Mongo round trips retain identical comparisons. + signature = json.loads(json.dumps(signature)) + return IndexDefinition( + rel.schemaname, + rel.relname, + node.idxname, + bool(node.unique), + not rel.inh, + bool(node.concurrent), + body, + signature, + ) + \ No newline at end of file diff --git a/ddp_lib/postgres_indexes.py b/ddp_lib/postgres_indexes.py new file mode 100644 index 0000000..2d79020 --- /dev/null +++ b/ddp_lib/postgres_indexes.py @@ -0,0 +1,162 @@ +"""PostgreSQL catalog and session primitives for dataset index lifecycle. + +No application metadata or authorization policy lives in this module. +""" +from contextlib import contextmanager +from contextvars import ContextVar +from dataclasses import dataclass +from hashlib import sha256 + +from psycopg2.sql import SQL, Identifier + + +class IndexLockBusy(RuntimeError): + """The lock is already taken. The caller can retry; this does not wait.""" + + +@dataclass(frozen=True) +class PhysicalIndex: + """One index as PostgreSQL reports it. This is not the saved DDP request.""" + + oid: int + schema: str + table: str + index_name: str + definition: str # CREATE INDEX text returned by PostgreSQL. + valid: bool # False when a failed build is still in the catalog. + ready: bool # False while PostgreSQL is still building the index. + primary: bool + constraint_owned: bool # True for a PRIMARY KEY or UNIQUE constraint. + relation_kind: str # Kind of the table. "p" means a partitioned table. + comment: str | None + + +def inspect_index(cursor, schema, name): + """Read one index from the catalog. Return None when that name is missing.""" + # Column order matches PhysicalIndex. t.relkind is the table kind, not the index kind. + cursor.execute('''SELECT i.oid, n.nspname, t.relname, i.relname, + pg_get_indexdef(x.indexrelid), x.indisvalid, x.indisready, x.indisprimary, + EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid=i.oid), + t.relkind, obj_description(i.oid, 'pg_class') + FROM pg_class i JOIN pg_namespace n ON n.oid=i.relnamespace + LEFT JOIN pg_index x ON x.indexrelid=i.oid + LEFT JOIN pg_class t ON t.oid=x.indrelid + WHERE n.nspname=%s AND i.relname=%s''', (schema, name)) + row = cursor.fetchone() + return PhysicalIndex(*row) if row else None + + +def list_indexes(cursor, schema, table): + """Return every index on this table, in name order.""" + cursor.execute('''SELECT i.relname FROM pg_index x + JOIN pg_class i ON i.oid=x.indexrelid JOIN pg_class t ON t.oid=x.indrelid + JOIN pg_namespace n ON n.oid=t.relnamespace + WHERE n.nspname=%s AND t.relname=%s ORDER BY i.relname''', (schema, table)) + return [inspect_index(cursor, schema, name) for name, in cursor.fetchall()] + + +def index_ready(cursor, physical): + """Verify an index and every attached index covering its partition tree.""" + # A ready parent alone does not prove that all its partitions are ready. + if not physical or not physical.valid or not physical.ready: + return False + if physical.relation_kind != 'p': + return True + # pg_get_indexdef renders ON ONLY even for a complete partitioned index. + # Compare definitions separately and require coverage/readiness at every + # level, including intermediate partitioned relations and empty branches. + cursor.execute('''WITH RECURSIVE + tables(oid) AS ( + SELECT indrelid FROM pg_index WHERE indexrelid=%s + UNION ALL + SELECT h.inhrelid FROM pg_inherits h JOIN tables t ON h.inhparent=t.oid + ), indexes(oid) AS ( + SELECT %s::oid + UNION ALL + SELECT h.inhrelid FROM pg_inherits h JOIN indexes i ON h.inhparent=i.oid + ) + SELECT EXISTS (SELECT 1 FROM tables) AND NOT EXISTS ( + SELECT 1 FROM tables t LEFT JOIN ( + SELECT x.* FROM pg_index x JOIN indexes i ON i.oid=x.indexrelid + ) x ON x.indrelid=t.oid + WHERE x.indexrelid IS NULL OR NOT x.indisvalid OR NOT x.indisready OR NOT x.indislive + )''', (physical.oid, physical.oid)) + return bool(cursor.fetchone()[0]) + + +def lock_id(key): + """Turn a text key into the number PostgreSQL uses for an advisory lock.""" + # The same key always hashes to the same signed 64-bit number. + return int.from_bytes(sha256(key.encode('utf8')).digest()[:8], 'big', signed=True) + + +@contextmanager +def advisory_lock(connection, key): + """Hold a session lock, or fail at once when another session already holds it.""" + with connection.cursor() as cur: + # This does not wait. False means a dataset or index change is already running. + cur.execute('SELECT pg_try_advisory_lock(%s)', (lock_id(key),)) + if not cur.fetchone()[0]: + raise IndexLockBusy('Dataset/index is busy; retry reconciliation') + try: + yield connection + finally: + # A closed connection has already released its locks. + if not connection.closed: + with connection.cursor() as cur: + cur.execute('SELECT pg_advisory_unlock(%s)', (lock_id(key),)) + + +# Connections already opened by this task, so nested index work can reuse them. +_sessions = ContextVar('ddp_index_sessions', default=None) + + +@contextmanager +def dataset_session(factory, collection, dataset_id, schema, table): + """Open one autocommit connection and lock this dataset for index changes. + + A nested call for the same dataset reuses that connection. CREATE and DROP + INDEX CONCURRENTLY cannot run inside a transaction, so autocommit stays on. + """ + key = f'ddp-index:v1:dataset:{collection}:{dataset_id}' + held = _sessions.get() or {} + if key in held: + # This task already opened the session. Do not lock or connect again. + yield held[key] + return + connection = factory() + if connection is None: + raise ConnectionError('Unable to connect to the datamart') + try: + connection.autocommit = True + with advisory_lock(connection, key): + # Also lock schema.table, so two records for one table cannot both change indexes. + with advisory_lock(connection, f'ddp-index:v1:relation:{schema}:{table}'): + token = _sessions.set(dict(held, **{key: connection})) + try: + yield connection + finally: + _sessions.reset(token) + finally: + connection.close() + + +def stamp(cursor, physical, receipt): + """Mark the index as one DDP owns, and keep every other comment line.""" + prefix = '[ddp-index:v1:' + # Remove an older DDP line, then add one new line. Other comment text stays. + lines = (physical.comment or '').split('\n') + original = '\n'.join(line for line in lines if not line.startswith(prefix)) + comment = original + ('\n' if original else '') + prefix + receipt + ']' + cursor.execute(SQL('COMMENT ON INDEX {}.{} IS %s').format( + Identifier(physical.schema), Identifier(physical.index_name)), (comment,)) + + +def drop(cursor, physical): + """Drop an index. Leave primary keys and constraint indexes alone.""" + if physical.primary or physical.constraint_owned or physical.table is None: + raise ValueError('Cannot drop a constraint or non-index relation') + # A partitioned table rejects DROP INDEX CONCURRENTLY, so it uses a normal drop. + cursor.execute(SQL('DROP INDEX {}{}.{}').format( + SQL('' if physical.relation_kind == 'p' else 'CONCURRENTLY '), + Identifier(physical.schema), Identifier(physical.index_name))) diff --git a/ddp_lib/reload_indexes.py b/ddp_lib/reload_indexes.py new file mode 100644 index 0000000..6fcc86b --- /dev/null +++ b/ddp_lib/reload_indexes.py @@ -0,0 +1,132 @@ +"""Transactional temporary removal for full loads; saved intent is never deleted.""" + +from dataclasses import dataclass, replace +import os + +from ddp_lib.index_metadata import IndexConflict, expected_revision +from ddp_lib.index_sql import parse_index, quote +from ddp_lib.postgres_indexes import inspect_index +from ddp_lib import secondary_indexes as lifecycle + + +@dataclass(frozen=True) +class ReloadPreparation: + token: str + dropped: tuple + + +def prepare_reload(manager, target, connection, token): + if connection.autocommit: + raise ValueError("Temporary index removal requires the publication transaction") + doc = target.collection.find_one({"_id": target.id}) or {} + schema_key = "data_mart_schema" if target.kind == "REFERENCE" else "schema" + if ( + not token + or doc.get("index_data_token") != token + or doc.get("index_data_ready") is not False + or doc.get("table_name") != target.table + or doc.get(schema_key, target.schema) != target.schema + ): + raise IndexConflict( + "Temporary removal requires the current uncommitted data attempt" + ) + target = replace(target, document=doc) + with connection.cursor() as cursor: + cursor.execute( + "SET LOCAL lock_timeout = %s", (os.getenv("INDEX_LOCK_TIMEOUT", "5s"),) + ) + cursor.execute( + "SET LOCAL statement_timeout = %s", + (os.getenv("INDEX_STATEMENT_TIMEOUT", "30min"),), + ) + # Fence table/index DDL before catalog checks. Only an actual ordinary + # DROP upgrades this to ACCESS EXCLUSIVE and blocks readers until commit. + cursor.execute( + f"LOCK TABLE {quote(target.schema)}.{quote(target.table)} IN SHARE ROW EXCLUSIVE MODE" + ) + sources = manager.source_policy(target, connection) + entries = sources + list(doc.get("secondary_indexes") or []) + selected, names = [], set() + for entry in entries: + definition = parse_index(entry["sql"]) + if ( + entry["index_name"] != definition.index_name + or entry["index_name"] in names + ): + raise IndexConflict("Duplicate or mismatched managed index name") + names.add(entry["index_name"]) + if entry["desired_state"] not in {"present", "absent"}: + raise IndexConflict("Invalid desired index state") + if entry["desired_state"] == "absent": + continue # Tombstones remain authoritative during restoration. + # Validate *all* desired definitions, including currently missing ones. + expected = lifecycle.canonical_signature( + cursor, definition, target.schema, target.table + ) + physical = inspect_index(cursor, target.schema, entry["index_name"]) + if physical is None: + continue + if (physical.schema, physical.table) != (target.schema, target.table): + raise IndexConflict("Index name is occupied by another relation") + if ( + physical.primary + or physical.constraint_owned + or physical.relation_kind == "p" + ): + continue + cursor.execute( + "SELECT 1 FROM pg_inherits WHERE inhrelid=%s OR inhparent=%s", + (physical.oid, physical.oid), + ) + if cursor.fetchone(): + continue + lifecycle.validate_existing( + cursor, entry, physical, target.schema, target.table + ) + if lifecycle.catalog_signature(physical, definition) != expected: + raise IndexConflict("Managed index differs from its saved definition") + selected.append((entry, physical)) + + query = { + "_id": target.id, + "index_data_token": token, + "index_data_ready": False, + "secondary_indexes_revision": expected_revision(doc), + "source_indexes": doc.get("source_indexes", {"$exists": False}), + } + # Acknowledged durable definitions and resolved source names precede the + # first DROP. No metadata change may convert this to an absent intent. + snapshot = { + "token": token, + "schema": target.schema, + "table": target.table, + "sources": sources, + "secondary_revision": doc.get("secondary_indexes_revision", 0), + "indexes": [ + dict(entry, physical_definition=p.definition, comment=p.comment) + for entry, p in selected + ], + } + if not target.collection.update_one( + query, + { + "$set": { + "index_reload": snapshot, + "index_repair_pending": True, + "index_repair_error": None, + "indexes_applied": False, + } + }, + ).matched_count: + raise IndexConflict( + "Index definitions changed during reload preparation; retry" + ) + for entry, physical in selected: + if not target.collection.find_one(query): + raise IndexConflict( + "Index definitions changed before temporary removal; retry" + ) + cursor.execute( + f"DROP INDEX {quote(physical.schema)}.{quote(physical.index_name)} RESTRICT" + ) + return ReloadPreparation(token, tuple(p.index_name for _, p in selected)) diff --git a/ddp_lib/secondary_indexes.py b/ddp_lib/secondary_indexes.py new file mode 100644 index 0000000..4813195 --- /dev/null +++ b/ddp_lib/secondary_indexes.py @@ -0,0 +1,445 @@ +"""Durable dataset index reconciliation, shared by API and worker (KAN-20).""" + +from dataclasses import asdict, dataclass +from hashlib import sha256 +import json +import os +from uuid import uuid4 + +from ddp_lib.index_sql import parse_index, quote +from ddp_lib.index_metadata import ( + IndexConflict, + save_intent, + delete_intent, + record_result, + expected_revision, +) +from ddp_lib.postgres_indexes import ( + advisory_lock, + dataset_session, + inspect_index, + list_indexes, + index_ready, + stamp, + drop, +) + + +@dataclass(frozen=True) +class ReconcileResult: + ready: bool + applied: int + errors: tuple + revision: int + + def to_dict(self): + return asdict(self) + + +class IndexRepairError(RuntimeError): + def __init__(self, message, result=None): + super().__init__(message) + self.result = result + + +def catalog_signature(physical, definition): + # Compare index definitions independently of their names. + signature = parse_index(physical.definition).signature + # PostgreSQL prints ONLY for every partitioned parent. Full-tree readiness + # is checked separately; catalog rendering must not change saved intent. + if physical.relation_kind == "p": + signature["only"] = definition.only + return signature + + +def receipt(entry, physical): + definition = parse_index(entry["sql"]) + payload = [ + entry["id"], + definition.signature, + catalog_signature(physical, definition), + ] + return sha256(json.dumps(payload, sort_keys=True).encode("utf8")).hexdigest() + + +def owns(entry, physical): + return "[ddp-index:v1:" + receipt(entry, physical) + "]" in ( + physical.comment or "" + ).split("\n") + + +def canonical_signature(cursor, definition, schema, table): + """Ask PostgreSQL to normalize the request against the target column types. + + A private, empty LIKE table avoids guessing which casts/default opclasses + the server inserts. No data is copied and no target index is modified. + """ + temp = "ddp_index_check_" + uuid4().hex + name = "ddp_index_" + uuid4().hex + created = False + try: + cursor.execute( + f"CREATE TEMP TABLE {quote(temp)} (LIKE {quote(schema)}.{quote(table)})" + ) + created = True + cursor.execute( + definition.render( + "pg_temp", temp, name=name, concurrently=False, only=False + ) + ) + cursor.execute( + """SELECT pg_get_indexdef(i.indexrelid) FROM pg_index i + JOIN pg_class t ON t.oid=i.indrelid + WHERE t.relnamespace=pg_my_temp_schema() AND t.relname=%s""", + (temp,), + ) + signature = parse_index(cursor.fetchone()[0]).signature + signature["only"] = definition.only + return signature + finally: + if created: + cursor.execute(f"DROP TABLE pg_temp.{quote(temp)}") + + +def validate_existing(cursor, entry, physical, schema, table): + if physical is None: + return + if (physical.schema, physical.table) != (schema, table): + raise IndexConflict("Index name is occupied by another relation") + if physical.primary or physical.constraint_owned: + raise IndexConflict( + f"Constraint-owned index '{physical.index_name}' is read-only" + ) + definition = parse_index(entry["sql"]) + if owns(entry, physical): + return + if not entry.get("adopt") or entry["desired_state"] != "present": + raise IndexConflict( + "Unmanaged index requires explicit adoption and definition review" + ) + expected = canonical_signature(cursor, definition, schema, table) + if catalog_signature(physical, definition) != expected: + raise IndexConflict("Existing index has a different definition") + + +def apply_entry(cursor, entry, schema, table, *, concurrently=True): + definition = parse_index(entry["sql"]) + physical = inspect_index(cursor, schema, entry["index_name"]) + if (physical and (physical.schema, physical.table) == (schema, table) + and (physical.primary or physical.constraint_owned)): + # Leave the primary key or unique constraint in place. A mistaken saved + # request must not block the other indexes on this table. + if entry["desired_state"] == "absent": + return {"status": "deleted", "schema": schema, "table": table} + if str(entry.get("id", "")).startswith("source:"): + raise IndexConflict( + f"Constraint-owned index '{physical.index_name}' is read-only" + ) + return { + "status": "error", + "last_error": f"Constraint-owned index '{physical.index_name}' is read-only", + "schema": schema, + "table": table, + } + validate_existing(cursor, entry, physical, schema, table) + if entry["desired_state"] == "absent": + if physical: + drop(cursor, physical) + if inspect_index(cursor, schema, entry["index_name"]) is not None: + raise IndexRepairError("Index still exists after DROP") + return {"status": "deleted", "schema": schema, "table": table} + if physical and (not physical.valid or not physical.ready): + if physical.relation_kind == "p": + raise IndexRepairError( + "Invalid partitioned index requires explicit attachment review" + ) + drop(cursor, physical) + physical = None + expected = entry.get("signature") + if not physical: + expected = canonical_signature(cursor, definition, schema, table) + cursor.execute( + """SELECT c.relkind FROM pg_class c JOIN pg_namespace n ON n.oid=c.relnamespace + WHERE n.nspname=%s AND c.relname=%s""", + (schema, table), + ) + kind = cursor.fetchone() + try: + cursor.execute( + definition.render( + schema, + table, + concurrently=concurrently and bool(kind) and kind[0] != "p", + ) + ) + except Exception as exc: + # Only a failed build owned by this CREATE can acquire a receipt. + # Duplicate-name races and connection ambiguity require review. + if getattr(exc, "pgcode", None) not in {None, "42P07", "42710"}: + invalid = inspect_index(cursor, schema, entry["index_name"]) + if ( + invalid + and invalid.table == table + and not invalid.valid + and not invalid.constraint_owned + and not invalid.primary + and catalog_signature(invalid, definition) == expected + ): + stamp(cursor, invalid, receipt(entry, invalid)) + raise + physical = inspect_index(cursor, schema, entry["index_name"]) + if not physical or catalog_signature(physical, definition) != expected: + raise IndexRepairError( + "Created index does not match the requested definition" + ) + stamp(cursor, physical, receipt(entry, physical)) + elif entry.get("adopt"): + stamp(cursor, physical, receipt(entry, physical)) + # Report success only when the index and all its partitions are ready. + if not index_ready(cursor, physical): + raise IndexRepairError("Index or partition tree is not valid and ready; attachment review required") + signature = catalog_signature(physical, definition) + if expected is not None and signature != expected: + raise IndexConflict( + "Physical definition differs from the verified saved definition" + ) + return { + "status": "created", + "signature": signature, + "schema": schema, + "table": table, + } + + +def _version(entries): + return {(e["id"], e["revision"]) for e in entries} + + +def reconcile( + collection, + dataset_id, + schema, + table, + connection_factory, + connection=None, + *, + concurrently=True, + source_entries=(), + finish=True, +): + if connection is None: + initial = collection.find_one({'_id': dataset_id}) or {} + try: + with dataset_session( + connection_factory, collection.full_name, dataset_id, schema, table + ) as conn: + return reconcile( + collection, + dataset_id, + schema, + table, + connection_factory, + conn, + concurrently=concurrently, + source_entries=source_entries, + finish=finish, + ) + except Exception as exc: + collection.update_one( + {"_id": dataset_id, "index_data_token": initial.get('index_data_token')}, + { + "$set": { + "index_repair_pending": True, + "index_repair_error": str(exc), + "indexes_applied": False, + } + }, + ) + if isinstance(exc, IndexRepairError): + raise + raise IndexRepairError(str(exc)) from exc + if not connection.autocommit: + raise ValueError('Index DDL requires a dedicated autocommit connection') + # A supplied connection follows the same lock contract. PostgreSQL session + # locks are reentrant when the caller already holds the data-write guard. + with advisory_lock(connection, f'ddp-index:v1:dataset:{collection.full_name}:{dataset_id}'): + with advisory_lock(connection, f'ddp-index:v1:relation:{schema}:{table}'): + return _reconcile_snapshot(collection, dataset_id, schema, table, connection, + concurrently, source_entries, finish) + + +def _error_text(errors): + return "; ".join( + f"{item['index_name']}: {item['error']}" if item.get("index_name") else item["error"] + for item in errors + ) + +def _reconcile_snapshot(collection, dataset_id, schema, table, connection, + concurrently, source_entries, finish): + """Make this table's indexes match the saved list. + + Source indexes run first, then secondary indexes. Stop if the saved list + changes. On success, mark the dataset verified. On failure, keep the + repair flag and name the index that failed. + """ + doc = collection.find_one({"_id": dataset_id}) + if not doc: + raise LookupError("Index target dataset does not exist") + entries = doc.get("secondary_indexes") or [] + errors = [] + applied = 0 + with connection.cursor() as cursor: + cursor.execute("SET lock_timeout = %s", (os.getenv("INDEX_LOCK_TIMEOUT", "5s"),)) + cursor.execute("SET statement_timeout = %s", (os.getenv("INDEX_STATEMENT_TIMEOUT", "30min"),)) + source_names = {e["index_name"] for e in source_entries} + for entry in list(source_entries) + entries: + source = entry in source_entries + try: + with advisory_lock( + connection, f'ddp-index:v1:name:{schema}:{entry["index_name"]}' + ): + if not source: + if entry["index_name"] in source_names: + raise IndexConflict( + "Source-managed indexes are read-only through the secondary API" + ) + latest = collection.find_one({"_id": dataset_id}) or {} + live = next( + ( + e + for e in latest.get("secondary_indexes", []) + if e["id"] == entry["id"] + ), + None, + ) + if not live or live["revision"] != entry["revision"]: + raise IndexConflict( + "Index intent changed before DDL; retry" + ) + outcome = apply_entry( + cursor, entry, schema, table, concurrently=concurrently + ) + if not source and not record_result( + collection, dataset_id, entry["id"], entry["revision"], outcome + ): + raise IndexConflict("Index intent changed during DDL; retry") + applied += 1 + except Exception as exc: + errors.append({"index_name": entry["index_name"], "error": str(exc)}) + if not source: + try: + record_result( + collection, + dataset_id, + entry["id"], + entry["revision"], + {"status": "error", "last_error": str(exc)}, + ) + except Exception as recording_error: + errors.append( + { + "index_name": entry["index_name"], + "error": str(recording_error), + } + ) + if not errors: + try: + cursor.execute(f"ANALYZE {quote(schema)}.{quote(table)}") + except Exception as exc: + errors.append({"error": str(exc)}) + latest = collection.find_one({"_id": dataset_id}) or {} + if latest.get('index_data_token') != doc.get('index_data_token'): + errors.append({'error': 'Data checkpoint belongs to a newer attempt'}) + if latest.get("source_indexes") != doc.get("source_indexes"): + errors.append( + {"error": "Source index policy changed during reconciliation; retry"} + ) + if _version(latest.get("secondary_indexes", [])) != _version(entries): + errors.append( + {"error": "Index definitions changed during reconciliation; retry"} + ) + if errors: + collection.update_one( + {"_id": dataset_id, "index_data_token": doc.get('index_data_token')}, + { + "$set": { + "index_repair_pending": True, + "index_repair_error": _error_text(errors), + "indexes_applied": False, + } + }, + ) + result = ReconcileResult( + False, applied, tuple(errors), latest.get("secondary_indexes_revision", 0) + ) + raise IndexRepairError(_error_text(errors), result) + # Never let index verification stand in for a data commit checkpoint. + if finish and latest.get("index_data_ready") is not False: + query = { + "_id": dataset_id, + "secondary_indexes_revision": expected_revision(latest), + "index_data_token": doc.get("index_data_token"), + "source_indexes": latest.get("source_indexes", {"$exists": False}), + } + changed = collection.update_one( + query, + { + "$set": { + "index_repair_pending": False, + "index_repair_error": None, + "indexes_applied": True, + "index_repair_stage": "verified", + } + }, + ) + if not changed.matched_count: + raise IndexRepairError( + "Dataset changed before reconciliation completion; retry" + ) + return ReconcileResult( + True, applied, (), latest.get("secondary_indexes_revision", 0) + ) + + +def listing(collection, dataset_id, schema, table, connection, source_entries=()): + doc = collection.find_one({"_id": dataset_id}) or {} + entries = {e["index_name"]: e for e in doc.get("secondary_indexes", [])} + sources = {e["index_name"]: e for e in source_entries} + with connection.cursor() as cursor: + physical = {p.index_name: p for p in list_indexes(cursor, schema, table)} + # Show the same readiness in the UI that reconciliation checks. + readiness = {name: index_ready(cursor, p) for name, p in physical.items()} + result = [] + for name in sorted(set(entries) | set(sources) | set(physical)): + entry, actual = entries.get(name), physical.get(name) + kind = ( + "constraint" + if actual and (actual.primary or actual.constraint_owned) + else "source" if name in sources else "secondary" if entry else "unmanaged" + ) + row = dict( + entry or {}, + schema=schema, + table=table, + index_name=name, + classification=kind, + index_repair_pending=bool(doc.get("index_repair_pending")), + index_repair_error=doc.get("index_repair_error"), + physical_ready=readiness.get(name, False), + physical_state=( + "missing" + if actual is None + else "ready" if readiness[name] else "invalid" + ), + can_delete=kind == "secondary" and (actual is None or owns(entry, actual)), + ) + if entry: + row["target_sql"] = parse_index(entry["sql"]).render(schema, table) + if actual: + row["index_definition"] = actual.definition + if entry and not owns(entry, actual): + row.update( + physical_state="unmanaged", physical_ready=False, can_delete=False + ) + result.append(row) + return result diff --git a/pyproject.toml b/pyproject.toml index d1b8c07..701ed26 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -17,6 +17,8 @@ classifiers = [ "Programming Language :: Python :: 3.12", ] dependencies = [ + "pglast>=7.23,<8", + "psycopg2-binary>=2.9.9,<3", "cryptography==44.0.2", "flask-restx==1.2.0", "inject==5.0.0", diff --git a/tests/test_index_creation_modes.py b/tests/test_index_creation_modes.py new file mode 100644 index 0000000..06e4dbd --- /dev/null +++ b/tests/test_index_creation_modes.py @@ -0,0 +1,240 @@ +"""I04 mode, timeout and checkpoint contracts on disposable PostgreSQL/MongoDB.""" +from contextlib import contextmanager +import os +import time +from types import SimpleNamespace +import unittest +from unittest.mock import patch +from uuid import uuid4 + +from ddp_lib.dataset_indexes import DatasetIndexes +from ddp_lib.enums import IndexCreationMode +from ddp_lib.index_metadata import begin_data, data_committed, save_intent +from ddp_lib.postgres_indexes import inspect_index +from ddp_lib.secondary_indexes import IndexRepairError, owns + + +@unittest.skipUnless(os.getenv('QUEUE_TEST_POSTGRES_DSN') and os.getenv('QUEUE_TEST_MONGO_URI'), + 'Set QUEUE_TEST_POSTGRES_DSN and QUEUE_TEST_MONGO_URI to disposable databases') +class CreationModeTests(unittest.TestCase): + def setUp(self): + import psycopg2 + from psycopg2 import extensions + from pymongo import MongoClient + self.events = [] + test = self + + class Cursor(extensions.cursor): + def execute(self, statement, parameters=None): + sql = statement if isinstance(statement, str) else statement.as_string(self) + test.events.append((sql, parameters)) + return super().execute(statement, parameters) + + self.connect = lambda: psycopg2.connect(os.environ['QUEUE_TEST_POSTGRES_DSN'], cursor_factory=Cursor) + self.connection = self.connect() + self.connection.autocommit = True + self.cursor = self.connection.cursor() + self.schema = 'i04_' + uuid4().hex[:12] + self.cursor.execute(f'CREATE SCHEMA "{self.schema}"') + self.cursor.execute(f'CREATE TABLE "{self.schema}".data (id int, value text)') + self.cursor.execute(f'INSERT INTO "{self.schema}".data VALUES (1, \'committed\')') + self.cursor.execute(f'CREATE TABLE "{self.schema}".unrelated (id int)') + self.client = MongoClient(os.environ['QUEUE_TEST_MONGO_URI']) + self.db = self.client['i04_' + uuid4().hex] + self.collection = self.db.references + self.collection.insert_one({'_id': 'target', 'data_mart_schema': self.schema, 'table_name': 'data'}) + self.manager = DatasetIndexes(self.db, lambda schema: SimpleNamespace(get_connection=self.connect), + lambda doc: doc['data_mart_schema']) + self.target = self.manager.get('REFERENCE', 'target') + timeout = patch.dict(os.environ, INDEX_LOCK_TIMEOUT='200ms', INDEX_STATEMENT_TIMEOUT='3s') + timeout.start() + self.addCleanup(timeout.stop) + + def tearDown(self): + self.cursor.execute(f'DROP SCHEMA "{self.schema}" CASCADE') + self.cursor.close() + self.connection.close() + self.client.drop_database(self.db.name) + self.client.close() + + def sql(self, name='idx'): + return f'CREATE INDEX CONCURRENTLY "{name}" ON "{self.schema}".data ((lower(value)))' + + def save(self): + return save_intent(self.collection, 'target', self.schema, 'data', self.sql()) + + def checkpoint(self): + begin_data(self.collection, 'target', 'committed-attempt') + data_committed(self.collection, 'target', 'committed-attempt') + + def physical(self): + return inspect_index(self.cursor, self.schema, 'idx') + + @contextmanager + def old_snapshot(self): + reader = self.connect() + try: + reader.set_session(isolation_level='REPEATABLE READ', readonly=True) + with reader.cursor() as cursor: + cursor.execute(f'SELECT * FROM "{self.schema}".unrelated') + cursor.fetchall() + yield reader + finally: + reader.close() + + def creates(self): + return [sql for sql, _ in self.events if sql.startswith('CREATE INDEX') + and f'ON "{self.schema}"."data"' in sql] + + def test_I04_A_post_load_restores_source_and_secondary_under_old_snapshot(self): + self.save() + self.collection.update_one({'_id': 'target'}, {'$set': {'source_indexes': [{'columns': ['id']}]}}) + self.checkpoint() + with self.old_snapshot(): + result = self.manager.reconcile(self.target, mode=IndexCreationMode.POST_LOAD.value) + self.assertTrue(result.ready) + self.assertEqual(result.applied, 2) + self.assertTrue(self.physical().valid and self.physical().ready) + self.assertEqual(len(self.creates()), 2) + self.assertTrue(all('CONCURRENTLY' not in sql for sql in self.creates())) + self.assertFalse(self.collection.find_one()['index_repair_pending']) + + def test_I04_B_owned_invalid_build_repairs_committed_data_under_old_snapshot(self): + entry = self.save() + self.checkpoint() + self.cursor.execute(f'SELECT ctid::text, * FROM "{self.schema}".data') + before = self.cursor.fetchall() + with self.old_snapshot(): + # Positive control: online CREATE really waits on this unrelated + # snapshot, times out, and leaves an invalid index with a receipt. + with self.assertRaises(IndexRepairError): + self.manager.reconcile(self.target) + invalid = self.physical() + self.assertFalse(invalid.valid) + self.assertTrue(invalid.ready) + self.assertTrue(owns(entry, invalid)) + self.events.clear() + self.assertTrue(self.manager.repair(self.target).ready) + self.assertTrue(self.physical().valid and self.physical().ready) + self.assertNotEqual(invalid.oid, self.physical().oid) + self.assertEqual(len(self.creates()), 1) + self.assertNotIn('CONCURRENTLY', self.creates()[0]) + self.assertTrue(any(sql.startswith('DROP INDEX CONCURRENTLY') for sql, _ in self.events)) + self.cursor.execute(f'SELECT ctid::text, * FROM "{self.schema}".data') + self.assertEqual(self.cursor.fetchall(), before) + self.assertEqual(self.collection.find_one()['index_data_token'], 'committed-attempt') + + def test_I04_C_online_requests_remain_concurrent_even_with_old_checkpoint(self): + self.checkpoint() + self.manager.create(self.target, self.sql().replace('CONCURRENTLY ', ''), {}) + self.assertEqual(len(self.creates()), 1) + self.assertIn('CONCURRENTLY', self.creates()[0]) + self.cursor.execute(f'CREATE MATERIALIZED VIEW "{self.schema}".view_data AS SELECT * FROM "{self.schema}".data') + self.db.populations.insert_one({'_id': 'view', 'schema': self.schema, 'table_name': 'view_data'}) + target = self.manager.get('POPULATION', 'view') + sql = f'CREATE INDEX view_idx ON "{self.schema}".view_data (id)' + self.manager.create(target, sql, {}) + self.assertTrue(any(s.startswith('CREATE INDEX CONCURRENTLY "view_idx"') for s, _ in self.events)) + + def test_I04_D_partition_parent_uses_ordinary_ddl_and_attached_children(self): + self.cursor.execute(f'DROP TABLE "{self.schema}".data') + self.cursor.execute(f'CREATE TABLE "{self.schema}".data(id int, value text) PARTITION BY RANGE(id)') + for name, start, end in [('part_a', 0, 10), ('part_b', 10, 20)]: + self.cursor.execute(f'CREATE TABLE "{self.schema}".{name} PARTITION OF "{self.schema}".data FOR VALUES FROM ({start}) TO ({end})') + self.manager.create(self.target, self.sql(), {}) + self.assertNotIn('CONCURRENTLY', self.creates()[0]) + self.assertTrue(self.physical().valid and self.physical().ready) + self.cursor.execute('''SELECT count(*) FROM pg_inherits h JOIN pg_index i ON i.indexrelid=h.inhrelid + WHERE h.inhparent=%s AND i.indisvalid AND i.indisready''', (self.physical().oid,)) + self.assertEqual(self.cursor.fetchone()[0], 2) + + def test_I04_E_target_writer_timeouts_preserve_intent_and_allow_retry(self): + entry = self.save() + self.checkpoint() + writer = self.connect() + try: + with writer.cursor() as cursor: + cursor.execute(f'INSERT INTO "{self.schema}".data VALUES (2, \'uncommitted\')') + for lock, statement, message in [('150ms', '3s', 'lock timeout'), ('3s', '150ms', 'statement timeout')]: + with self.subTest(timeout=message), patch.dict(os.environ, + INDEX_LOCK_TIMEOUT=lock, INDEX_STATEMENT_TIMEOUT=statement): + started = time.monotonic() + with self.assertRaisesRegex(IndexRepairError, message) as caught: + self.manager.reconcile(self.target, mode=IndexCreationMode.POST_LOAD.value) + self.assertLess(time.monotonic() - started, 2) + self.assertFalse(caught.exception.result.ready) + document = self.collection.find_one() + current = document['secondary_indexes'][0] + self.assertEqual((current['id'], current['revision'], current['desired_state']), + (entry['id'], entry['revision'], 'present')) + self.assertEqual(current['status'], 'error') + self.assertTrue(document['index_repair_pending'] and document['index_data_ready']) + self.assertFalse(document['indexes_applied']) + self.assertIsNone(self.physical()) + finally: + writer.close() + self.assertTrue(self.manager.repair(self.target).ready) + self.assertFalse(self.collection.find_one()['index_repair_pending']) + + def test_manual_repair_cannot_invent_or_use_an_uncommitted_checkpoint(self): + self.save() + with self.assertRaisesRegex(IndexRepairError, 'committed data checkpoint'): + self.manager.reconcile(self.target, mode=IndexCreationMode.POST_LOAD.value) + self.assertFalse(self.creates()) + self.assertTrue(self.manager.repair(self.target).ready) + self.assertIn('CONCURRENTLY', self.creates()[0]) + self.assertNotIn('index_data_ready', self.collection.find_one()) + self.checkpoint() + stale_target = self.manager.get('REFERENCE', 'target') + begin_data(self.collection, 'target', 'new-attempt') + self.events.clear() + with self.assertRaisesRegex(IndexRepairError, 'has not committed'): + self.manager.repair(stale_target) + with self.assertRaisesRegex(IndexRepairError, 'committed data checkpoint'): + self.manager.reconcile(stale_target, mode=IndexCreationMode.POST_LOAD.value) + self.assertFalse(self.creates()) + self.assertFalse(self.collection.find_one()['index_data_ready']) + + def test_timeouts_apply_on_each_borrowed_connection_before_any_ddl(self): + self.save() + with patch.dict(os.environ): + os.environ.pop('INDEX_LOCK_TIMEOUT', None) + os.environ.pop('INDEX_STATEMENT_TIMEOUT', None) + for mode, lock, statement in [ + (IndexCreationMode.ONLINE.value, '5s', '30min'), + (IndexCreationMode.POST_LOAD.value, '700ms', '4s'), + ]: + if mode == IndexCreationMode.POST_LOAD.value: + self.checkpoint() + os.environ.update(INDEX_LOCK_TIMEOUT=lock, INDEX_STATEMENT_TIMEOUT=statement) + self.cursor.execute(f'DROP INDEX "{self.schema}".idx') + self.events.clear() + self.manager.reconcile(self.target, self.connection, mode=mode) + lock_event = ('SET lock_timeout = %s', (lock,)) + statement_event = ('SET statement_timeout = %s', (statement,)) + first_ddl = next(i for i, (sql, _) in enumerate(self.events) if sql.startswith('CREATE ')) + self.assertLess(self.events.index(lock_event), first_ddl) + self.assertLess(self.events.index(statement_event), first_ddl) + self.assertFalse(self.connection.closed) + + def test_borrowed_connection_rechecks_checkpoint_after_acquiring_guard(self): + self.save() + self.checkpoint() + original = self.manager.guard + + @contextmanager + def newer_attempt(target, connection=None): + with original(target, connection) as guarded: + begin_data(self.collection, 'target', 'new-attempt') + yield guarded + + with patch.object(self.manager, 'guard', side_effect=newer_attempt): + with self.assertRaisesRegex(IndexRepairError, 'committed data checkpoint'): + self.manager.reconcile(self.target, self.connection, mode=IndexCreationMode.POST_LOAD.value) + self.assertFalse(self.creates()) + self.assertFalse(self.connection.closed) + self.assertFalse(self.collection.find_one()['index_data_ready']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_reload_indexes.py b/tests/test_reload_indexes.py new file mode 100644 index 0000000..68d2048 --- /dev/null +++ b/tests/test_reload_indexes.py @@ -0,0 +1,161 @@ +"""Canonical preparation, ownership and rollback on disposable databases.""" + +from contextlib import contextmanager +import os +import unittest +from unittest.mock import patch +from types import SimpleNamespace + +import test_index_creation_modes as modes +from ddp_lib import secondary_indexes as lifecycle +from ddp_lib.index_metadata import begin_data, save_intent, IndexConflict +from ddp_lib.postgres_indexes import inspect_index + + +@unittest.skipUnless( + os.getenv("QUEUE_TEST_POSTGRES_DSN") and os.getenv("QUEUE_TEST_MONGO_URI"), + "Set PostgreSQL and MongoDB test connection variables", +) +class ReloadTests(unittest.TestCase): + setUp = modes.CreationModeTests.setUp + tearDown = modes.CreationModeTests.tearDown + sql = modes.CreationModeTests.sql + save = modes.CreationModeTests.save + physical = modes.CreationModeTests.physical + + def prepare(self, target=None): + target = target or self.target + begin_data(self.collection, target.id, "attempt") + connection = self.connect() + try: + result = self.manager.prepare_reload(target, connection, "attempt") + connection.commit() + return result + finally: + connection.close() + + def test_constraint_primary_and_unmanaged_indexes_keep_oids(self): + self.cursor.execute(f'ALTER TABLE "{self.schema}".data ADD PRIMARY KEY (id)') + self.cursor.execute( + f'ALTER TABLE "{self.schema}".data ADD CONSTRAINT uq UNIQUE(value)' + ) + self.cursor.execute( + f'CREATE INDEX unmanaged ON "{self.schema}".data (id, value)' + ) + for name, column in [("data_pkey", "id"), ("uq", "value")]: + save_intent( + self.collection, + "target", + self.schema, + "data", + f'CREATE UNIQUE INDEX {name} ON "{self.schema}".data ({column})', + ) + before = { + n: inspect_index(self.cursor, self.schema, n).oid + for n in ("data_pkey", "uq", "unmanaged") + } + self.assertEqual(self.prepare().dropped, ()) + self.assertEqual( + {n: inspect_index(self.cursor, self.schema, n).oid for n in before}, before + ) + + def test_partition_parent_and_attached_child_never_dropped(self): + self.cursor.execute(f'DROP TABLE "{self.schema}".data') + self.cursor.execute( + f'CREATE TABLE "{self.schema}".data(id int, value text) PARTITION BY RANGE(id)' + ) + self.cursor.execute( + f'CREATE TABLE "{self.schema}".leaf PARTITION OF "{self.schema}".data FOR VALUES FROM (0) TO (10)' + ) + self.manager.create(self.target, self.sql(), {}) + parent = self.physical() + self.cursor.execute( + "SELECT c.relname FROM pg_inherits h JOIN pg_class c ON c.oid=h.inhrelid WHERE h.inhparent=%s", + (parent.oid,), + ) + name = self.cursor.fetchone()[0] + child = inspect_index(self.cursor, self.schema, name) + self.assertEqual(self.prepare().dropped, ()) + self.collection.insert_one( + {"_id": "leaf", "data_mart_schema": self.schema, "table_name": "leaf"} + ) + save_intent( + self.collection, "leaf", self.schema, "leaf", child.definition, adopt=True + ) + self.assertEqual( + self.prepare(self.manager.get("REFERENCE", "leaf")).dropped, () + ) + self.assertEqual(self.physical().oid, parent.oid) + self.assertEqual(inspect_index(self.cursor, self.schema, name).oid, child.oid) + + def test_revision_cas_failure_prevents_drop(self): + from pymongo.collection import Collection + + self.save() + self.manager.reconcile(self.target) + before = self.physical().oid + original = Collection.update_one + + def race(collection, query, update, *args, **kwargs): + if "index_reload" in update.get("$set", {}): + return SimpleNamespace(matched_count=0) + return original(collection, query, update, *args, **kwargs) + + self.events.clear() + with ( + patch.object(Collection, "update_one", new=race), + self.assertRaisesRegex(IndexConflict, "definitions changed"), + ): + self.prepare() + self.assertEqual(self.physical().oid, before) + self.assertFalse(any(sql.startswith("DROP INDEX") for sql, _ in self.events)) + + def test_late_reconciliation_error_does_not_mark_newer_data_broken(self): + self.save() + begin_data(self.collection, "target", "attempt-A") + original = lifecycle.dataset_session + + @contextmanager + def delayed(*args, **kwargs): + with original(*args, **kwargs) as connection: + yield connection + # New ownership starts after A releases the dataset lock. + self.collection.update_one( + {"_id": "target"}, + { + "$set": { + "index_data_token": "attempt-B", + "index_data_ready": False, + "index_repair_error": None, + "index_repair_pending": False, + } + }, + ) + raise RuntimeError("delayed worker A error") + + with ( + patch.object(lifecycle, "dataset_session", delayed), + self.assertRaises(lifecycle.IndexRepairError), + ): + lifecycle.reconcile( + self.collection, "target", self.schema, "data", self.connect + ) + current = self.collection.find_one() + self.assertEqual(current["index_data_token"], "attempt-B") + self.assertIsNone(current["index_repair_error"]) + self.assertFalse(current["index_repair_pending"]) + + def test_temporary_removal_rejects_autocommit_and_wrong_token(self): + with self.assertRaisesRegex(ValueError, "publication transaction"): + self.manager.prepare_reload(self.target, self.connection, "attempt") + connection = self.connect() + try: + begin_data(self.collection, "target", "newer") + with self.assertRaises(IndexConflict): + self.manager.prepare_reload(self.target, connection, "old") + finally: + connection.close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_secondary_indexes.py b/tests/test_secondary_indexes.py new file mode 100644 index 0000000..1cfb927 --- /dev/null +++ b/tests/test_secondary_indexes.py @@ -0,0 +1,359 @@ +"""I01 contracts against disposable PostgreSQL/MongoDB, not donor mocks.""" +import os +import threading +import unittest +from unittest.mock import patch +from uuid import uuid4 + +from ddp_lib.index_sql import parse_index +from ddp_lib.index_metadata import (IndexConflict, save_intent, delete_intent, record_result, + editable_fields, begin_data, data_committed) + + +class ParserTests(unittest.TestCase): + def test_I01_E_rejects_multiple_wrong_grammar_and_truncation(self): + for statement in [ + 'CREATE INDEX i ON s.t (id); DROP TABLE s.t', 'DROP INDEX s.i', + 'CREATE INDEX i ON t (id)', 'CREATE INDEX i ON s.t', + 'CREATE INDEX ' + 'a'*64 + ' ON s.t (id)', + 'CREATE INDEX "' + 'é'*32 + '" ON s.t (id)', + 'CREATE INDEX i ON s.t ("' + 'a'*64 + '")', + ]: + with self.subTest(statement=statement), self.assertRaises(ValueError): + parse_index(statement) + + def test_I01_F_preserves_literals_expressions_order_and_only(self): + sql = 'CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS "Name" ON ONLY "My Schema"."Table" ((lower("Name")), id DESC) INCLUDE (value) WHERE value = \'a b\'' + definition = parse_index(sql) + replay = definition.render('new schema', 'renamed') + self.assertIn("'a b'", replay) + self.assertIn('lower("Name")', replay) + self.assertIn('ON ONLY "new schema"."renamed"', replay) + self.assertEqual(definition.signature, parse_index(replay).signature) + self.assertNotEqual(definition.signature, parse_index(sql.replace('a b', 'a b')).signature) + + def test_I01_C_protected_dotted_paths(self): + fields = {'_id': 'evil', 'secondary_indexes.0.sql': 'evil', 'index_data_ready': True, + 'index_data_token.x': 'evil', 'index_repair_error': None, 'name': 'new'} + self.assertEqual(editable_fields('references', fields), {'name': 'new'}) + + +@unittest.skipUnless(os.getenv('QUEUE_TEST_POSTGRES_DSN') and os.getenv('QUEUE_TEST_MONGO_URI'), + 'Set QUEUE_TEST_POSTGRES_DSN and QUEUE_TEST_MONGO_URI to disposable databases') +class LifecycleTests(unittest.TestCase): + def setUp(self): + import psycopg2 + from pymongo import MongoClient + from ddp_lib import secondary_indexes + self.life = secondary_indexes + self.client = MongoClient(os.environ['QUEUE_TEST_MONGO_URI']) + self.db = self.client['kan20_' + uuid4().hex] + self.collection = self.db.populations + self.schema = 'kan20_' + uuid4().hex[:12] + self.collection.insert_one({'_id': 'target', 'schema': self.schema, 'table_name': 'data'}) + self.connect = lambda: psycopg2.connect(os.environ['QUEUE_TEST_POSTGRES_DSN']) + self.connection = self.connect() + self.connection.autocommit = True + self.cursor = self.connection.cursor() + self.cursor.execute(f'CREATE SCHEMA "{self.schema}"') + self.cursor.execute(f'CREATE TABLE "{self.schema}".data (id int, value text, "Name" text)') + + def tearDown(self): + self.cursor.execute(f'DROP SCHEMA "{self.schema}" CASCADE') + self.cursor.close() + self.connection.close() + self.client.drop_database(self.db.name) + self.client.close() + + def sql(self, name='idx', body='(id)', unique=False): + return f'CREATE {"UNIQUE " if unique else ""}INDEX CONCURRENTLY "{name}" ON "{self.schema}".data {body}' + + def save(self, sql=None, **options): + return save_intent(self.collection, 'target', self.schema, 'data', sql or self.sql(), **options) + + def run_indexes(self): + return self.life.reconcile(self.collection, 'target', self.schema, 'data', self.connect) + + def physical(self, name='idx'): + from ddp_lib.postgres_indexes import inspect_index + return inspect_index(self.cursor, self.schema, name) + + def test_I01_A_B_restore_definition_and_keep_tombstone_across_two_rebuilds(self): + entry = self.save(self.sql(body='((lower("Name")), id DESC) INCLUDE (value) WHERE value = \'a b\'')) + self.run_indexes() + original = self.physical().definition + for _ in range(2): + self.cursor.execute(f'DROP TABLE "{self.schema}".data') + self.cursor.execute(f'CREATE TABLE "{self.schema}".data (id int, value text, "Name" text)') + self.run_indexes() + self.assertEqual(self.physical().definition, original) + self.assertTrue(self.physical().valid and self.physical().ready) + delete_intent(self.collection, 'target', self.schema, 'idx') + self.run_indexes() + for _ in range(2): + self.cursor.execute(f'DROP TABLE "{self.schema}".data') + self.cursor.execute(f'CREATE TABLE "{self.schema}".data (id int, value text, "Name" text)') + self.run_indexes() + self.assertIsNone(self.physical()) + tombstone = self.collection.find_one()['secondary_indexes'][0] + self.assertEqual((tombstone['id'], tombstone['desired_state'], tombstone['revision']), (entry['id'], 'absent', 2)) + + def test_I01_D_result_revision_and_legacy_counter_are_fenced(self): + created = self.save() + deleted = delete_intent(self.collection, 'target', self.schema, 'idx') + self.assertFalse(record_result(self.collection, 'target', created['id'], created['revision'], {'status': 'created'})) + self.assertEqual(self.collection.find_one()['secondary_indexes'][0]['revision'], deleted['revision']) + recreated = self.save() + self.assertEqual(recreated['revision'], 3) + self.assertEqual(self.save()['revision'], 3) + + def test_I01_D_concurrent_requests_and_mutation_during_ddl(self): + barrier = threading.Barrier(8) + errors = [] + def create(i): + try: + barrier.wait() + self.save(self.sql(name='idx' + str(i))) + except Exception as exc: + errors.append(exc) + threads = [threading.Thread(target=create, args=(i,)) for i in range(8)] + for thread in threads: thread.start() + for thread in threads: thread.join() + self.assertFalse(errors) + self.assertEqual(len(self.collection.find_one()['secondary_indexes']), 8) + original = self.life.apply_entry + def delayed(cursor, entry, *args, **kwargs): + result = original(cursor, entry, *args, **kwargs) + delete_intent(self.collection, 'target', self.schema, entry['index_name']) + return result + with patch.object(self.life, 'apply_entry', side_effect=delayed), self.assertRaises(self.life.IndexRepairError): + self.run_indexes() + self.assertTrue(all(e['desired_state'] == 'absent' for e in self.collection.find_one()['secondary_indexes'])) + self.run_indexes() + self.assertIsNone(self.physical('idx0')) + + def test_I01_E_wrong_target_and_definition_conflict_have_no_ddl(self): + with self.assertRaises(ValueError): + self.save('CREATE INDEX idx ON wrong.table (id)') + self.save() + with self.assertRaises(IndexConflict): + self.save(self.sql(body='(value)')) + self.assertIsNone(self.physical()) + + def test_I01_G_unmanaged_constraint_and_other_table_are_not_taken_over(self): + self.cursor.execute(self.sql()) + oid = self.physical().oid + self.save() + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + self.assertEqual(self.physical().oid, oid) + delete_intent(self.collection, 'target', self.schema, 'idx') + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + self.assertEqual(self.physical().oid, oid) + + def test_saved_constraints_do_not_block_other_indexes_or_get_dropped(self): + self.cursor.execute(f'ALTER TABLE "{self.schema}".data ADD CONSTRAINT primary_idx PRIMARY KEY (id)') + self.cursor.execute(f'ALTER TABLE "{self.schema}".data ADD CONSTRAINT unique_idx UNIQUE (value)') + oids = {name: self.physical(name).oid for name in ('primary_idx', 'unique_idx')} + for name in oids: + self.save(self.sql(name, unique=True), adopt=True) + self.save() + self.assertTrue(self.run_indexes().ready) + self.assertTrue(self.physical().valid) + entries = {e['index_name']: e for e in self.collection.find_one()['secondary_indexes']} + for name, oid in oids.items(): + self.assertEqual(entries[name]['status'], 'error') + self.assertIn(name, entries[name]['last_error']) + self.assertEqual(self.physical(name).oid, oid) + delete_intent(self.collection, 'target', self.schema, name) + self.assertTrue(self.run_indexes().ready) + for name, oid in oids.items(): + self.assertEqual(self.physical(name).oid, oid) + self.assertTrue(self.physical(name).constraint_owned) + + def test_create_rejects_constraint_names_before_saving(self): + from ddp_lib.dataset_indexes import DatasetIndexes + from types import SimpleNamespace + self.cursor.execute(f'ALTER TABLE "{self.schema}".data ADD CONSTRAINT primary_idx PRIMARY KEY (id)') + self.cursor.execute(f'ALTER TABLE "{self.schema}".data ADD CONSTRAINT unique_idx UNIQUE (value)') + manager = DatasetIndexes(self.db, lambda schema: SimpleNamespace(get_connection=self.connect), + lambda doc: doc['data_mart_schema']) + target = manager.get('POPULATION', 'target') + before = self.collection.find_one() + for name in ('primary_idx', 'unique_idx'): + oid = self.physical(name).oid + with self.assertRaisesRegex(IndexConflict, name): + manager.create(target, self.sql(name, unique=True), {}) + self.assertEqual(self.collection.find_one(), before) + self.assertEqual(self.physical(name).oid, oid) + + def test_other_table_constraint_remains_a_conflict(self): + self.cursor.execute(f'CREATE TABLE "{self.schema}".other (id int CONSTRAINT other_pkey PRIMARY KEY)') + oid = self.physical('other_pkey').oid + self.save(self.sql('other_pkey')) + for state in ('present', 'absent'): + if state == 'absent': + delete_intent(self.collection, 'target', self.schema, 'other_pkey') + with self.assertRaisesRegex(self.life.IndexRepairError, + 'other_pkey: Index name is occupied by another relation'): + self.run_indexes() + self.assertEqual(self.physical('other_pkey').oid, oid) + + def test_source_constraint_still_fails_reconciliation(self): + self.cursor.execute(f'ALTER TABLE "{self.schema}".data ADD CONSTRAINT primary_idx PRIMARY KEY (id)') + oid = self.physical('primary_idx').oid + source = {'id': 'source:test', 'index_name': 'primary_idx', + 'sql': self.sql('primary_idx', unique=True), 'desired_state': 'present', + 'revision': 1, 'adopt': False} + with self.assertRaisesRegex(self.life.IndexRepairError, 'primary_idx'): + self.life.reconcile(self.collection, 'target', self.schema, 'data', self.connect, + source_entries=[source]) + self.assertEqual(self.physical('primary_idx').oid, oid) + self.assertTrue(self.collection.find_one()['index_repair_pending']) + + def test_I01_G_explicit_adoption_verifies_and_preserves_comment(self): + self.cursor.execute(self.sql()) + self.cursor.execute(f'COMMENT ON INDEX "{self.schema}".idx IS %s', ('organization:{"owner":"ops"}',)) + self.save(adopt=True) + self.run_indexes() + self.assertTrue(self.physical().comment.startswith('organization:{"owner":"ops"}\n')) + self.assertFalse(self.collection.find_one()['secondary_indexes'][0]['adopt']) + self.cursor.execute(f'DROP INDEX "{self.schema}".idx') + self.cursor.execute(self.sql()) + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + + def test_I01_H_receipt_recovers_metadata_outage_but_missing_receipt_requires_review(self): + self.save() + with patch.object(self.life, 'record_result', side_effect=RuntimeError('Mongo unavailable')): + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + self.assertIn('[ddp-index:v1:', self.physical().comment) + self.run_indexes() + self.assertEqual(self.collection.find_one()['secondary_indexes'][0]['status'], 'created') + self.cursor.execute(f'COMMENT ON INDEX "{self.schema}".idx IS NULL') + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + + def test_I01_H_failed_unique_build_gets_receipt_and_repairs(self): + self.cursor.execute(f'INSERT INTO "{self.schema}".data(id) VALUES(1),(1)') + self.save(self.sql(unique=True)) + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + self.assertFalse(self.physical().valid) + self.assertIn('[ddp-index:v1:', self.physical().comment) + self.cursor.execute(f'DELETE FROM "{self.schema}".data WHERE ctid IN (SELECT ctid FROM "{self.schema}".data LIMIT 1)') + self.run_indexes() + self.assertTrue(self.physical().valid) + + def test_I01_I_dataset_and_name_contention_close_connections(self): + from ddp_lib.postgres_indexes import advisory_lock + self.save() + for key in [f'ddp-index:v1:dataset:{self.collection.full_name}:target', f'ddp-index:v1:name:{self.schema}:idx']: + opened = [] + def connect(): + conn = self.connect(); opened.append(conn); return conn + with advisory_lock(self.connection, key): + with self.assertRaises(self.life.IndexRepairError): + self.life.reconcile(self.collection, 'target', self.schema, 'data', connect) + self.assertTrue(opened and all(c.closed for c in opened)) + self.run_indexes() + + def test_supplied_ddl_connection_obeys_dataset_lock_and_is_not_closed(self): + from ddp_lib.postgres_indexes import advisory_lock, IndexLockBusy + self.save() + borrowed = self.connect() + try: + with self.assertRaises(ValueError): + self.life.reconcile(self.collection, 'target', self.schema, 'data', self.connect, borrowed) + borrowed.autocommit = True + with advisory_lock(self.connection, f'ddp-index:v1:dataset:{self.collection.full_name}:target'): + with self.assertRaises(IndexLockBusy): + self.life.reconcile(self.collection, 'target', self.schema, 'data', self.connect, borrowed) + self.assertFalse(borrowed.closed) + self.life.reconcile(self.collection, 'target', self.schema, 'data', self.connect, borrowed) + self.assertFalse(borrowed.closed) + self.assertTrue(self.physical().valid) + finally: + borrowed.close() + + def test_checkpoint_and_completion_cas_do_not_claim_data_success(self): + begin_data(self.collection, 'target', 'attempt') + self.save() + self.run_indexes() + self.assertFalse(self.collection.find_one()['index_data_ready']) + self.assertTrue(self.collection.find_one()['index_repair_pending']) + with self.assertRaises(IndexConflict): data_committed(self.collection, 'target', 'old') + data_committed(self.collection, 'target', 'attempt') + self.run_indexes() + self.assertFalse(self.collection.find_one()['index_repair_pending']) + + def test_I01_F_rebind_rename_without_rewriting_literal_or_expression(self): + self.save(self.sql(body="((lower(value))) WHERE value = 'a b'")) + self.run_indexes() + self.cursor.execute(f'ALTER TABLE "{self.schema}".data RENAME TO renamed') + self.life.reconcile(self.collection, 'target', self.schema, 'renamed', self.connect) + entry = self.collection.find_one()['secondary_indexes'][0] + self.assertIn("'a b'", entry['sql']) + self.assertEqual(entry['table'], 'renamed') + self.assertTrue(self.physical().valid) + + def test_unicode_identifiers_and_dollar_quoted_literal_are_replayed(self): + self.save(self.sql('indice_é', "((value || $$two spaces;$$))")) + self.run_indexes() + self.assertTrue(self.physical('indice_é').valid) + self.assertIn('two spaces;', self.physical('indice_é').definition) + + def test_invalid_partition_parent_requires_attachment_review(self): + self.cursor.execute(f'DROP TABLE "{self.schema}".data') + self.cursor.execute(f'CREATE TABLE "{self.schema}".data(id int) PARTITION BY RANGE(id)') + self.cursor.execute(f'CREATE TABLE "{self.schema}".part PARTITION OF "{self.schema}".data FOR VALUES FROM(0) TO(10)') + self.save(self.sql().replace('ON ', 'ON ONLY ')) + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + oid = self.physical().oid + with self.assertRaisesRegex(self.life.IndexRepairError, 'attachment review'): self.run_indexes() + self.assertEqual(self.physical().oid, oid) + + def test_I01_G_source_policy_classification_and_secondary_delete_rejection(self): + from ddp_lib.dataset_indexes import DatasetIndexes + from types import SimpleNamespace + self.collection.delete_many({}) + self.db.references.insert_one({'_id': 'ref', 'data_mart_schema': self.schema, + 'table_name': 'data', 'source_indexes': [{'columns': ['id']}]}) + self.cursor.execute(self.sql('historic_source')) + manager = DatasetIndexes(self.db, lambda schema: SimpleNamespace(get_connection=self.connect), + lambda doc: doc['data_mart_schema']) + target = manager.get('REFERENCE', 'ref') + self.assertEqual(manager.listing(target)[0]['classification'], 'source') + with self.assertRaises(IndexConflict): manager.delete(target, 'historic_source') + with self.assertRaises(IndexConflict): manager.create(target, self.sql('historic_source'), {}) + with self.assertRaises(self.life.IndexRepairError): manager.reconcile(target) + self.assertIsNone(self.physical('historic_source').comment) + + def test_duplicate_physical_metadata_owners_block_lifecycle(self): + from ddp_lib.dataset_indexes import DatasetIndexes + self.db.references.insert_one({'_id':'other', 'data_mart_schema':self.schema, 'table_name':'data'}) + manager = DatasetIndexes(self.db, None, lambda doc: doc['data_mart_schema']) + with self.assertRaisesRegex(IndexConflict, 'Duplicate'): + manager.get('POPULATION', 'target') + + def test_completion_cas_cannot_clear_newer_request(self): + self.save() + real_update = self.collection.update_one + inserted = [] + def racing_update(query, update, **kwargs): + if update.get('$set', {}).get('index_repair_pending') is False and not inserted: + inserted.append(True) + self.save(self.sql('newer')) + return real_update(query, update, **kwargs) + with patch.object(self.collection, 'update_one', side_effect=racing_update): + with self.assertRaises(self.life.IndexRepairError): self.run_indexes() + self.assertTrue(self.collection.find_one()['index_repair_pending']) + self.assertIsNone(self.physical('newer')) + self.run_indexes() + + def test_legacy_import_does_not_recreate_a_newer_tombstone(self): + entry = self.save() + delete_intent(self.collection, 'target', self.schema, 'idx') + result = save_intent(self.collection, 'target', self.schema, 'data', self.sql(), only_if_missing=True) + self.assertEqual(result['desired_state'], 'absent') + self.assertEqual(result['id'], entry['id']) + + +if __name__ == '__main__': + unittest.main() diff --git a/tests/test_source_indexes.py b/tests/test_source_indexes.py new file mode 100644 index 0000000..3ee182d --- /dev/null +++ b/tests/test_source_indexes.py @@ -0,0 +1,325 @@ +"""I07 saved source policy contracts; database cases use disposable PG/Mongo.""" + +import copy +import os +import unittest +from dataclasses import replace +from types import SimpleNamespace +from uuid import uuid4 + +from ddp_lib.dataset_indexes import Dataset, DatasetIndexes, source_entries +from ddp_lib.index_metadata import IndexConflict, save_intent, delete_intent +from ddp_lib.index_sql import parse_index +from ddp_lib.postgres_indexes import inspect_index, index_ready, list_indexes +from ddp_lib.secondary_indexes import IndexRepairError, apply_entry, owns + + +def target(policies, secondary=()): + return Dataset( + "REFERENCE", + None, + { + "_id": "reference", + "source_indexes": policies, + "secondary_indexes": list(secondary), + }, + "schema", + "table", + ) + + +class SourcePolicyTests(unittest.TestCase): + def test_I07_D_collisions_duplicates_and_order_have_stable_names(self): + policies = [ + {"columns": ["a_b", "c"]}, + {"columns": ["a", "b_c"]}, + {"columns": ["A", "B"]}, + {"columns": ["a", "b"]}, + {"columns": ["b", "a"]}, + {"columns": ["a", "b"], "unique": True}, + ] + first = source_entries(target(policies)) + second = source_entries(target(list(reversed(policies)) + [policies[0]])) + self.assertEqual( + {e["id"]: e["index_name"] for e in first}, + {e["id"]: e["index_name"] for e in second}, + ) + self.assertEqual(len({e["index_name"] for e in first}), len(policies)) + self.assertEqual(len(second), len(first)) + + def test_short_names_and_existing_long_name_identity_are_preserved(self): + self.assertEqual( + source_entries(target([{"columns": ["id"]}]))[0]["index_name"], + "idx_schema_table_id", + ) + policies = [{"columns": ["x" * 60]}, {"columns": ["x" * 59 + "y"]}] + first = source_entries(target(policies)) + self.assertEqual(first, source_entries(target(policies))) + self.assertEqual(len({e["index_name"] for e in first}), 2) + self.assertTrue(all(len(e["index_name"].encode()) <= 63 for e in first)) + + def test_exact_keys_are_not_trimmed_or_lowercased(self): + entries = source_entries( + target([{"columns": [" ID ", 'é"Key']}, {"columns": ["ID", 'é"Key']}]) + ) + self.assertNotEqual(entries[0]["id"], entries[1]["id"]) + self.assertIn('" ID "', entries[0]["sql"]) + self.assertIn('"é""Key"', entries[0]["sql"]) + + def test_I07_E_unsupported_definitions_are_explicit(self): + malformed = [ + {}, + {"columns": "id"}, + {"columns": []}, + {"columns": [None]}, + {"columns": [{"expression": "lower(id)"}]}, + {"columns": [""]}, + {"columns": ["a" * 64]}, + {"columns": ["id"], "unique": "false"}, + {"columns": ["id"], "predicate": "id > 0"}, + {"columns": ["id"], "method": "gin"}, + {"columns": ["id"], "include": ["x"]}, + {"columns": ["id"], "expressions": ["lower(id)"]}, + "id", + ] + for policy in malformed: + with self.subTest(policy=policy), self.assertRaises(ValueError): + source_entries(target([{"columns": ["valid"]}, policy])) + for policies in ({}, "", False): + with self.subTest(policies=policies), self.assertRaises(ValueError): + source_entries(target(policies)) + + def test_empty_missing_and_primary_only_are_read_only(self): + for policies in ( + [], + None, + [{"primary": True}], + [{"columns": ["id"], "source_idxtype": "U"}], + ): + dataset = target(policies) + original = copy.deepcopy(dataset.document) + entries = source_entries(dataset) + self.assertEqual(dataset.document, original) + self.assertEqual( + len(entries), int(bool(policies and not policies[0].get("primary"))) + ) + + def test_generated_name_cannot_acquire_secondary_ownership(self): + policies = [{"columns": ["id"]}] + name = source_entries(target(policies))[0]["index_name"] + with self.assertRaisesRegex(IndexConflict, "secondary intent"): + source_entries( + target(policies, [{"index_name": name, "desired_state": "absent"}]) + ) + + +@unittest.skipUnless( + os.getenv("QUEUE_TEST_POSTGRES_DSN") and os.getenv("QUEUE_TEST_MONGO_URI"), + "Set QUEUE_TEST_POSTGRES_DSN and QUEUE_TEST_MONGO_URI to disposable databases", +) +class SourcePolicyDatabaseTests(unittest.TestCase): + def setUp(self): + import psycopg2 + from pymongo import MongoClient + + self.connect = lambda: psycopg2.connect(os.environ["QUEUE_TEST_POSTGRES_DSN"]) + self.connection = self.connect() + self.connection.autocommit = True + self.cursor = self.connection.cursor() + self.schema = "i07_" + uuid4().hex[:12] + self.table = f'"{self.schema}".data' + self.cursor.execute(f'CREATE SCHEMA "{self.schema}"') + self.cursor.execute( + f"CREATE TABLE {self.table} (id int, a_b int, c int, a int, b_c int)" + ) + self.client = MongoClient(os.environ["QUEUE_TEST_MONGO_URI"]) + self.db = self.client["i07_" + uuid4().hex] + self.db.references.insert_one( + { + "_id": "reference", + "data_mart_schema": self.schema, + "table_name": "data", + "source_indexes": [], + } + ) + self.manager = DatasetIndexes( + self.db, + lambda schema: SimpleNamespace(get_connection=self.connect), + lambda doc: doc["data_mart_schema"], + ) + + def tearDown(self): + self.cursor.execute(f'DROP SCHEMA "{self.schema}" CASCADE') + self.cursor.close() + self.connection.close() + self.client.drop_database(self.db.name) + self.client.close() + + def target(self, policies=None): + if policies is not None: + self.db.references.update_one( + {"_id": "reference"}, {"$set": {"source_indexes": policies}} + ) + return self.manager.get("REFERENCE", "reference") + + def physical(self, name): + return inspect_index(self.cursor, self.schema, name) + + def test_I07_C_owned_historical_name_reused_without_duplicate(self): + target = self.target([{"columns": ["a_b", "c"], "unique": True}]) + self.manager.reconcile(target) + original = self.manager.source_policy(target, self.connection)[0]["index_name"] + oid = self.physical(original).oid + self.cursor.execute( + f'ALTER INDEX "{self.schema}"."{original}" RENAME TO historical' + ) + self.manager.reconcile(target) + bound = self.manager.source_policy(target, self.connection) + self.assertEqual([e["index_name"] for e in bound], ["historical"]) + self.assertEqual(self.physical("historical").oid, oid) + self.assertIsNone(self.physical(original)) + self.assertTrue(owns(bound[0], self.physical("historical"))) + self.assertEqual(len(list_indexes(self.cursor, self.schema, "data")), 1) + + def test_historical_equivalence_respects_order_uniqueness_and_adoption(self): + target = self.target([{"columns": ["a_b", "c"], "unique": True}]) + for name, keys, unique in [ + ("wrong_order", "c,a_b", True), + ("not_unique", "a_b,c", False), + ("historical", "a_b,c", True), + ]: + self.cursor.execute( + f'CREATE {"UNIQUE " if unique else ""}INDEX {name} ON {self.table} ({keys})' + ) + bound = self.manager.source_policy(target, self.connection)[0] + self.assertEqual(bound["index_name"], "historical") + with self.assertRaises(IndexRepairError): + self.manager.reconcile(target) + self.assertIsNone(self.physical("historical").comment) + apply_entry(self.cursor, dict(bound, adopt=True), self.schema, "data") + self.manager.reconcile(target) + self.assertEqual(len(list_indexes(self.cursor, self.schema, "data")), 3) + + def test_secondary_equivalent_and_receipt_never_become_source(self): + sql = f"CREATE INDEX secondary ON {self.table} (id)" + save_intent(self.db.references, "reference", self.schema, "data", sql) + self.manager.reconcile(self.target()) + oid = self.physical("secondary").oid + target = self.target([{"columns": ["id"]}]) + self.manager.reconcile(target) + self.assertNotEqual( + self.manager.source_policy(target, self.connection)[0]["index_name"], + "secondary", + ) + self.assertEqual(self.physical("secondary").oid, oid) + # Even if metadata is lost, a foreign receipt cannot silently change owners. + self.db.references.update_one( + {"_id": "reference"}, {"$set": {"secondary_indexes": []}} + ) + entries = self.manager.source_policy(self.target(), self.connection) + self.assertNotEqual(entries[0]["index_name"], "secondary") + + def test_I07_D_ambiguous_old_name_is_not_dropped(self): + policies = [{"columns": ["a_b", "c"]}, {"columns": ["a", "b_c"]}] + target = self.target(policies) + ambiguous = f"idx_{self.schema}_data_a_b_c" + self.cursor.execute(f'CREATE INDEX "{ambiguous}" ON {self.table} (id)') + oid = self.physical(ambiguous).oid + self.manager.reconcile(target) + entries = self.manager.source_policy(target, self.connection) + self.assertEqual(len({e["index_name"] for e in entries}), 2) + self.assertTrue(all(self.physical(e["index_name"]).valid for e in entries)) + self.assertEqual(self.physical(ambiguous).oid, oid) + self.assertIsNone(self.physical(ambiguous).comment) + self.assertEqual(self.db.references.find_one()["source_indexes"], policies) + + def test_I07_B_restoration_preserves_source_and_secondary_intent(self): + policies = [{"columns": ["a_b", "c"]}] + target = self.target(policies) + entry = save_intent( + self.db.references, + "reference", + self.schema, + "data", + f"CREATE INDEX secondary ON {self.table} (id)", + ) + self.manager.reconcile(target) + for _ in range(2): + self.cursor.execute(f"DROP TABLE {self.table}") + self.cursor.execute(f"CREATE TABLE {self.table} (id int, a_b int, c int)") + self.manager.reconcile(self.target()) + doc = self.db.references.find_one() + self.assertEqual(doc["source_indexes"], policies) + for key in ("id", "sql", "revision", "desired_state"): + self.assertEqual(doc["secondary_indexes"][0][key], entry[key]) + delete_intent(self.db.references, "reference", self.schema, "secondary") + self.manager.reconcile(self.target()) + self.assertIsNone(self.physical("secondary")) + + def partition_tree(self): + self.cursor.execute(f"DROP TABLE {self.table}") + self.cursor.execute( + f"CREATE TABLE {self.table} (id int, a int) PARTITION BY RANGE(id)" + ) + self.cursor.execute( + f'CREATE TABLE "{self.schema}".branch PARTITION OF {self.table} ' + "FOR VALUES FROM(0) TO(100) PARTITION BY RANGE(id)" + ) + self.cursor.execute( + f'CREATE TABLE "{self.schema}".leaf PARTITION OF "{self.schema}".branch ' + "FOR VALUES FROM(0) TO(100)" + ) + return self.target([{"columns": ["id"]}]) + + def test_partition_parent_only_rendering_reuses_complete_historical_tree(self): + target = self.partition_tree() + self.manager.reconcile(target) + entry = self.manager.source_policy(target, self.connection)[0] + self.cursor.execute( + f'ALTER INDEX "{self.schema}"."{entry["index_name"]}" RENAME TO historical' + ) + self.assertIn("ON ONLY", self.physical("historical").definition) + self.manager.reconcile(target) + self.assertTrue(index_ready(self.cursor, self.physical("historical"))) + self.assertFalse( + parse_index( + self.manager.source_policy(target, self.connection)[0]["sql"] + ).only + ) + self.assertEqual(len(list_indexes(self.cursor, self.schema, "data")), 1) + + def test_partition_tree_readiness_checks_descendants_even_if_parent_valid(self): + target = self.partition_tree() + self.manager.reconcile(target) + entry = self.manager.source_policy(target, self.connection)[0] + parent = self.physical(entry["index_name"]) + leaf = list_indexes(self.cursor, self.schema, "leaf")[0] + # Fault injection is restricted to this disposable schema's leaf index. + self.cursor.execute( + "UPDATE pg_index SET indisready=false WHERE indexrelid=%s", (leaf.oid,) + ) + self.assertTrue(self.physical(parent.index_name).valid) + self.assertFalse(index_ready(self.cursor, parent)) + with self.assertRaisesRegex(IndexRepairError, "partition tree"): + self.manager.reconcile(target) + self.assertFalse(self.manager.listing(target)[0]["physical_ready"]) + self.assertTrue(self.db.references.find_one()["index_repair_pending"]) + self.cursor.execute( + "UPDATE pg_index SET indisready=true WHERE indexrelid=%s", (leaf.oid,) + ) + self.manager.reconcile(target) + self.assertEqual(self.physical(parent.index_name).oid, parent.oid) + + def test_incomplete_partition_parent_requires_review_without_replacement(self): + target = self.partition_tree() + entry = source_entries(target)[0] + self.cursor.execute(parse_index(entry["sql"]).render(only=True)) + parent = self.physical(entry["index_name"]) + self.assertFalse(index_ready(self.cursor, parent)) + with self.assertRaises(IndexRepairError): + apply_entry(self.cursor, dict(entry, adopt=True), self.schema, "data") + self.assertEqual(self.physical(parent.index_name).oid, parent.oid) + + +if __name__ == "__main__": + unittest.main()