From d35ef3e6baf19f31dbd4035300d401aaf009b8d7 Mon Sep 17 00:00:00 2001 From: Kent Bull Date: Sat, 17 Oct 2026 14:00:24 -0600 Subject: [PATCH] Fix Seeker indexing and bounded startup recovery Encode typed scalar tuples as fixed-size equality keys and derive complete canonical index definitions before use. Repair existing accepted-credential indexes on startup, including partial entries and incorrect compound definitions, without dropping named databases. Keep recovery state in Seeker, retry only missing schemas, and make permanent failures visible. Bound scheduler work, tolerate deletion during repair, and isolate credential query semantics from exchange queries. Add real LMDB regressions for key boundaries, interrupted recovery, optional attributes, and query error behavior. Validation: 38 focused tests pass in the pre-publication run; 77 distinct affected cases passed across earlier runs. Ruff and diff checks pass. The existing persistent-state test_agency, full-suite execution, and remote CI remain unqualified. --- src/keria/app/agenting.py | 48 ++- src/keria/app/credentialing.py | 14 +- src/keria/db/basing.py | 676 +++++++++++++++++++++++--------- src/keria/keriaing.py | 18 + tests/app/test_agenting.py | 3 +- tests/app/test_basing.py | 8 +- tests/app/test_seeker_repair.py | 482 +++++++++++++++++++++++ 7 files changed, 1039 insertions(+), 210 deletions(-) create mode 100644 src/keria/keriaing.py create mode 100644 tests/app/test_seeker_repair.py diff --git a/src/keria/app/agenting.py b/src/keria/app/agenting.py index 05316d1b..94991a80 100644 --- a/src/keria/app/agenting.py +++ b/src/keria/app/agenting.py @@ -1425,25 +1425,55 @@ def recur(self, tyme, tock=0.0, **opts): class SeekerDoer(doing.Doer): + """Schedule bounded repair work and saved cues; Seeker owns recovery state.""" + + # Bound work per scheduler turn without imposing one tick per index row. + RepairBatchSize = 128 + def __init__(self, seeker, cues, tock=0.0): + """Start reconciliation before serving queries and retain the shared cue deck.""" self.seeker = seeker self.cues = cues - self.tock = tock - super(SeekerDoer, self).__init__(tock=self.tock) + self.repair = seeker.startRepair() + super(SeekerDoer, self).__init__(tock=tock) def recur(self, tyme=None, tock=0.0, **opts): + """Advance a repair batch, or check one pending schema and consume one cue.""" + if self.repair is not None: + try: + for _ in range(self.RepairBatchSize): + said = next(self.repair) + if said is not None: + self._report(said, self.seeker.failures.get(said)) + return False + except StopIteration: + self.repair = None + except Exception as ex: + self.repair = None + self.seeker.failRepair(ex) + logger.exception("Seeker startup reconciliation failed") + return False + if (attempt := self.seeker.retry()) is not None: + self._report(*attempt) if self.cues: cue = self.cues.popleft() if cue["kin"] == "saved": - creder = cue["creder"] - try: - self.seeker.index(said=creder.said) - except Exception: - self.cues.append(cue) - return False + said = cue["creder"].said + self._report(said, self.seeker.process(said)) else: self.cues.append(cue) - return False + return False + + @staticmethod + def _report(said, error): + """Log classified failures once per attempt, retaining the original traceback.""" + if error is not None: + logger.error( + "Seeker indexing failed for %s: %s", + said, + error, + exc_info=(type(error), error, error.__traceback__), + ) class ExchangeCueDoer(doing.Doer): diff --git a/src/keria/app/credentialing.py b/src/keria/app/credentialing.py index 92758c98..1c41656e 100644 --- a/src/keria/app/credentialing.py +++ b/src/keria/app/credentialing.py @@ -21,6 +21,7 @@ from ..utils.openapi import dataclassFromFielddom from keri.core.serdering import Protocols, Vrsn_1_0, Vrsn_2_0, SerderKERI from ..core import httping, longrunning +from .. import keriaing from marshmallow import fields, Schema as MarshmallowSchema from typing import List, Dict, Any, Optional, Literal, Union from .aiding import ( @@ -836,8 +837,17 @@ def on_post(req, rep): skip = 0 limit = 25 - cur = agent.seeker.find(filtr=filtr, sort=sort, skip=skip, limit=limit) - saids = [coring.Saider(qb64=said) for said in cur] + try: + cur = agent.seeker.find(filtr=filtr, sort=sort, skip=skip, limit=limit) + saids = [coring.Saider(qb64=said) for said in cur] + except keriaing.UnsupportedQueryError as ex: + raise falcon.HTTPBadRequest( + title="Unsupported credential query", description=str(ex) + ) + except keriaing.IndexNotReadyError as ex: + raise falcon.HTTPServiceUnavailable( + title="Credential indexes unavailable", description=str(ex) + ) creds = agent.rgy.reger.cloneCreds(saids=saids, db=agent.hby.db) end = skip + (len(creds) - 1) if len(creds) > 0 else 0 diff --git a/src/keria/db/basing.py b/src/keria/db/basing.py index 64cd033d..d6346758 100644 --- a/src/keria/db/basing.py +++ b/src/keria/db/basing.py @@ -1,27 +1,57 @@ # -*- encoding: utf-8 -*- -""" -KERIA -keria.db.basing module - -""" +"""Agency database storage, search indexes, key codecs, and query execution.""" +import hashlib +import math +import struct from dataclasses import dataclass +from itertools import islice from ordered_set import OrderedSet as oset - from keri.core import coring from keri.db import dbing, subing, koming +from keria import keriaing -SCALAR_TYPES = ("string", "number") +# JSON Schema payload types eligible for scalar search indexes. +SCALAR_TYPES = ("string", "number", "integer") +# Top-level credential issuer AID (distinct from the payload issuee). ISSUER_FIELD = coring.Pather(path=["i"]) +# Optional credential recipient AID in the attribute block. ISSUEE_FIELD = coring.Pather(path=["a", "i"]) +# Credential schema SAID used to scope schema-specific searches. SCHEMA_FIELD = coring.Pather(path=["s"]) +# Credential registry identifier used for registry searches. REGISTRY_FIELD = coring.Pather(path=["ri"]) +def tupleKey(values): + """Hash a typed, length-framed tuple into a fixed-size equality key. + + Strings use UTF-8, integers decimal bytes, and finite floats binary64 bytes. + Signed zero is normalized; other types are rejected. SHA-256 keeps even + long compound strings below LMDB's key limit. Keys carry no sort order; + prefix matching and ordering resolve the original credential values. + """ + key = bytearray() + for value in values: + if type(value) is str: + tag, raw = b"s", value.encode("utf-8") + elif type(value) is int: + tag, raw = b"i", str(value).encode("ascii") + elif type(value) is float and math.isfinite(value): + tag, raw = b"f", struct.pack(">d", 0.0 if value == 0.0 else value) + else: + raise ValueError(f"Unsupported index scalar: {type(value).__name__}") + key.extend(tag + len(raw).to_bytes(4, "big") + raw) + return hashlib.sha256(key).hexdigest() + + @dataclass class IndexRecord: - """Registry Key keyed by Registry name""" + """Persist a named index's LMDB subkey and ordered qb64 field paths. + + Path order determines the field order in compound equality keys. + """ subkey: str paths: list @@ -112,23 +142,28 @@ def reopen(self, **kwa): class Seeker(dbing.LMDBer): - """ - Seeker indexes all credentials in the KERIpy `saved` Creder database. + """Seeker indexes all credentials in the KERIpy `saved` Creder database. Static indexes are created for issued by/schema and issued to/schema and dynamic indexes are created for all top level scalar valued fields in the credential payload ('a' field). The Seeker uses the schema of each credential to determine the payload fields to index by. + Schema definitions select scalar payload indexes; entries map typed keys to + credential SAIDs. SeekerDoer drives startup reconciliation and recovery. + Queries fail while reconciliation or recorded indexing failures remain. """ + # LMDB storage paths, temporary-directory prefix, and named-index capacity. TailDirPath = "keri/seekdb" AltTailDirPath = ".keri/seekdb" TempPrefix = "keri_seekdb_" MaxNamedDBs = 500 def __init__(self, db, reger, headDirPath=None, perm=None, reopen=False, **kwa): - """ - Setup named sub databases. + """Bind schema storage (db) and credential storage (reger). + + Pass reopen=True to open immediately; LMDBer kwargs such as name/temp + select persistent or test storage. Construction does not run repair. Inherited Parameters: name is str directory path name differentiator for main database @@ -153,6 +188,9 @@ def __init__(self, db, reger, headDirPath=None, perm=None, reopen=False, **kwa): self.reger = reger self.indexes = dict() + self.failures = {} + self.pending = {} + self.reconciling = False self.schIdx = None self.dynIdx = None @@ -161,6 +199,7 @@ def __init__(self, db, reger, headDirPath=None, perm=None, reopen=False, **kwa): ) def reopen(self, **kwa): + """Open stored index definitions and base tables without rebuilding entries.""" super(Seeker, self).reopen(**kwa) # List of indexs for a given schema @@ -178,214 +217,316 @@ def reopen(self, **kwa): db=self, subkey=idx.subkey, klas=coring.Saider ) - # Create persistent Indexes if they don't already exist - self.createIndex(SCHEMA_FIELD.qb64) - self.createIndex(REGISTRY_FIELD.qb64) - - # Index of credentials by issuer/issuee. - for field in (ISSUER_FIELD, ISSUEE_FIELD): - self.createIndex(field.qb64) - subkey = f"{field.qb64}.{SCHEMA_FIELD.qb64}" - self.createIndex(subkey) + for key in self._baseIndexes(): + self.createIndex(key) @property def table(self): + """Expose accepted credential SAIDs as the query candidate table.""" return self.reger.saved def value(self, said): + """Resolve an accepted credential SAID to its SAD for query evaluation.""" saider = self.reger.saved.get(keys=(said,)) creder = self.reger.creds.get(keys=(saider.qb64,)) return creder.sad def saidIter(self): + """Yield accepted (key tuple, Saider) pairs for fallback searches.""" return self.reger.saved.getItemIter() def createIndex(self, key): - if self.dynIdx.get(keys=(key,)) is None: + """Install the canonical paths for a named single or compound index.""" + record = IndexRecord(subkey=key, paths=key.split(".")) + old = self.dynIdx.get(keys=(key,)) + if key not in self.indexes or (old and old.subkey != key): self.indexes[key] = subing.CesrDupSuber( db=self, subkey=key, klas=coring.Saider ) - self.dynIdx.pin(keys=(key,), val=IndexRecord(subkey=key, paths=[key])) - - def index(self, said): - if (saider := self.reger.saved.get(keys=(said,))) is None: - raise ValueError(f"{said} is not a verified credential") - - creder = self.reger.creds.get(keys=(saider.qb64,)) - saider = coring.Saider(qb64b=creder.saidb) - - # Load schema index and if not indexed in schIdx, index it. - schemaSaid = creder.schema - if not (indexes := self.schIdx.get(keys=(schemaSaid,))): - indexes = self.generateIndexes(schemaSaid) - - for index in indexes: - db = self.indexes[index] - idx = self.dynIdx.get(keys=(index,)) - values = [] - for path in idx.paths: - pather = coring.Pather(qb64=path) - values.append(pather.resolve(creder.sad)) + if old != record: + self.dynIdx.pin(keys=(key,), val=record) + + def _payload(self, said): + """Resolve the schema's attribute object, including the ACDC oneOf form.""" + schemer = self.db.schema.get(keys=(said,)) + if schemer is None: + raise keriaing.MissingSchemaError(f"Missing credential schema {said}") + payload = schemer.sed["properties"]["a"] + if "oneOf" in payload: + payload = next( + (item for item in payload["oneOf"] if item.get("type") == "object"), + None, + ) + if not isinstance(payload, dict) or "properties" not in payload: + raise ValueError(f"Schema {said} has no supported attribute object") + return payload + + @staticmethod + def _baseIndexes(issuee=True): + """Return canonical base names, omitting recipient indexes for attestations.""" + issuer, schema = ISSUER_FIELD.qb64, SCHEMA_FIELD.qb64 + names = [schema, issuer, REGISTRY_FIELD.qb64, f"{issuer}.{schema}"] + if issuee: + names.extend([ISSUEE_FIELD.qb64, f"{ISSUEE_FIELD.qb64}.{schema}"]) + return names + + @classmethod + def _definitions(cls, payload): + """Derive the complete ordered index names without changing persistent state.""" + issuer, issuee = ISSUER_FIELD.qb64, ISSUEE_FIELD.qb64 + schema = SCHEMA_FIELD.qb64 + fields = [issuer] if "i" not in payload["properties"] else [issuer, issuee] + names = cls._baseIndexes(issuee=issuee in fields) + for name, definition in payload["properties"].items(): + if "type" not in definition: + raise ValueError( + f"Unsupported attribute schema for {name}: missing type" + ) + if not isinstance(definition["type"], str): + raise ValueError(f"Unsupported attribute type declaration for {name}") + if definition["type"] not in SCALAR_TYPES: + continue + path = coring.Pather(path=["a", name]).qb64 + names.extend([path, f"{schema}.{path}"]) + for field in fields: + names.extend([f"{field}.{path}", f"{field}.{schema}.{path}"]) + return list(dict.fromkeys(names)) - value = "".join(values) - db.add(keys=(value,), val=saider) + def generateIndexes(self, said): + """Validate all definitions before installing canonical records and schema refs. - def unindex(self, said): - if (saider := self.reger.saved.get(keys=(said,))) is None: + Always derive from the schema: a nonempty stored list is not evidence of + completeness after a crash or failed generation. Repeated calls repair + retained definitions as well as missing ones. + """ + names = self._definitions(self._payload(said)) + for name in names: + self.createIndex(name) + if self.schIdx.get(keys=(said,)) != names: + self.schIdx.pin(keys=(said,), vals=names) + return names + + def _entries(self, said): + """Prepare all keys before writing; omit indexes with absent optional fields.""" + saider = self.reger.saved.get(keys=(said,)) + if saider is None: raise ValueError(f"{said} is not a verified credential") - - creder = self.reger.creds.get(keys=(saider.qb64,)) - indexes = self.schIdx.get(keys=(creder.schema,)) - if not indexes: - raise ValueError(f"No known indexes for schema {creder.schema}") - - for index in indexes: - db = self.indexes[index] - idx = self.dynIdx.get(keys=(index,)) + creder = self.reger.creds.get(keys=(said,)) + if creder is None: + raise ValueError(f"Accepted credential {said} is missing") + payload = self._payload(creder.schema) + names = self.generateIndexes(creder.schema) + entries = [] + for name in names: values = [] - for path in idx.paths: + for path in name.split("."): pather = coring.Pather(qb64=path) - values.append(pather.resolve(creder.sad)) - - value = "".join(values) - db.rem(keys=(value,), val=saider) + try: + values.append(pather.resolve(creder.sad)) + except KeyError: + if ( + len(pather.path) == 2 + and pather.path[0] == "a" + and pather.path[1] not in payload.get("required", []) + ): + break + raise + else: + entries.append((self.indexes[name], tupleKey(values), saider)) + return entries - def generateIndexes(self, said): - """Parse schema of said, create schIdx entry keyed to said of schema and the subkey indexes in - self.indexes + def index(self, said): + """Index a saved credential after full validation, then retire its failure. + Entry writes use separate transactions. Startup reconciliation removes + partial writes after interruption; schema references never prove success. """ - if (schemer := self.db.schema.get(keys=(said,))) is None: - raise ValueError(f"{said} is not a valid schema SAID to index") - - properties = schemer.sed["properties"] - payload = properties["a"] - if "oneOf" in payload: - oo = payload["oneOf"] - for p in oo: - if p["type"] == "object": - payload = p - break - - if not isinstance(payload, dict): - raise ValueError( - f"schema with SAID={said} is not value, no payload of values" - ) - - properties = payload["properties"] - - attestation = "i" not in properties + for db, key, saider in self._entries(said): + db.add(keys=(key,), val=saider) + self._forget(said) - # Assign single field Schema and ISSUER index and ISSUER/SCHEMA: - self.schIdx.add(keys=(said,), val=SCHEMA_FIELD.qb64b) - self.schIdx.add(keys=(said,), val=ISSUER_FIELD.qb64b) - self.schIdx.add(keys=(said,), val=REGISTRY_FIELD.qb64b) - subkey = f"{ISSUER_FIELD.qb64}.{SCHEMA_FIELD.qb64}" - self.schIdx.add(keys=(said,), val=subkey.encode("UTF-8")) + def _forget(self, said): + """Retire recovery state after successful indexing or intentional deletion.""" + self.failures.pop(said, None) + self.pending.pop(said, None) - # Assign single field ISSUEE index and ISSUEE/SCHEMA if needed - if not attestation: - self.schIdx.add(keys=(said,), val=ISSUEE_FIELD.qb64b) - subkey = f"{ISSUEE_FIELD.qb64}.{SCHEMA_FIELD.qb64}" - self.schIdx.add(keys=(said,), val=subkey.encode("UTF-8")) - - for p, val in properties.items(): - if val["type"] not in SCALAR_TYPES: - continue + def unindex(self, said): + """Remove a saved credential's entries and retire its recovery state. - pather = coring.Pather(path=["a", p]) - if pather.qb64 not in self.indexes: - self.indexes[pather.qb64] = subing.CesrDupSuber( - db=self, subkey=pather.qb64, klas=coring.Saider - ) - idx = IndexRecord(subkey=pather.qb64, paths=[pather.qb64]) - self.dynIdx.pin(keys=(pather.qb64,), val=idx) - self.schIdx.add(keys=(said,), val=pather.qb64b) - - subkey = f"{SCHEMA_FIELD.qb64}.{pather.qb64}" - if subkey not in self.indexes: - self.indexes[subkey] = subing.CesrDupSuber( - db=self, subkey=subkey, klas=coring.Saider + Healthy indexes use the same tuple keys as writes. Failed or reconciling + indexes fall back to a SAID scan so missing schemas and partial/legacy + entries cannot prevent deletion. The caller deletes the Reger data. + """ + if self.reger.saved.get(keys=(said,)) is None: + raise ValueError(f"{said} is not a verified credential") + entries = None + if not self.reconciling and said not in self.failures: + try: + entries = self._entries(said) + except Exception: + # Cleanup must work even when definitions or values cannot be rebuilt. + pass + try: + if entries is not None: + for db, key, saider in entries: + db.rem(keys=(key,), val=saider) + else: + for db in self.indexes.values(): + for keys, val in db.getItemIter(): + if val.qb64 == said: + db.rem(keys=keys, val=val) + except Exception as ex: + self.failures[said] = ex + raise + self._forget(said) + + def process(self, said): + """Attempt queued indexing; retain errors and retry only missing schemas. + + Return the failure for logging, or None on success/deletion. A stale cue + for a credential no longer accepted has no projection to rebuild. + """ + if self.reger.saved.get(keys=(said,)) is None: + self._forget(said) + return None + try: + self.index(said) + except Exception as ex: + self.pending.pop(said, None) + self.failures[said] = ex + if isinstance(ex, keriaing.MissingSchemaError): + self.pending[said] = self.reger.creds.get(keys=(said,)).schema + return ex + return None + + def retry(self): + """Check one pending schema round-robin; return an attempted SAID/error pair.""" + if not self.pending: + return None + said = next(iter(self.pending)) + schema = self.pending.pop(said) + if self.reger.saved.get(keys=(said,)) is None: + self._forget(said) + elif self.reger.creds.get(keys=(said,)) is None: + return said, self.process(said) + elif self.db.schema.get(keys=(schema,)) is None: + self.pending[said] = schema + else: + return said, self.process(said) + return None + + def startRepair(self): + """Gate queries immediately and return the startup iterator when work exists.""" + if next(self.reger.schms.getItemIter(), None) is not None: + self.reconciling = True + return self.reconcile() + return None + + def failRepair(self, error): + """Keep an interrupted startup visibly failed until a successful full repair.""" + self.reconciling = False + self.failures["startup"] = error + + def reconcile(self): + """Yield during discovery, cleanup and rebuilding of accepted schms entries. + + Clean the union of old and canonical index handles before rebuilding. + Recheck acceptance after yields so concurrent deletions are not failures. + Unused definition metadata is removed; physical named databases remain. + """ + self.reconciling = True + completed = False + try: + accepted, schemas = set(), set() + for keys, saider in self.reger.schms.getItemIter(): + if self.reger.saved.get(keys=(saider.qb64,)) is not None: + schemas.add(keys[0]) + accepted.add(saider.qb64) + yield None + old = list(self.indexes.values()) + for schema in schemas: + try: + self.generateIndexes(schema) + except Exception: + # Rebuilding each credential below retains/classifies the error. + pass + yield None + indexes = list(dict.fromkeys(old + list(self.indexes.values()))) + for db in indexes: + for keys, val in db.getItemIter(): + if val.qb64 in accepted: + db.rem(keys=keys, val=val) + yield None + for said in accepted: + self.process(said) + yield said + used = {name for _, name in self.schIdx.getItemIter()} + base = set(self._baseIndexes()) + for keys, record in list(self.dynIdx.getItemIter()): + name = ".".join(keys) + if name not in used and name not in base: + self.dynIdx.rem(keys=keys) + self.indexes.pop(name, None) + self.failures.pop("startup", None) + completed = True + finally: + if not completed: + self.failRepair( + keriaing.IndexNotReadyError("Reconciliation interrupted") ) - idx = IndexRecord(subkey=subkey, paths=[SCHEMA_FIELD.qb64, pather.qb64]) - self.dynIdx.pin(keys=(subkey,), val=idx) - self.schIdx.add(keys=(said,), val=subkey) - - for field in (ISSUER_FIELD, ISSUEE_FIELD): - subkey = f"{field.qb64}.{pather.qb64}" - if subkey not in self.indexes: - self.indexes[subkey] = subing.CesrDupSuber( - db=self, subkey=subkey, klas=coring.Saider - ) - idx = IndexRecord(subkey=subkey, paths=[field.qb64, pather.qb64]) - self.dynIdx.pin(keys=(subkey,), val=idx) - - self.schIdx.add(keys=(said,), val=subkey) - - subkey = f"{field.qb64}.{SCHEMA_FIELD.qb64}.{pather.qb64}" - if subkey not in self.indexes: - self.indexes[subkey] = subing.CesrDupSuber( - db=self, subkey=subkey, klas=coring.Saider - ) - idx = IndexRecord( - subkey=subkey, - paths=[field.qb64, SCHEMA_FIELD.qb64, pather.qb64], - ) - self.dynIdx.pin(keys=(subkey,), val=idx) - - self.schIdx.add(keys=(said,), val=subkey) - - return [index for index in self.schIdx.get(keys=(said,))] + self.reconciling = False def find(self, filtr, sort=None, skip=None, limit=None): - return Cursor(seeker=self, filtr=filtr, sort=sort, skip=skip, limit=limit) + """Return a lazy SAID cursor for filters, sort fields, and pagination. + + Raise IndexNotReadyError during repair or unresolved failures. Query + operators and unsupported ordering are checked at creation/iteration. + """ + if self.reconciling: + raise keriaing.IndexNotReadyError("Credential indexes are reconciling") + if self.failures: + details = ", ".join( + f"{said} ({type(error).__name__})" + for said, error in islice(self.failures.items(), 3) + ) + raise keriaing.IndexNotReadyError( + f"Credential indexes have {len(self.failures)} unresolved failures: {details}" + ) + return CredentialCursor( + seeker=self, filtr=filtr, sort=sort, skip=skip, limit=limit + ) class ExnSeeker(dbing.LMDBer): - """ - Seeker indexes all credentials in the KERIpy `saved` Creder database. - - Static indexes are created for issued by/schema and issued to/schema and dynamic indexes are - created for all top level scalar valued fields in the credential payload ('a' field). The Seeker - uses the schema of each credential to determine the payload fields to index by. + """Maintain fixed search indexes over saved exchange messages in db.exns. + Preserve legacy string-concatenated keys, distinct from Seeker's typed + credential keys. Optional message paths are indexed when present. """ + # LMDB storage paths, temporary-directory prefix, and named-index capacity. TailDirPath = "keri/exndb" AltTailDirPath = ".keri/exndb" TempPrefix = "keri_exndb_" MaxNamedDBs = 36 + # Exchange timestamp for date filtering and legacy string ordering. DATE_FIELD = coring.Pather(path=["dt"]) + # Exchange sender AID. SENDER_FIELD = coring.Pather(path=["i"]) + # Optional recipient AID in the exchange payload. RECIPIENT_FIELD = coring.Pather(path=["a", "i"]) + # Exchange route used to select message families. ROUTE_FIELD = coring.Pather(path=["r"]) - # Special field for IPEX messages... consider moving to IpexSeeker if needed + # Schema SAID of an ACDC embedded in an IPEX exchange. SCHEMA = coring.Pather(path=["e", "acdc", "s"]) def __init__(self, db, headDirPath=None, perm=None, reopen=False, **kwa): - """ - Setup named sub databases. - - Inherited Parameters: - name is str directory path name differentiator for main database - When system employs more than one keri database, name allows - differentiating each instance by name - default name='main' - temp is boolean, assign to .temp - True then open in temporary directory, clear on close - Othewise then open persistent directory, do not clear on close - default temp=False - headDirPath is optional str head directory pathname for main database - If not provided use default .HeadDirpath - default headDirPath=None so uses self.HeadDirPath - perm is numeric optional os dir permissions mode - default perm=None so do not set mode - reopen is boolean, IF True then database will be reopened by this init - default reopen=True - + """Bind exchange storage and configure a separate LMDB search database. + Pass reopen=True to open fixed indexes immediately; name/temp and other + LMDBer kwargs select the storage location and lifetime. """ self.db = db self.indexes = dict() @@ -395,10 +536,10 @@ def __init__(self, db, headDirPath=None, perm=None, reopen=False, **kwa): ) def reopen(self, **kwa): + """Open fixed single-field and ordered two-field exchange indexes.""" super(ExnSeeker, self).reopen(**kwa) - # List of dynamically created indexes to be recreated at load - # Create persistent Indexes if they don't already exist + # Reopen the fixed set of exchange search indexes. fields = ( self.ROUTE_FIELD, self.SENDER_FIELD, @@ -406,7 +547,7 @@ def reopen(self, **kwa): self.DATE_FIELD, self.SCHEMA, ) - # Index of credentials by issuer/issuee. + # Open each field and each ordered pair for compound searches. for field in fields: self.createIndex(field.qb64) for subfield in fields: @@ -417,26 +558,35 @@ def reopen(self, **kwa): @property def table(self): + """Expose saved exchanges as the query candidate table.""" return self.db.exns def value(self, said): + """Resolve a saved exchange SAID to its event dictionary.""" serder = self.db.exns.get(keys=(said,)) return serder.ked def saidIter(self): + """Yield SAID strings from saved exchanges.""" for (said,), _ in self.db.exns.getItemIter(): yield said def createIndex(self, key): + """Open a named exchange index mapping legacy keys to duplicate SAIDs.""" self.indexes[key] = subing.CesrDupSuber(db=self, subkey=key, klas=coring.Saider) def index(self, said): + """Add a saved exchange to fixed indexes, ignoring absent optional paths. + + Concatenate available string values in path order; skip empty keys and + raise ValueError when the exchange SAID is not saved. + """ if (serder := self.db.exns.get(keys=(said,))) is None: raise ValueError(f"{said} is not a valid exn") saider = coring.Saider(qb64b=serder.saidb) - # Load schema index and if not indexed in schIdx, index it. + # Missing optional paths contribute no value to the legacy key. for index, db in self.indexes.items(): pathers = [coring.Pather(qb64=path) for path in index.split(".")] values = [] @@ -453,13 +603,26 @@ def index(self, said): db.add(keys=(value,), val=saider) def find(self, filtr, sort=None, skip=None, limit=None): + """Return a lazy cursor using legacy exchange filter and ordering semantics.""" return Cursor(seeker=self, filtr=filtr, sort=sort, skip=skip, limit=limit) class Cursor: + """Lazily select SAIDs through index lookups, scans, and pagination. + + Filters use CESR path strings (for example -a-LEI), literal equality or + $eq/$begins objects. Credential equality is typed; exchange keys retain + legacy semantics. Configure sort/skip/limit before starting iteration. + """ + def __init__(self, seeker, filtr=None, sort=None, skip=None, limit=None): - self.filtr = filtr - self.operators = operators(self.filtr) + """Bind the seeker and compile filters; defer database reads until iteration. + + Default to no filter, zero skip and a limit of 25. Credential filters + reject unsupported operators; exchange filters retain legacy parsing. + """ + self.filtr = filtr if filtr is not None else {} + self.operators = self.compile(self.filtr) self.names = [op.name for op in self.operators] self.indexable = next( (False for op in self.operators if not isinstance(op, Eq)), True @@ -475,9 +638,11 @@ def __init__(self, seeker, filtr=None, sort=None, skip=None, limit=None): self.saids = None def __iter__(self): + """Return this stateful iterator; iteration does not reset its position.""" return self def __next__(self): + """Execute the query once, then yield SAIDs until the selected page is exhausted.""" if self.saids is None: self._query() @@ -489,18 +654,26 @@ def __next__(self): return said def sort(self, sort): + """Set ordered CESR sort paths and return self; configure before iteration.""" self._sort = sort return self def skip(self, skip): + """Set the result offset and return self; configure before iteration.""" self._skip = skip return self def limit(self, limit): + """Set the page size and return self; configure before iteration.""" self._limit = limit return self def _query(self): + """Materialize the selected page using direct lookup or fallback scans. + + Validate credential equality values and evaluate prefixes independently + of the tuple encoding; ordering and slicing occur after selection. + """ self.cur = 0 if len(self.filtr) == 0: self.saids = self.order( @@ -515,20 +688,22 @@ def _query(self): self.saids = self.order(saids) def indexSearch(self): + """Return SAIDs from a matching single/compound index, or None if unavailable.""" if len(self.operators) == 1 and self.operators[0].name in self.seeker.indexes: op = self.operators[0] idx = self.seeker.indexes[op.name] - return op.index(idx) + return self._indexOperator(op, idx) index = ".".join(self.names) if not (self.indexable and index in self.seeker.indexes): return None idx = self.seeker.indexes[index] - val = "".join(self.values) + val = self.encodeKey(self.values) return [val.qb64 for val in idx.getIter(keys=(val,))] def indexScan(self): + """Intersect indexed predicates, then evaluate remaining predicates on candidates.""" use = [] scan = [] @@ -542,13 +717,13 @@ def indexScan(self): return self.fullTableScan() idx = self.seeker.indexes[use[0].name] - saids = oset(use[0].index(idx)) + saids = oset(self._indexOperator(use[0], idx)) if len(saids) == 0: return list() for i, op in enumerate(use[1:]): idx = self.seeker.indexes[op.name] - nxt = oset(op.index(idx)) + nxt = oset(self._indexOperator(op, idx)) saids &= nxt if len(scan) == 0: @@ -556,30 +731,45 @@ def indexScan(self): else: return self.tableScan(list(saids), scan) + @staticmethod + def compile(filtr): + """Compile filters using the legacy exchange operator contract.""" + return operators(filtr) + + @staticmethod + def encodeKey(values): + """Encode compound exchange keys with their existing concatenation format.""" + return "".join(values) + + def _indexOperator(self, op, idx): + """Delegate legacy indexed matching to the operator.""" + return op.index(idx) + def fullTableScan(self): + """Evaluate filters over candidates from the seeker iterator instead of an index.""" saids = [saider.qb64 for _, saider in self.seeker.saidIter()] return self.tableScan(saids, ops=self.operators) def tableScan(self, saids, ops): + """Retain legacy exchange per-operator accumulation semantics.""" res = [] for said in saids: val = self.seeker.value(said) for op in ops: if op(val): res.append(said) - return res def order(self, saids): + """Order exchanges using an existing index, or preserve candidate order.""" if not self._sort: return self.slice(saids) - if (res := self.indexOrder(saids)) is not None: return res - else: - return self.tableScanOrder(saids) + return self.tableScanOrder(saids) def indexOrder(self, saids): + """Read a matching legacy sort index, retaining candidates and applying skip/limit.""" index = ".".join([coring.Pather(bext=s).qb64 for s in self._sort]) if index not in self.seeker.indexes: return None @@ -606,6 +796,7 @@ def indexOrder(self, saids): return res def slice(self, saids): + """Return the configured page from an already selected/ordered SAID list.""" if self._skip >= len(saids): return [] @@ -613,35 +804,117 @@ def slice(self, saids): return saids[self._skip : end] def tableScanOrder(self, saids): - """Should we bother implementing table scan sort order + """Apply pagination without sorting when no legacy compound sort index exists.""" + return self.slice(saids) - We have single field indexes for all fields in credentials so this situation will - only occur if multiple fields are selected for which we don't have a multi-column - index. In that case, perhaps we raise an exception. - For now, we'll just slice the results to honor skip and limit. +class CredentialCursor(Cursor): + """Specialize the existing cursor's encoding, matching and ordering boundaries. - """ - return self.slice(saids) + The shared planner never inspects the concrete seeker type. Credential + semantics stay here; exchange cursors retain their existing behavior. + """ + @staticmethod + def compile(filtr): + """Reject unsupported operators and equality values before database reads.""" + ops = operators(filtr, strict=True) + for op in ops: + if isinstance(op, Eq): + try: + tupleKey([op.value]) + except ValueError as ex: + raise keriaing.UnsupportedQueryError(str(ex)) from ex + return ops + + @staticmethod + def encodeKey(values): + """Use the same typed tuple codec as credential writes and removals.""" + return tupleKey(values) + + @staticmethod + def matches(op, sad): + """Match supported scalars; missing paths and non-scalar actuals do not match.""" + try: + actual = op.pather.resolve(sad) + if isinstance(op, Eq): + return tupleKey([actual]) == tupleKey([op.value]) + return isinstance(actual, str) and actual.startswith(op.value) + except (KeyError, TypeError, ValueError): + return False + + def _indexOperator(self, op, idx): + """Use equality keys directly; evaluate string prefixes on original values.""" + if isinstance(op, Eq): + return [val.qb64 for val in idx.getIter(keys=(tupleKey([op.value]),))] + return [ + val.qb64 + for _, val in idx.getItemIter() + if self.matches(op, self.seeker.value(val.qb64)) + ] + + def tableScan(self, saids, ops): + """Require every predicate to match each candidate credential.""" + res = [] + for said in saids: + sad = self.seeker.value(said) + if all(self.matches(op, sad) for op in ops): + res.append(said) + return res + + def order(self, saids): + """Sort string tuples; omit missing fields and reject non-string sorting. + + Equal tuples use SAID order for stable pagination across query plans. + Index membership is honored when a matching sort index exists. + """ + if not self._sort: + return self.slice(saids) + paths = [coring.Pather(bext=field) for field in self._sort] + name = ".".join(path.qb64 for path in paths) + if name in self.seeker.indexes: + indexed = {val.qb64 for _, val in self.seeker.indexes[name].getItemIter()} + saids = [said for said in saids if said in indexed] + values = {} + for said in saids: + sad = self.seeker.value(said) + try: + row = tuple(path.resolve(sad) for path in paths) + except (KeyError, TypeError): + continue + if any(type(value) is not str for value in row): + raise keriaing.UnsupportedQueryError("Numeric sorting is not supported") + values[said] = row + return self.slice(sorted(values, key=lambda said: (values[said], said))) -def operators(filtr): - """Executable operator factory method - An factory for processing a filter dict and generating an array of - executable operators to apply to a given credential search +def operators(filtr, strict=False): + """Compile CESR-path filters into Eq and Begins predicates in input order. + Literal values mean equality. Strict credential mode rejects unsupported + operators; non-strict exchange mode ignores unknown operators. """ # filtr = {"-a-i": {"$begins": "984"}} ops = [] for f, v in filtr.items(): if isinstance(v, dict): + if strict and not v: + raise keriaing.UnsupportedQueryError("Empty query operator object") for op, val in v.items(): match op: case "$eq": ops.append(Eq(field=f, value=val)) case "$begins": + if strict and not isinstance(val, str): + raise keriaing.UnsupportedQueryError( + "Prefix queries require a string" + ) ops.append(Begins(field=f, value=val)) + case _: + if strict: + raise keriaing.UnsupportedQueryError( + f"Unsupported query operator: {op}" + ) pass else: ops.append(Eq(field=f, value=v)) @@ -650,12 +923,19 @@ def operators(filtr): class Eq: + """Represent path equality; Cursor supplies typed credential semantics. + + Direct calls and index lookups retain legacy Python/string-key behavior. + """ + def __init__(self, field, value): + """Bind a CESR path expression and the equality value.""" self.field = field self.pather = coring.Pather(bext=self.field) self.value = value def __call__(self, *args, **kwargs): + """Compare the resolved field using Python equality; require one document argument.""" if len(args) != 1: raise ValueError( f"invalid argument length={len(args)} for equals operator, must be 2" @@ -666,14 +946,19 @@ def __call__(self, *args, **kwargs): @property def name(self) -> str: + """Return the qb64 path used to identify a single-field index.""" return self.pather.qb64 def index(self, idx): + """Return SAIDs matching the raw legacy key; credential cursors encode keys separately.""" return [val.qb64 for val in idx.getIter(keys=(self.value,))] class Begins: + """Represent a string-prefix predicate on a CESR document path.""" + def __init__(self, field, value): + """Bind a CESR path and string prefix; reject non-string prefixes.""" self.field = field self.pather = coring.Pather(bext=self.field) @@ -682,6 +967,7 @@ def __init__(self, field, value): self.value = value def __call__(self, *args, **kwargs): + """Test the resolved string prefix; require one document with a string field.""" if len(args) != 1: raise ValueError( f"invalid argument length={len(args)} for begins operator, must be 2" @@ -694,8 +980,10 @@ def __call__(self, *args, **kwargs): return val.startswith(self.value) def index(self, idx): + """Read a raw legacy key prefix; credential cursors scan resolved string values.""" return [val.qb64 for _, val in idx.getItemIter(keys=(self.value,))] @property def name(self) -> str: + """Return the qb64 path used to identify a single-field index.""" return self.pather.qb64 diff --git a/src/keria/keriaing.py b/src/keria/keriaing.py new file mode 100644 index 00000000..e80b4535 --- /dev/null +++ b/src/keria/keriaing.py @@ -0,0 +1,18 @@ +# -*- encoding: utf-8 -*- +"""KERIA-specific exceptions shared across database and application layers.""" + + +class KeriaError(Exception): + """Base class for KERIA exceptions, following KERIpy's KeriError pattern.""" + + +class MissingSchemaError(KeriaError, ValueError): + """Indexing can resume when the referenced schema becomes available.""" + + +class UnsupportedQueryError(KeriaError, ValueError): + """The requested query has no supported ordering/equality semantics.""" + + +class IndexNotReadyError(KeriaError, RuntimeError): + """Credential search cannot claim completeness during repair or failure.""" diff --git a/tests/app/test_agenting.py b/tests/app/test_agenting.py index aba10a4f..cac0ecdf 100644 --- a/tests/app/test_agenting.py +++ b/tests/app/test_agenting.py @@ -1157,7 +1157,8 @@ def test_seeker_doer(helpers): result = seeker.recur() assert result is False - assert len(cues) == 1 + assert len(cues) == 0 + assert not agent.seeker.failures # stale cue: credential is no longer saved def test_submitter(seeder, helpers): diff --git a/tests/app/test_basing.py b/tests/app/test_basing.py index efcb3fbc..efd0ea58 100644 --- a/tests/app/test_basing.py +++ b/tests/app/test_basing.py @@ -3,7 +3,7 @@ KERIA keria.app.basing module -Testing the database classes +Testing credential and exchange search indexes """ import random @@ -41,7 +41,7 @@ def test_seeker(helpers, seeder, mockHelpingNowUTC): indexes = seeker.generateIndexes(QVI_SAID) # Verify the indexes created for the QVI schema - assert indexes == [ + assert [index for index in indexes if "gracePeriod" not in index] == [ "5AABAA-s", "5AABAA-i", "4AABA-ri", @@ -74,7 +74,7 @@ def test_seeker(helpers, seeder, mockHelpingNowUTC): ] # Test that the index tables were correctly created - assert len(seeker.indexes) == 29 + assert len(seeker.indexes) == 35 indexes = seeker.generateIndexes(LE_SAID) @@ -112,7 +112,7 @@ def test_seeker(helpers, seeder, mockHelpingNowUTC): ] # Assure that no new index tables needed to be created - assert len(seeker.indexes) == 29 + assert len(seeker.indexes) == 35 # Test with a bad credential SAID with pytest.raises(ValueError): diff --git a/tests/app/test_seeker_repair.py b/tests/app/test_seeker_repair.py new file mode 100644 index 00000000..c6a3b279 --- /dev/null +++ b/tests/app/test_seeker_repair.py @@ -0,0 +1,482 @@ +"""Real LMDB regressions for credential indexing and startup recovery.""" + +import math + +import pytest +from hio.help import decking +from keri.app import habbing +from keri.core import coring, scheming +from keri.vc import proving +from keri.vdr import viring + +from keria.app import agenting +from keria import keriaing +from keria.db import basing + + +@pytest.fixture +def stores(tmp_path): + with habbing.openHab(name="seeker-repair", temp=True) as (hby, hab): + reger = viring.Reger(name="repair", temp=True) + seeker = basing.Seeker( + name="repair", + headDirPath=str(tmp_path), + temp=False, + reopen=True, + db=hby.db, + reger=reger, + ) + try: + yield hby, hab, reger, seeker + finally: + seeker.close(clear=True) + reger.close(clear=True) + + +def schema(hby, issuee=False, x_type="number", extra=None, optional=(), oneof=False): + properties = { + "d": {"type": "string"}, + "x": {"type": x_type}, + "y": {"type": "string"}, + } + properties.update(extra or {}) + if issuee: + properties["i"] = {"type": "string"} + payload = { + "type": "object", + "properties": properties, + "required": [name for name in properties if name not in optional], + } + if oneof: + payload = {"oneOf": [{"type": "string"}, payload]} + schemer = scheming.Schemer( + sed={ + "$id": "", + "$schema": "http://json-schema.org/draft-07/schema#", + "type": "object", + "properties": {"a": payload}, + } + ) + hby.db.schema.pin(keys=(schemer.said,), val=schemer) + return schemer + + +def save(hab, reger, schemer, x, y="c", **attributes): + creder = proving.credential( + issuer=hab.pre, + schema=schemer.said, + status=hab.pre, + data={"x": x, "y": y, **attributes}, + ) + saider = coring.Saider(qb64=creder.said) + reger.creds.pin(keys=(creder.said,), val=creder) + reger.saved.pin(keys=(creder.said,), val=saider) + reger.schms.add(keys=(schemer.said,), val=saider) + return creder + + +def finish(doer): + for _ in range(10000): + doer.recur() + if doer.repair is None: + return + pytest.fail("startup reconciliation did not finish") + + +def test_typed_equality_and_reopen(stores): + hby, hab, reger, seeker = stores + sch = schema(hby) + schemas = { + int: schema(hby, x_type="integer"), + float: sch, + str: schema(hby, x_type="string"), + } + creds = [ + save(hab, reger, schemas[type(value)], value) + for value in (-12, 1, 1.0, "1", -0.0, 2.75) + ] + for creder in creds: + assert hby.db.schema.get(keys=(creder.schema,)).verify(raw=creder.raw) + for creder in creds: + seeker.index(creder.said) + for creder in creds: + assert list(seeker.find({"-a-x": creder.sad["a"]["x"]})) == [creder.said] + assert list(seeker.find({"-a-x": 0.0})) == [creds[4].said] + assert list(seeker.find({"-a-x": {"$begins": "1"}})) == [creds[3].said] + assert list(seeker.find({"-a-x": 1, "-a-y": "c"})) == [creds[1].said] + seeker.close(clear=False) + seeker.reopen() + assert list(seeker.find({"-a-x": 1.0})) == [creds[2].said] + seeker.unindex(creds[1].said) + assert list(seeker.find({"-a-x": 1})) == [] + with pytest.raises(keriaing.UnsupportedQueryError, match="Numeric sorting"): + list(seeker.find({}, sort=["-a-x"])) + with pytest.raises(keriaing.UnsupportedQueryError): + list(seeker.find({"-a-x": {"$gt": 1}})) + + +@pytest.mark.parametrize("value", [True, math.inf, -math.inf, math.nan, [], {}, None]) +def test_reject_scalars_before_writes(stores, value): + hby, hab, reger, seeker = stores + sch = schema(hby) + creder = save(hab, reger, sch, value) + with pytest.raises(ValueError): + seeker.index(creder.said) + assert all(not list(db.getItemIter()) for db in seeker.indexes.values()) + + +def test_boundaries_strings_and_issueeless(stores): + hby, hab, reger, seeker = stores + sch = schema(hby, x_type="string") + one = save(hab, reger, sch, "ab", "c") + two = save(hab, reger, sch, "a", "bc") + for creder in (one, two): + seeker.index(creder.said) + assert list(seeker.find({"-a-x": "ab", "-a-y": "c"})) == [one.said] + assert basing.tupleKey(["ab", "c"]) != basing.tupleKey(["a", "bc"]) + seeker.unindex(one.said) + assert list(seeker.find({"-a-x": "ab", "-a-y": "c"})) == [] + assert list(seeker.find({"-a-x": {"$begins": "ab"}})) == [] + assert list(seeker.find({"-a-x": "a", "-a-y": "bc"})) == [two.said] + seeker.index(one.said) + assert set(seeker.find({"-a-x": {"$begins": "a"}})) == {one.said, two.said} + assert list(seeker.find({}, sort=["-a-x"])) == [two.said, one.said] + definitions = seeker.schIdx.get(keys=(sch.said,)) + assert all( + basing.ISSUEE_FIELD.qb64 not in seeker.dynIdx.get(keys=(idx,)).paths + for idx in definitions + ) + + +def test_reconcile_partial_poison_and_repeat(stores): + hby, hab, reger, seeker = stores + sch = schema(hby) + creder = save(hab, reger, sch, -3) + seeker.generateIndexes(sch.said) + poison = f"{basing.ISSUEE_FIELD.qb64}.{coring.Pather(path=['a', 'x']).qb64}" + seeker.createIndex(poison) + seeker.dynIdx.pin( + keys=(poison,), + val=basing.IndexRecord( + subkey=poison, + paths=[basing.ISSUEE_FIELD.qb64, coring.Pather(path=["a", "x"]).qb64], + ), + ) + seeker.schIdx.add(keys=(sch.said,), val=poison) + saider = coring.Saider(qb64=creder.said) + seeker.indexes[poison].add(keys=("legacy-poison",), val=saider) + seeker.indexes[basing.ISSUER_FIELD.qb64].add(keys=(hab.pre,), val=saider) + doer = agenting.SeekerDoer(seeker, decking.Deck()) + with pytest.raises(keriaing.IndexNotReadyError): + seeker.find({}) + finish(doer) + assert not seeker.failures + assert seeker.dynIdx.get(keys=(poison,)) is None + assert seeker.env.open_db(poison.encode(), create=False) is not None + assert list(seeker.find({"-a-x": -3})) == [creder.said] + assert list(seeker.indexes[basing.ISSUER_FIELD.qb64].getIter(keys=(hab.pre,))) == [] + before = {name: list(db.getItemIter()) for name, db in seeker.indexes.items()} + list(seeker.reconcile()) + after = {name: list(db.getItemIter()) for name, db in seeker.indexes.items()} + assert { + key: [(keys, val.qb64) for keys, val in rows] for key, rows in before.items() + } == {key: [(keys, val.qb64) for keys, val in rows] for key, rows in after.items()} + seeker.close(clear=False) + seeker.reopen() + finish(agenting.SeekerDoer(seeker, decking.Deck())) + assert list(seeker.find({"-a-x": -3})) == [creder.said] + + +def test_missing_schema_and_permanent_failure(stores): + hby, hab, reger, seeker = stores + sch = schema(hby) + good = save(hab, reger, sch, -3) + bad = save(hab, reger, sch, True) + hby.db.schema.rem(keys=(sch.said,)) + cues = decking.Deck([dict(kin="saved", creder=good), dict(kin="saved", creder=bad)]) + doer = agenting.SeekerDoer(seeker, cues) + finish(doer) + for _ in range(5): + doer.recur() + assert not cues + assert set(seeker.pending) == {good.said, bad.said} + hby.db.schema.pin(keys=(sch.said,), val=sch) + for _ in range(5): + doer.recur() + assert not seeker.pending + assert good.said not in seeker.failures + assert isinstance(seeker.failures[bad.said], ValueError) + failure = seeker.failures[bad.said] + for _ in range(5): + doer.recur() + assert seeker.failures[bad.said] is failure + assert not cues + with pytest.raises(keriaing.IndexNotReadyError): + seeker.find({}) + assert reger.saved.get(keys=(bad.said,)) is not None + + +def test_unexpected_failure_does_not_cycle(stores, monkeypatch): + hby, hab, reger, seeker = stores + sch = schema(hby) + creder = save(hab, reger, sch, 1) + cues = decking.Deck() + doer = agenting.SeekerDoer(seeker, cues) + finish(doer) + calls = [] + + def fail_write(**kwargs): + calls.append(kwargs) + raise OSError("injected write failure") + + monkeypatch.setattr(seeker.indexes[basing.ISSUER_FIELD.qb64], "add", fail_write) + cues.append(dict(kin="saved", creder=creder)) + doer.recur() + failure = seeker.failures[creder.said] + assert isinstance(failure, OSError) + for _ in range(5): + doer.recur() + assert len(calls) == 1 + assert not cues and not seeker.pending + assert seeker.failures[creder.said] is failure + seeker.unindex(creder.said) + assert not seeker.failures + assert all(not list(db.getItemIter()) for db in seeker.indexes.values()) + + +def test_query_errors_are_explicit(stores): + from types import SimpleNamespace + import falcon + from falcon import testing + from keria.app import credentialing + + hby, hab, reger, seeker = stores + sch = schema(hby) + creder = save(hab, reger, sch, 1) + seeker.index(creder.said) + + class Context: + def process_request(self, req, resp): + req.context.agent = SimpleNamespace( + seeker=seeker, hby=hby, rgy=SimpleNamespace(reger=reger) + ) + + app = falcon.App(middleware=[Context()]) + app.add_route("/credentials/query", credentialing.CredentialQueryCollectionEnd()) + client = testing.TestClient(app) + result = client.simulate_post( + "/credentials/query", json={"filter": {"-a": {"$eq": "irrelevant"}}} + ) + assert result.status_code == 200 and result.json == [] + result = client.simulate_post( + "/credentials/query", json={"sort": ["-a-absent", "-a-y"]} + ) + assert result.status_code == 200 and result.json == [] + result = client.simulate_post("/credentials/query", json={"sort": ["-a-x"]}) + assert result.status_code == 400 + assert result.json["title"] == "Unsupported credential query" + result = client.simulate_post( + "/credentials/query", json={"filter": {"-a-x": {"$gt": 0}}} + ) + assert result.status_code == 400 + result = client.simulate_post("/credentials/query", json={"filter": {"-a-x": {}}}) + assert result.status_code == 400 + doer = agenting.SeekerDoer(seeker, decking.Deck()) + result = client.simulate_post("/credentials/query", json={}) + assert result.status_code == 503 + assert result.json["title"] == "Credential indexes unavailable" + finish(doer) + seeker.failRepair(RuntimeError("injected startup failure")) + result = client.simulate_post("/credentials/query", json={}) + assert result.status_code == 503 + assert "startup (RuntimeError)" in result.json["description"] + + +@pytest.mark.parametrize("length", [153, 423, 511, 1024]) +def test_long_valid_strings_and_deletion(stores, length): + hby, hab, reger, seeker = stores + sch = schema(hby, issuee=True, x_type="string") + creder = save(hab, reger, sch, "x" * length, i=hab.pre) + assert sch.verify(raw=creder.raw) + assert seeker.process(creder.said) is None + assert list(seeker.find({"-i": hab.pre, "-s": sch.said, "-a-x": "x" * length})) == [ + creder.said + ] + seeker.close(clear=False) + seeker.reopen() + assert list(seeker.find({"-a-x": "x" * length})) == [creder.said] + # Deletion must not require a usable schema. + hby.db.schema.rem(keys=(sch.said,)) + seeker.unindex(creder.said) + assert all(not list(db.getItemIter()) for db in seeker.indexes.values()) + + +def test_canonical_compound_definitions(stores): + hby, hab, reger, seeker = stores + sch = schema(hby, issuee=True, x_type="string") + one = save(hab, reger, sch, "c", i="ab") + two = save(hab, reger, sch, "bc", i="a") + for creder in (one, two): + assert sch.verify(raw=creder.raw) + seeker.index(creder.said) + assert list(seeker.find({"-a-i": "ab", "-a-x": "c"})) == [one.said] + assert list(seeker.find({"-a-i": "a", "-a-x": "bc"})) == [two.said] + for filtr in ({"-i": hab.pre, "-s": sch.said}, {"-s": sch.said, "-i": hab.pre}): + assert set(seeker.find(filtr)) == {one.said, two.said} + assert list(seeker.find({"-a-i": "ab", "-s": sch.said})) == [one.said] + # Repair retained metadata as well as obsolete metadata. + name = f"{basing.ISSUER_FIELD.qb64}.{basing.SCHEMA_FIELD.qb64}" + seeker.dynIdx.pin(keys=(name,), val=basing.IndexRecord(subkey=name, paths=[name])) + list(seeker.reconcile()) + assert seeker.dynIdx.get(keys=(name,)).paths == name.split(".") + assert set(seeker.find({"-i": hab.pre, "-s": sch.said})) == {one.said, two.said} + seeker.unindex(one.said) + assert list(seeker.find({"-a-i": "ab", "-a-x": "c"})) == [] + + +def test_partial_definitions_cannot_become_success(stores): + hby, hab, reger, seeker = stores + good = schema(hby) + seeker.index(save(hab, reger, good, 1).said) + bad = schema( + hby, + extra={"z": {"anyOf": [{"type": "string"}, {"type": "number"}]}}, + optional=("z",), + ) + creder = save(hab, reger, bad, 2, y="needle") + assert bad.verify(raw=creder.raw) + # Simulate interrupted legacy publication; a truthy list cannot bypass validation. + seeker.schIdx.add(keys=(bad.said,), val=basing.ISSUER_FIELD.qb64) + cues = decking.Deck([dict(kin="saved", creder=creder)] * 2) + doer = agenting.SeekerDoer(seeker, cues) + finish(doer) + for _ in range(3): + doer.recur() + assert isinstance(seeker.failures[creder.said], ValueError) + assert not cues and not seeker.pending + with pytest.raises(keriaing.IndexNotReadyError): + seeker.find({"-a-y": "needle"}) + seeker.unindex(creder.said) + assert not seeker.failures + + +def test_optional_attributes_and_scalar_fallback(stores): + """Exercise the ECR-shaped oneOf attribute object with optional a.u.""" + hby, hab, reger, seeker = stores + sch = schema( + hby, + extra={"u": {"type": "string"}, "flag": {"type": "boolean"}}, + optional=("u",), + issuee=True, + oneof=True, + ) + absent = save(hab, reger, sch, 1, flag=True, i=hab.pre) + present = save(hab, reger, sch, 2, flag=False, u="salt", i=hab.pre) + for creder in (absent, present): + assert sch.verify(raw=creder.raw) + seeker.index(creder.said) + assert set(seeker.find({"-s": sch.said})) == {absent.said, present.said} + assert list(seeker.find({"-a": {"$eq": "irrelevant"}})) == [] + assert list(seeker.find({"-a-flag": 1})) == [] + assert list(seeker.find({}, sort=["-a-u"])) == [present.said] + assert list(seeker.find({}, sort=["-a-u", "-a-y"])) == [present.said] + + +def test_delete_during_repair_and_stale_cue(stores): + hby, hab, reger, seeker = stores + sch = schema(hby) + creder = save(hab, reger, sch, 1) + seeker.index(creder.said) + repair = seeker.startRepair() + next(repair) # accepted SAID has been discovered + seeker.unindex(creder.said) + reger.schms.rem(keys=(sch.said,), val=coring.Saider(qb64=creder.said)) + reger.saved.rem(keys=(creder.said,)) + reger.creds.rem(keys=(creder.said,)) + list(repair) + assert seeker.process(creder.said) is None + assert not seeker.failures and not seeker.pending + assert list(seeker.find({})) == [] + + +@pytest.mark.parametrize("steps", [1, 2, 8, 18]) +def test_interrupted_repair_restarts(stores, steps): + hby, hab, reger, seeker = stores + sch = schema(hby) + creder = save(hab, reger, sch, 1) + seeker.index(creder.said) + repair = seeker.startRepair() + for _ in range(steps): + next(repair) + repair.close() + with pytest.raises(keriaing.IndexNotReadyError): + seeker.find({}) + seeker.close(clear=False) + seeker.reopen() + doer = agenting.SeekerDoer(seeker, decking.Deck()) + with pytest.raises(keriaing.IndexNotReadyError): + seeker.find({}) + finish(doer) + assert not seeker.failures + assert list(seeker.find({"-a-x": 1})) == [creder.said] + + +def test_repair_batches_scheduler_work(stores): + hby, hab, reger, seeker = stores + sch = schema(hby) + for value in range(10): + seeker.index(save(hab, reger, sch, value).said) + doer = agenting.SeekerDoer(seeker, decking.Deck()) + doer.recur() + assert doer.repair is not None # bounded, not an unbounded drain + doer.recur() + assert doer.repair is None # 182 small steps fit in two 128-step turns + assert len(list(seeker.find({}))) == 10 + + +def test_healthy_unindex_uses_direct_keys(stores, monkeypatch): + hby, hab, reger, seeker = stores + creder = save(hab, reger, schema(hby), 1) + seeker.index(creder.said) + + def unexpected_scan(*args, **kwargs): + pytest.fail("healthy deletion must not scan every credential index") + + with monkeypatch.context() as patch: + for db in seeker.indexes.values(): + patch.setattr(db, "getItemIter", unexpected_scan) + seeker.unindex(creder.said) + assert all(not list(db.getItemIter()) for db in seeker.indexes.values()) + + +def test_pending_credential_disappears(stores): + hby, hab, reger, seeker = stores + sch = schema(hby) + creder = save(hab, reger, sch, 1) + hby.db.schema.rem(keys=(sch.said,)) + assert isinstance(seeker.process(creder.said), keriaing.MissingSchemaError) + reger.creds.rem(keys=(creder.said,)) + said, error = seeker.retry() + assert said == creder.said and isinstance(error, ValueError) + assert not isinstance(error, keriaing.MissingSchemaError) + assert not seeker.pending + assert seeker.failures[said] is error + + +def test_partial_deletion_remains_observable(stores, monkeypatch): + hby, hab, reger, seeker = stores + creder = save(hab, reger, schema(hby), 1) + seeker.index(creder.said) + + def fail_remove(**kwargs): + raise OSError("injected deletion failure") + + with monkeypatch.context() as patch: + patch.setattr(seeker.indexes[basing.ISSUER_FIELD.qb64], "rem", fail_remove) + with pytest.raises(OSError): + seeker.unindex(creder.said) + with pytest.raises(keriaing.IndexNotReadyError): + seeker.find({}) + seeker.unindex(creder.said) + assert not seeker.failures + assert all(not list(db.getItemIter()) for db in seeker.indexes.values())