Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
355 changes: 355 additions & 0 deletions ddp_lib/dataset_indexes.py

Large diffs are not rendered by default.

15 changes: 13 additions & 2 deletions ddp_lib/document.py
Original file line number Diff line number Diff line change
@@ -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
Expand Down Expand Up @@ -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

Expand Down Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions ddp_lib/enums.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ class SyncStatus(Enum):


class QueuedJobAction(Enum):
RECONCILE_INDEXES = "RECONCILE_INDEXES"
FULL_REBUILD = "FULL_REBUILD"
FULL_REFRESH = "FULL_REFRESH"
FULL_SYNC = "FULL_SYNC"
Expand Down
61 changes: 61 additions & 0 deletions ddp_lib/index_hooks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
"""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.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)
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
134 changes: 134 additions & 0 deletions ddp_lib/index_metadata.py
Original file line number Diff line number Diff line change
@@ -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'})
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')
130 changes: 130 additions & 0 deletions ddp_lib/index_sql.py
Original file line number Diff line number Diff line change
@@ -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,
)

Loading
Loading