From e924d09ff55985f463bc5f998ab117e4b60c4806 Mon Sep 17 00:00:00 2001 From: Kent Bull Date: Sat, 31 Oct 2026 20:47:07 -0600 Subject: [PATCH 1/4] Advance acceptance and webhook work through durable phases Queue acceptance when verification completes, and queue delivery in the acceptance or retirement transaction. Resume the single active delivery after restart instead of scanning completed result and outbox history. Bound webhook attempts, retain failed events in a dead-letter phase, and provide an explicit local retry command. Keep authentication, immutable event bytes and destination cooldown intact. This intentionally requires fresh application stores without migrations. Focused persistence, delivery and acceptance checks passed, including atomic phase recovery and exhausted attempts. The full fresh installed-wheel suite is running for the coordinated Oracle and Comply review. --- docs/operations.md | 40 +++++----- protocol/verifier-api-v1/README.md | 11 ++- src/eoa_verifier/associations/accepting.py | 6 +- src/eoa_verifier/delivery/delivering.py | 44 +++++------ src/eoa_verifier/persistence/basing.py | 89 ++++++++++++++++++++-- src/eoa_verifier/persistence/records.py | 7 ++ src/eoa_verifier/runtime/cli.py | 26 +++++++ src/eoa_verifier/runtime/config.py | 4 +- src/eoa_verifier/runtime/serving.py | 1 + tests/delivery/test_delivering.py | 59 +++++++++++++- tests/persistence/test_basing.py | 4 + 11 files changed, 231 insertions(+), 60 deletions(-) diff --git a/docs/operations.md b/docs/operations.md index 0551dde..1c05527 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -84,7 +84,8 @@ Retiring an old association does not retire its replacement. ## Delivery failures Transient network/HTTP failures retry automatically with persisted destination -cooldown. Each attempt signs the same immutable event bytes anew. Only an expected +cooldown, up to `--webhook-max-attempts` (default three). Exhaustion moves the event +to the durable dead-letter queue. Each attempt signs the same immutable event bytes anew. Only an expected authenticated HTTP 200 ACK completes it. Observation age never triggers refresh. Malformed HTTP chunk framing closes the affected client without stopping sibling tasks. RPC observations remain retryable; malformed webhook responses leave their @@ -98,28 +99,25 @@ Local operators can inspect `store.destinations.get(keys=(event.destination,))` for the destination's failure count and `nextAttemptAt` (UTC Unix seconds). These scheduling records remain durable and drive the sender; they are absent from public GET. -An embedding application can call `service.sender.request(event_id)`. For a -standalone process, stop it and use its installed Python to unblock the **current** -event with the same store coordinates, then restart. This preserves the event and destination cooldown, recording the -retry request as its current reason; it does not mark an ACK: - -```python -from keri.db import dbing -from eoa_verifier.persistence.basing import VerifierBaser - -with dbing.openLMDB(cls=VerifierBaser, name="verifier", base="", - headDirPath="/var/lib/eoa-verifier", temp=False) as store: - event_id = ":" # From the public status response. - event = store.outbox.get(keys=(event_id,)) - if event is None or event.acknowledged: - raise ValueError("event is unknown or already acknowledged") - status = store.associations.get(keys=(event.associationSaid,)) - if status.eventId != event_id: - raise ValueError("only the current association event can resume") - store.delivery_result(event_id, error="operator requested retry after correction", - blocked=False) +Acceptance and delivery are distinct durable phases. `accepting.` contains only +unfinished acceptance; `delivery-ready.` and the single `delivery-active.` slot +contain unfinished outbound work. `delivery-dead.` retains exhausted/permanent +failures. Completed verification/results and immutable outbox history are not +scanned to discover delivery work. These are breaking storage changes; use fresh +stores rather than expecting backfill or migration. + +After correcting the cause, stop the service and resume the current dead letter: + +```sh +eoa-verifier retry-delivery "$EVENT_ID" --name verifier --head-dir /var/lib/eoa-verifier ``` +Use the same name/base/head directory as startup, then restart. An embedding +application can call `service.sender.request(event_id)`. Both paths explicitly +requeue a dead letter and reset its bounded attempt budget, retaining immutable +event bytes and destination cooldown. They never mark an ACK. An obsolete event +remains ineligible for delivery even if an operator retries it. + Do not edit event bytes, delete replay records or clear accepted/revoked status to retry delivery. There is no retry REST route. Undelivered revocation can leave a downstream mapping active until delivery and withdrawal finish. Source-chain diff --git a/protocol/verifier-api-v1/README.md b/protocol/verifier-api-v1/README.md index baefa72..03bcbd9 100644 --- a/protocol/verifier-api-v1/README.md +++ b/protocol/verifier-api-v1/README.md @@ -53,19 +53,24 @@ reassessments. Initial source-chain validation remains mandatory. ## Delivery and revocation -The sender rediscovers pending events across restart, validates HTTP success, +The sender resumes explicit LMDB delivery phases across restart, validates HTTP success, the signed request reference and event-storage acknowledgment before completion, and signs every retry anew. Permanent failures stay blocked until correction and -explicit resumption; transient failures retry automatically. Acceptance events replaced by terminal retirement +explicit resumption; transient failures retry up to a finite attempt budget. Acceptance events replaced by terminal retirement remain stored but are not sent after retirement. +Completed verification queues acceptance atomically. Acceptance consumes that +phase and queues its webhook obligation atomically. Delivery references move from +ready to one active slot, then leave active work on ACK or move to dead letters. +Completed results and outbox history are never scanned to discover delivery work. + Persist acceptance and its webhook obligation together. Deliver after commit; the receiver durably stores the status before acknowledging. Retry unacknowledged events across restart, preserving event identity and duplicate-safe processing. Use one HIO sender per configured destination. Configurable defaults are one request in flight, at least one second between starts (including successes), -and a 10-second overall request timeout. Transient failures use jittered +a 10-second overall request timeout, and three attempts per event before dead-lettering. Transient failures use jittered exponential backoff from 1–2 seconds to a 150–300-second cap; valid `Retry-After` can extend that delay. Persist destination-wide cooldown across restart, reset failures only on an authenticated ACK, and retain permanent errors for correction. diff --git a/src/eoa_verifier/associations/accepting.py b/src/eoa_verifier/associations/accepting.py index 1d8eed3..134a759 100644 --- a/src/eoa_verifier/associations/accepting.py +++ b/src/eoa_verifier/associations/accepting.py @@ -7,7 +7,7 @@ class AcceptanceDoer(doing.Doer): """Commit application acceptance using borrowed evidence and result stores. - A bounded result scan recovers completion-to-acceptance gaps after restart. + The accepting phase recovers completion-to-acceptance gaps after restart. Read locally stored issuance evidence; do not repeat cryptographic or account verification. Missing local evidence leaves the completed result available for recovery. Existing accepted status never expires or gets reverified here. @@ -20,8 +20,8 @@ def __init__(self, *, baser, rgy, destination=None, peer_aid=None, **kwa): super().__init__(**kwa) def recur(self, tyme): - """Inspect one result page per turn, retaining KERIpy/application store separation.""" - page = self.baser.result_batch(after=self.after) + """Inspect one unfinished acceptance per turn, retaining KERIpy/application store separation.""" + page = self.baser.acceptance_batch(after=self.after) if not page: self.after = "" for result in page: diff --git a/src/eoa_verifier/delivery/delivering.py b/src/eoa_verifier/delivery/delivering.py index 4598257..a43957f 100644 --- a/src/eoa_verifier/delivery/delivering.py +++ b/src/eoa_verifier/delivery/delivering.py @@ -9,7 +9,6 @@ from hio.base import doing from hio.core import http -from hio.help import decking from .authing import AuthenticationError, ServiceAuthenticator @@ -40,8 +39,8 @@ def __init__(self, message, *, retry_after=0.0): class WebhookSender(doing.DoDoer): """Own sequential attempts, destination pacing and authenticated completion. - Scan pending outbox events across restart. Transient failures cool down every - event for that destination; permanent failures wait for correction and explicit + Resume the durable active delivery across restart. Transient failures cool + down every event for that destination; permanent failures wait for correction and explicit request(event_id). Reuse stored bytes/target but sign every attempt anew. The injected UTC clock and uniform random source permit deterministic policy tests. """ @@ -57,6 +56,7 @@ def __init__( backoff_cap=150.0, clock=time.time, uniform=random.uniform, + max_attempts=3, **kwa, ): self.baser, self.hab, self.timeout = baser, hab, timeout @@ -66,31 +66,24 @@ def __init__( backoff_cap, ) self.clock, self.uniform = clock, uniform - self.requests = decking.Deck() - self.after = "" + if max_attempts < 1: + raise ValueError("max_attempts must be positive") + self.max_attempts = max_attempts super().__init__(doers=[doing.doify(self.send_do)], **kwa) def request(self, event_id): """Resume an event after correcting its failure; still respect destination cooldown.""" - if event_id not in self.requests: - self.requests.append(event_id) + self.baser.retry_delivery(event_id) def send_do(self, tymth, tock=0.0, **opts): - """Process requests sequentially; HIO child removal closes each HTTP client.""" + """Advance only durable delivery phases, closing each client before the next.""" yield tock while True: - if not self.requests: - page = self.baser.delivery_batch(after=self.after) - self.after = page[-1].eventId if page else "" - for event in page: - if not event.acknowledged and not event.blocked: - self.request(event.eventId) + event = self.baser.next_delivery() + if event is None: yield self.tock continue - event_id = self.requests.popleft() - event = self.baser.outbox.get(keys=(event_id,)) - if event is None or event.acknowledged: - continue + event_id = event.eventId status = self.baser.associations.get(keys=(event.associationSaid,)) if ( status is None @@ -105,7 +98,6 @@ def send_do(self, tymth, tock=0.0, **opts): continue schedule = self.baser.destinations.get(keys=(event.destination,)) if schedule.nextAttemptAt > self.clock(): - self.request(event_id) yield self.tock continue yield from self._attempt(event) @@ -113,7 +105,12 @@ def send_do(self, tymth, tock=0.0, **opts): def _attempt(self, event): """Persist pacing before I/O, then atomically record the result and cooldown.""" - self.baser.record_attempt( + if event.attempts >= self.max_attempts: + self.baser.delivery_result( + event.eventId, error="delivery attempt limit reached", blocked=True + ) + return + event = self.baser.record_attempt( event.eventId, next_attempt_at=self.clock() + self.interval ) try: @@ -125,7 +122,7 @@ def _attempt(self, event): except (_TransientFailure, OSError) as error: schedule = self.baser.destinations.get(keys=(event.destination,)) schedule.failures += 1 - # Clamp the exponent before computing it; failures can accumulate indefinitely. + # Bound the exponent independently of the configured attempt budget. exponent = min( schedule.failures - 1, math.ceil(math.log2(self.backoff_cap / self.backoff_base)), @@ -139,6 +136,7 @@ def _attempt(self, event): event.eventId, error=str(error) or type(error).__name__, schedule=schedule, + blocked=event.attempts >= self.max_attempts, ) else: self.baser.delivery_result(event.eventId) @@ -211,7 +209,9 @@ def _check_response(self, event, auth, sent, response): or ack["eventId"] != event.eventId or ack["stored"] is not True ): - raise ValueError("webhook ACK does not confirm storage of the expected event") + raise ValueError( + "webhook ACK does not confirm storage of the expected event" + ) def _retry_after(value, now): diff --git a/src/eoa_verifier/persistence/basing.py b/src/eoa_verifier/persistence/basing.py index 4bc5f52..8eea3c6 100644 --- a/src/eoa_verifier/persistence/basing.py +++ b/src/eoa_verifier/persistence/basing.py @@ -11,6 +11,7 @@ AcceptedNonce, AssociationStatus, Delivery, + DeliveryReference, DestinationSchedule, PendingVerification, ReplayClaim, @@ -46,6 +47,18 @@ def reopen(self, **kwa): db=self, subkey="accepted_nonces.", schema=AcceptedNonce ) self.outbox = koming.Komer(db=self, subkey="outbox.", schema=Delivery) + self.accepting = koming.Komer( + db=self, subkey="accepting.", schema=VerificationResult + ) + self.delivery_ready = koming.Komer( + db=self, subkey="delivery-ready.", schema=DeliveryReference + ) + self.delivery_active = koming.Komer( + db=self, subkey="delivery-active.", schema=DeliveryReference + ) + self.delivery_dead = koming.Komer( + db=self, subkey="delivery-dead.", schema=DeliveryReference + ) self.destinations = koming.Komer( db=self, subkey="destinations.", schema=DestinationSchedule ) @@ -108,6 +121,8 @@ def finish(self, result): if txn.get(key, db=self.pending.sdb) is None: raise ValueError("pending work is absent") txn.put(key, self.results.serializer(result), db=self.results.sdb) + if result.status == "verified": + txn.put(key, self.accepting.serializer(result), db=self.accepting.sdb) txn.delete(key, db=self.pending.sdb) def pending_batch(self, *, after="", limit=32): @@ -123,17 +138,54 @@ def claim_nonce(self, peer, nonce, expires_at): """ return self.replay_claims.put(keys=(peer, nonce), val=ReplayClaim(expires_at)) - def result_batch(self, *, after="", limit=32): - """Copy a bounded result page; close the read transaction before acceptance.""" - return self._batch(self.results, after=after, limit=limit) + def acceptance_batch(self, *, after="", limit=1): + """Copy unfinished acceptance only; completed results never schedule work.""" + return self._batch(self.accepting, after=after, limit=limit) def association_batch(self, *, after="", limit=32): """Copy a bounded status page for local TEL revocation reconciliation.""" return self._batch(self.associations, after=after, limit=limit) - def delivery_batch(self, *, after="", limit=32): - """Copy a bounded outbox page for pending-delivery discovery, including after restart.""" - return self._batch(self.outbox, after=after, limit=limit) + def next_delivery(self): + """Claim one ready event, or resume the single interrupted delivery.""" + with self.env.begin(write=True) as txn: + reference = self.delivery_active.deserializer( + txn.get(b"sender", db=self.delivery_active.sdb) + ) + if reference is None: + with txn.cursor(db=self.delivery_ready.sdb) as cursor: + if not cursor.first(): + return None + key, raw = cursor.item() + reference = self.delivery_ready.deserializer(raw) + txn.put( + b"sender", + self.delivery_active.serializer(reference), + db=self.delivery_active.sdb, + ) + txn.delete(key, db=self.delivery_ready.sdb) + return self.outbox.deserializer( + txn.get(reference.eventId.encode(), db=self.outbox.sdb) + ) + + def retry_delivery(self, event_id): + """Explicitly resume a corrected dead letter with a fresh bounded attempt budget.""" + key = event_id.encode() + with self.env.begin(write=True) as txn: + reference = self.delivery_dead.deserializer( + txn.get(key, db=self.delivery_dead.sdb) + ) + if reference is None: + raise ValueError("unknown dead-letter event") + event = self.outbox.deserializer(txn.get(key, db=self.outbox.sdb)) + event.blocked, event.error, event.attempts = False, "", 0 + txn.put(key, self.outbox.serializer(event), db=self.outbox.sdb) + txn.put( + key, + self.delivery_ready.serializer(reference), + db=self.delivery_ready.sdb, + ) + txn.delete(key, db=self.delivery_dead.sdb) def _batch(self, table, *, after, limit): """Seek strictly after a key and release the LMDB cursor before returning.""" @@ -250,6 +302,7 @@ def accept(self, said, *, association, nonce, destination=None, peer_aid=None): self.associations.serializer(rejected), db=self.associations.sdb, ) + txn.delete(key, db=self.accepting.sdb) return rejected accepted = AssociationStatus( said, @@ -273,12 +326,18 @@ def accept(self, said, *, association, nonce, destination=None, peer_aid=None): self.outbox.serializer(event), db=self.outbox.sdb, ) + txn.put( + event.eventId.encode(), + self.delivery_ready.serializer(DeliveryReference(event.eventId)), + db=self.delivery_ready.sdb, + ) txn.put( destination.encode(), self.destinations.serializer(DestinationSchedule()), db=self.destinations.sdb, overwrite=False, ) + txn.delete(key, db=self.accepting.sdb) return accepted def retire(self, said): @@ -328,6 +387,11 @@ def retire(self, said): self.outbox.serializer(event), db=self.outbox.sdb, ) + txn.put( + event.eventId.encode(), + self.delivery_ready.serializer(DeliveryReference(event.eventId)), + db=self.delivery_ready.sdb, + ) return retired def record_attempt(self, event_id, *, next_attempt_at=None): @@ -382,6 +446,19 @@ def delivery_result(self, event_id, *, error="", blocked=False, schedule=None): txn.put( event_id.encode(), self.outbox.serializer(event), db=self.outbox.sdb ) + if event.acknowledged or event.blocked: + txn.delete(event_id.encode(), db=self.delivery_ready.sdb) + active = self.delivery_active.deserializer( + txn.get(b"sender", db=self.delivery_active.sdb) + ) + if active and active.eventId == event_id: + txn.delete(b"sender", db=self.delivery_active.sdb) + if event.blocked: + txn.put( + event_id.encode(), + self.delivery_dead.serializer(DeliveryReference(event_id)), + db=self.delivery_dead.sdb, + ) if event.acknowledged: raw = txn.get(event.destination.encode(), db=self.destinations.sdb) schedule = self.destinations.deserializer(raw) diff --git a/src/eoa_verifier/persistence/records.py b/src/eoa_verifier/persistence/records.py index a4f63d8..7b60eaa 100644 --- a/src/eoa_verifier/persistence/records.py +++ b/src/eoa_verifier/persistence/records.py @@ -92,3 +92,10 @@ class DestinationSchedule: failures: int = 0 nextAttemptAt: float = 0.0 + + +@dataclass +class DeliveryReference: + """One event's membership in a delivery phase; bytes remain in the outbox.""" + + eventId: str diff --git a/src/eoa_verifier/runtime/cli.py b/src/eoa_verifier/runtime/cli.py index 8b9b6ac..c451017 100644 --- a/src/eoa_verifier/runtime/cli.py +++ b/src/eoa_verifier/runtime/cli.py @@ -103,7 +103,33 @@ def main(argv=None): default=150.0, help="Retry lower-bound cap in seconds; upper is twice this (default: 150)", ) + start.add_argument("--webhook-max-attempts", type=int, default=3) + retry = commands.add_parser( + "retry-delivery", help="Resume a corrected dead letter with service stopped" + ) + retry.add_argument("event_id") + retry.add_argument("--name", default="eoa-verifier") + retry.add_argument("--base", default="") + retry.add_argument("--head-dir") args = vars(parser.parse_args(argv)) + if args["command"] == "retry-delivery": + from keri.db import dbing + + from eoa_verifier.persistence.basing import VerifierBaser + + try: + with dbing.openLMDB( + cls=VerifierBaser, + name=args["name"], + base=args["base"], + headDirPath=args["head_dir"], + temp=False, + ) as baser: + baser.retry_delivery(args["event_id"]) + except (ValueError, OSError) as exc: + print(f"eoa-verifier: {exc}", file=sys.stderr) + return 1 + return 0 args.pop("command") args.pop("action") try: diff --git a/src/eoa_verifier/runtime/config.py b/src/eoa_verifier/runtime/config.py index d796b8e..a7ef7e8 100644 --- a/src/eoa_verifier/runtime/config.py +++ b/src/eoa_verifier/runtime/config.py @@ -8,7 +8,6 @@ from keri.core import coring - @dataclass(frozen=True) class ServiceConfig: """Service identity, local storage and initial-verification network settings.""" @@ -41,6 +40,7 @@ class ServiceConfig: webhook_url: str | None = None webhook_aid: str | None = None # Operational seconds: one in-flight request; backoff range is [lower, 2 * lower]. + webhook_max_attempts: int = 3 webhook_timeout: float = 10.0 webhook_interval: float = 1.0 webhook_backoff_base: float = 1.0 @@ -48,6 +48,8 @@ class ServiceConfig: def __post_init__(self): """Reject invalid verification configuration before opening resources.""" + if type(self.webhook_max_attempts) is not int or self.webhook_max_attempts < 1: + raise ValueError("webhook max attempts must be a positive integer") timings = ( self.webhook_timeout, self.webhook_interval, diff --git a/src/eoa_verifier/runtime/serving.py b/src/eoa_verifier/runtime/serving.py index 7ac4d5b..44d0b6e 100644 --- a/src/eoa_verifier/runtime/serving.py +++ b/src/eoa_verifier/runtime/serving.py @@ -140,6 +140,7 @@ def __init__(self, config, *, hby, rgy, baser, noter, **kwa): baser=baser, hab=hab, timeout=config.webhook_timeout, + max_attempts=config.webhook_max_attempts, interval=config.webhook_interval, backoff_base=config.webhook_backoff_base, backoff_cap=config.webhook_backoff_cap, diff --git a/tests/delivery/test_delivering.py b/tests/delivery/test_delivering.py index f43c413..c159f41 100644 --- a/tests/delivery/test_delivering.py +++ b/tests/delivery/test_delivering.py @@ -107,7 +107,9 @@ def on_post(self, req, rep): status = ( 500 if reply == "signed-error" - else 401 if reply == "unauthorized" else 200 + else 401 + if reply == "unauthorized" + else 200 ) headers, _ = receiver.sign( method=req.method, @@ -161,7 +163,7 @@ def on_post(self, req, rep): backoff_base=0.05, backoff_cap=0.05, ) - # The sender discovers the committed event; intake need not enqueue it again. + # Acceptance atomically queued this event; the sender reads only its work phase. def wait_for_attempt(tymth, tock=0.0, **kwa): """Stop after one recorded result so failed ACKs cannot be hidden by retries.""" @@ -321,7 +323,9 @@ def lower_bound(lower, upper): ranges.append((lower, upper)) return lower - sender = WebhookSender(baser=outbox, hab=None, clock=clock, uniform=lower_bound) + sender = WebhookSender( + baser=outbox, hab=None, clock=clock, uniform=lower_bound, max_attempts=12 + ) def attempt(event): """Hold each attempt open over scheduler turns, then fail ten times before succeeding.""" @@ -419,7 +423,7 @@ def corrected(event): with patch.object(resumed, "_send", corrected): scheduler.do(doers=[resumed], tyme=4) delivered = outbox.outbox.get(keys=(accepted.eventId,)) - assert delivered.acknowledged and not delivered.blocked and delivered.attempts == 2 + assert delivered.acknowledged and not delivered.blocked and delivered.attempts == 1 def test_retry_after_supports_seconds_and_http_date(): @@ -442,3 +446,50 @@ def test_retry_after_supports_seconds_and_http_date(): assert caught.value.retry_after == 600 assert _retry_after("nonsense", now) == _retry_after("-1", now) == 0 assert _retry_after(future, 1700) == 0 + + +def test_transient_attempt_budget_moves_to_dead_letter_without_history_scan(outbox): + """A finite sender stops after three failures and restart never discovers it again.""" + accepted = accept(outbox, "bounded") + sender = WebhookSender( + baser=outbox, + hab=None, + interval=0.01, + backoff_base=0.01, + backoff_cap=0.01, + clock=lambda: 1000, + uniform=lambda low, high: low, + ) + + def unavailable(event): + yield 0.0 + raise TimeoutError("unavailable") + + for attempt in range(3): + event = outbox.next_delivery() + assert event.eventId == accepted.eventId + with patch.object(sender, "_send", unavailable): + list(sender._attempt(event)) + event = outbox.outbox.get(keys=(accepted.eventId,)) + assert event.blocked and not event.acknowledged and event.attempts == 3 + assert outbox.delivery_dead.get(keys=(accepted.eventId,)) is not None + outbox.close() + outbox.reopen() + assert outbox.next_delivery() is None + outbox.retry_delivery(accepted.eventId) + assert outbox.next_delivery().attempts == 0 + + +def test_delivery_phase_resumes_active_and_releases_completed(outbox): + """A crash retains the active event; ACK atomically removes its scheduling reference.""" + accepted = accept(outbox, "phase") + event = outbox.next_delivery() + assert event.eventId == accepted.eventId + assert outbox.delivery_ready.cntAll() == 0 + outbox.close() + outbox.reopen() + assert outbox.next_delivery() == event + outbox.delivery_result(event.eventId) + assert outbox.delivery_active.cntAll() == 0 + assert outbox.next_delivery() is None + assert outbox.outbox.get(keys=(event.eventId,)).acknowledged diff --git a/tests/persistence/test_basing.py b/tests/persistence/test_basing.py index a45b31a..4303567 100644 --- a/tests/persistence/test_basing.py +++ b/tests/persistence/test_basing.py @@ -42,6 +42,7 @@ def test_duplicates_completion_and_restart(tmp_path): ) assert baser.pending.get(keys=("b",)) is None assert baser.results.get(keys=("b",)) == result + assert baser.acceptance_batch() == [result] finally: baser.close() @@ -86,6 +87,7 @@ def begin(self, **kwa): baser.finish(VerificationResult("a", "verified")) assert baser.pending.get(keys=("a",)) == work assert baser.results.get(keys=("a",)) is None + assert baser.accepting.cntAll() == 0 baser.finish(VerificationResult("a", "rejected", "invalid proof")) assert baser.pending.get(keys=("a",)) is None assert baser.results.get(keys=("a",)).reason == "invalid proof" @@ -97,6 +99,8 @@ def test_acceptance_and_delivery_progress_survive_reopen(verified_store): baser.close() baser.reopen() accepted = accept_verified_result(baser) + assert baser.acceptance_batch() == [] + assert baser.delivery_ready.get(keys=(accepted.eventId,)) is not None baser.record_attempt(accepted.eventId) baser.delivery_result(accepted.eventId, error="connection failed") event = baser.outbox.get(keys=(accepted.eventId,)) From 804a152c2209466135d09dfbe70086b35a92e43f Mon Sep 17 00:00:00 2001 From: Kent Bull Date: Sat, 31 Oct 2026 21:20:59 -0600 Subject: [PATCH 2/4] Replace revocation scans with atomic native TEL handoffs Record accepted revocation work in the same registry transaction as KERIpy's TEL index. Consume one handoff at a time, committing application retirement before acknowledging it, so restart recovery no longer scans association history or depends on transient cues. The service owns a narrow Reger subclass against pinned GLEIF KERI 1.2.19. Focused tests cover both revocation variants, write rollback and the retirement acknowledgement gap; all four witnessed IPEX/Anvil scenarios passed. --- src/eoa_verifier/associations/retiring.py | 38 +++----- src/eoa_verifier/persistence/registry.py | 49 ++++++++++ src/eoa_verifier/runtime/serving.py | 6 +- tests/persistence/test_registry.py | 111 ++++++++++++++++++++++ tests/support/services.py | 5 +- 5 files changed, 181 insertions(+), 28 deletions(-) create mode 100644 src/eoa_verifier/persistence/registry.py create mode 100644 tests/persistence/test_registry.py diff --git a/src/eoa_verifier/associations/retiring.py b/src/eoa_verifier/associations/retiring.py index 4e9e5ec..073a885 100644 --- a/src/eoa_verifier/associations/retiring.py +++ b/src/eoa_verifier/associations/retiring.py @@ -1,38 +1,28 @@ -"""Reconcile accepted verified association revocation with durable application status.""" +"""Consume accepted TEL revocation handoffs, one credential per scheduler turn.""" from hio.base import doing -from keri import kering class RetirementDoer(doing.Doer): - """Borrow stores and scan a bounded page of associations each scheduler turn. + """Borrow both stores; retire locally before acknowledging the native handoff. - Read accepted local TEL state, without verification refreshes, peer polling or - account/source checks. The scan recovers KERIpy/application commit gaps after - restart and does not rely on transient cues or a new Grant notification. + A crash between commits repeats an idempotent retirement. Revocation before + initial acceptance is handled by verification and the acceptance TEL guard; + unrelated credentials do not create application status or delivery events. """ def __init__(self, *, baser, rgy, tock=0.25, **kwa): + """Borrow the application store and service-owned VerifierReger.""" self.baser, self.rgy = baser, rgy - self.after = "" super().__init__(tock=tock, **kwa) def recur(self, tyme): - """Retire only the exact SAID whose KERIpy TEL has accepted rev/brv state.""" - page = self.baser.association_batch(after=self.after) - if not page: - self.after = "" - for association in page: - self.after = association.associationSaid - if association.status != "accepted": - continue - credential = self.rgy.reger.creds.get(keys=(self.after,)) - if credential is None: - continue - try: - state = self.rgy.reger.tevers[credential.regi].vcState(self.after) - except (KeyError, kering.MissingEntryError): - continue - if state is not None and state.et in ("rev", "brv"): - self.baser.retire(self.after) + """Apply one handoff; completed association history is never a work source.""" + handoff = self.rgy.reger.next_revocation() + if handoff is not None: + said, _ = handoff + association = self.baser.associations.get(keys=(said,)) + if association is not None and association.status == "accepted": + self.baser.retire(said) + self.rgy.reger.revocations.rem(keys=(said,)) return False diff --git a/src/eoa_verifier/persistence/registry.py b/src/eoa_verifier/persistence/registry.py new file mode 100644 index 0000000..0d1c2a3 --- /dev/null +++ b/src/eoa_verifier/persistence/registry.py @@ -0,0 +1,49 @@ +"""KERIpy registry with a durable handoff for accepted credential revocations.""" + +from keri.core import serdering +from keri.db import dbing, subing +from keri.vdr import viring + + +class VerifierReger(viring.Reger): + """Keep revocation handoffs in the same LMDB transaction as the accepted TEL index. + + In pinned KERIpy, Tever.logEvent calls putTel only after validating the TEL + event and its anchor. Event bytes have already been persisted in tvts. This + narrow override preserves native validation and replaces the final index write + with an atomic index-plus-handoff write. Transient Tever cues are not recovery + records. Changes to this upstream boundary require requalification. + """ + + def reopen(self, **kwa): + """Bind the handoff after opening all native registry subdatabases.""" + super().reopen(**kwa) + try: + self.revocations = subing.Suber(db=self, subkey="verifier-revocations.") + except Exception: + self.close() + raise + return self.env + + def putTel(self, key, val): + """Insert an accepted TEL index and, for rev/brv, its exact credential SAID.""" + pre, _ = dbing.splitKeySN(key) + with self.env.begin(write=True) as txn: + raw = txn.get(dbing.dgKey(pre, val), db=self.tvts) + if raw is None: + raise ValueError("accepted TEL index requires stored event bytes") + event = serdering.SerderKERI(raw=bytes(raw)) + inserted = txn.put(key, val, db=self.tels, overwrite=False) + if inserted and event.ilk in ("rev", "brv"): + txn.put( + event.pre.encode(), event.said.encode(), db=self.revocations.sdb + ) + return inserted + + def next_revocation(self): + """Return one detached (credential SAID, TEL event SAID) handoff, or None.""" + with self.env.begin(db=self.revocations.sdb) as txn, txn.cursor() as cursor: + if cursor.first(): + key, value = cursor.item() + return key.decode(), value.decode() + return None diff --git a/src/eoa_verifier/runtime/serving.py b/src/eoa_verifier/runtime/serving.py index 44d0b6e..e14dc7e 100644 --- a/src/eoa_verifier/runtime/serving.py +++ b/src/eoa_verifier/runtime/serving.py @@ -21,13 +21,15 @@ from keri.end import ending from keri.peer import exchanging from keri.vc import protocoling -from keri.vdr import credentialing, eventing as veventing, verifying, viring +from keri.vdr import credentialing, verifying +from keri.vdr import eventing as veventing from ..associations.accepting import AcceptanceDoer from ..associations.retiring import RetirementDoer from ..associations.statusing import StatusEnd from ..delivery.delivering import WebhookSender from ..persistence.basing import VerifierBaser +from ..persistence.registry import VerifierReger from ..receiving.directing import CesrEnd, Receiver from ..receiving.grants import GrantNotificationDoer from ..verification.constants import ASSOCIATION_SCHEMA @@ -209,7 +211,7 @@ def run_service(config: ServiceConfig, *, expire: float = 0.0): keeping.openKS(temp=config.temp, **options) as ks, basing.openDB(temp=config.temp, **options) as db, configing.openCF(temp=config.temp, **options) as cf, - viring.openReger(temp=config.temp, db=db, **options) as reger, + dbing.openLMDB(cls=VerifierReger, temp=config.temp, db=db, **options) as reger, dbing.openLMDB(cls=VerifierBaser, temp=config.temp, **options) as baser, dbing.openLMDB(cls=notifying.Noter, temp=config.temp, **options) as noter, ): diff --git a/tests/persistence/test_registry.py b/tests/persistence/test_registry.py new file mode 100644 index 0000000..220b807 --- /dev/null +++ b/tests/persistence/test_registry.py @@ -0,0 +1,111 @@ +"""Atomic native TEL handoffs and idempotent application retirement.""" + +from types import SimpleNamespace +from unittest.mock import patch + +import pytest +from keri import core +from keri.db import dbing +from keri.vdr import eventing + +from eoa_verifier.associations.retiring import RetirementDoer +from eoa_verifier.persistence.registry import VerifierReger +from tests.support.acceptance import accept_verified_result + + +def revocation(*, backers=False): + """Make a syntactic TEL event; integration tests separately establish native validation.""" + said = core.Diger(ser=b"credential").qb64 + registry = core.Diger(ser=b"registry").qb64 + digest = core.Diger(ser=b"issuance").qb64 + if backers: + return eventing.backerRevoke(said, registry, 0, registry, digest) + return eventing.revoke(said, registry, digest) + + +@pytest.mark.parametrize("backers", [False, True]) +def test_accepted_tel_and_handoff_survive_reopen(tmp_path, backers): + """Both native revocation variants commit one handoff; native replay cannot recreate it.""" + with dbing.openLMDB( + cls=VerifierReger, name="handoff", headDirPath=str(tmp_path), temp=False + ) as reger: + event = revocation(backers=backers) + key = dbing.snKey(event.pre, event.sn) + reger.putTvt(dbing.dgKey(event.pre, event.said), event.raw) + assert reger.putTel(key, event.saidb) + reger.close() + reger.reopen() + assert bytes(reger.getTel(key)) == event.saidb + assert reger.next_revocation() == (event.pre, event.said) + reger.revocations.rem(keys=(event.pre,)) + assert not reger.putTel(key, event.saidb) + assert reger.next_revocation() is None + + +def test_failed_handoff_write_rolls_back_native_acceptance(): + """A fault after the TEL index write commits neither index nor handoff.""" + with dbing.openLMDB(cls=VerifierReger) as reger: + event = revocation() + key = dbing.snKey(event.pre, event.sn) + reger.putTvt(dbing.dgKey(event.pre, event.said), event.raw) + real = reger.env + + class Transaction: + def __enter__(self): + self.txn = real.begin(write=True) + return self + + def __exit__(self, kind, value, traceback): + self.txn.abort() if kind else self.txn.commit() + + def get(self, *args, **kwargs): + return self.txn.get(*args, **kwargs) + + def put(self, *args, **kwargs): + if kwargs["db"] == reger.revocations.sdb: + raise RuntimeError("handoff unavailable") + return self.txn.put(*args, **kwargs) + + with ( + patch.object( + reger, "env", SimpleNamespace(begin=lambda **kwargs: Transaction()) + ), + pytest.raises(RuntimeError, match="handoff unavailable"), + ): + reger.putTel(key, event.saidb) + assert reger.getTel(key) is None + assert reger.next_revocation() is None + assert reger.putTel(key, event.saidb) + + +def test_retirement_ack_gap_repeats_only_the_same_event(verified_store, tmp_path): + """Reopening after application commit repeats its exact event before clearing the handoff.""" + baser = verified_store + accepted = accept_verified_result(baser) + with dbing.openLMDB( + cls=VerifierReger, name="retirement", headDirPath=str(tmp_path), temp=False + ) as reger: + reger.revocations.put(keys=("association",), val="revocation") + worker = RetirementDoer(baser=baser, rgy=SimpleNamespace(reger=reger)) + with ( + patch.object( + reger.revocations, + "rem", + side_effect=RuntimeError("interrupted acknowledgement"), + ), + pytest.raises(RuntimeError, match="interrupted acknowledgement"), + ): + worker.recur(0) + retired = baser.associations.get(keys=("association",)) + assert ( + retired.status == "revoked" and retired.association == accepted.association + ) + body = baser.outbox.get(keys=(retired.eventId,)).body + baser.close() + baser.reopen() + reger.close() + reger.reopen() + worker.recur(0) + assert reger.next_revocation() is None + assert baser.outbox.get(keys=(retired.eventId,)).body == body + assert baser.outbox.cntAll() == 2 diff --git a/tests/support/services.py b/tests/support/services.py index afa819e..d5f2816 100644 --- a/tests/support/services.py +++ b/tests/support/services.py @@ -16,8 +16,9 @@ def verifier_service(config): """ from keri.app import configing, keeping, notifying from keri.db import basing, dbing - from keri.vdr import credentialing, viring + from keri.vdr import credentialing + from eoa_verifier.persistence.registry import VerifierReger from eoa_verifier.persistence.basing import VerifierBaser from eoa_verifier.runtime.serving import VerifierService @@ -26,7 +27,7 @@ def verifier_service(config): keeping.openKS(temp=config.temp, **options) as ks, basing.openDB(temp=config.temp, **options) as db, configing.openCF(temp=config.temp, **options) as cf, - viring.openReger(temp=config.temp, db=db, **options) as reger, + dbing.openLMDB(cls=VerifierReger, temp=config.temp, db=db, **options) as reger, dbing.openLMDB(cls=VerifierBaser, temp=config.temp, **options) as baser, dbing.openLMDB(cls=notifying.Noter, temp=config.temp, **options) as noter, ): From 6a2c2b3c9cab284cfa3a48fcd2cbfbec39f38ee0 Mon Sep 17 00:00:00 2001 From: Kent Bull Date: Sat, 31 Oct 2026 21:21:57 -0600 Subject: [PATCH 3/4] Replace paged intake and verification with durable single-item phases Claim one Grant or verification attempt before processing, persist retry deadlines and finite budgets, and dead-letter exhausted work for explicit operator resumption. Replace acceptance pages with one unfinished obligation and stop missing or revoked evidence instead of revisiting it indefinitely. Delete batch readers, scan bookmarks and the in-memory retry calendar. Completion requires active verification. Public stored status, retry commands, protocol documentation and ADRs describe the breaking layout with no migration or compatibility path. Focused phase, rollback, restart, fairness and operator-command checks pass; full installed-wheel and paired qualification follow this exact commit. --- README.md | 62 ++-- adrs/0004-component-organization.md | 7 +- adrs/0005-accepted-association-nonces.md | 8 +- docs/operations.md | 41 ++- protocol/verifier-api-v1/README.md | 9 +- src/eoa_verifier/associations/accepting.py | 42 ++- src/eoa_verifier/associations/statusing.py | 15 +- src/eoa_verifier/persistence/basing.py | 285 +++++++++++++++--- src/eoa_verifier/persistence/records.py | 15 +- src/eoa_verifier/receiving/grants.py | 93 +++--- src/eoa_verifier/runtime/cli.py | 28 +- src/eoa_verifier/verification/coordinating.py | 209 +++++-------- tests/associations/test_statusing.py | 32 +- tests/conftest.py | 1 + tests/delivery/test_delivering.py | 3 + tests/integration/test_ipex_verification.py | 9 +- tests/persistence/test_accepted_nonces.py | 2 + tests/persistence/test_basing.py | 16 +- tests/receiving/test_grants.py | 67 ++-- tests/runtime/test_cli.py | 31 ++ tests/verification/test_coordinating.py | 93 ++++-- 21 files changed, 717 insertions(+), 351 deletions(-) diff --git a/README.md b/README.md index 9da2653..501fa70 100644 --- a/README.md +++ b/README.md @@ -33,13 +33,13 @@ current key state must already be KERIpy-accepted by this verifier; missing keys leave delivery blocked pending correction. Omitting both retains verification-only operation. Public `GET /v1/associations/{said}/status` returns stored `pending`, `rejected`, -`verified`, `accepted` or `revoked` status and any initial account observation. +`verifying`, `waiting`, `dead-letter`, `verified`, `accepted` or `revoked` status and any initial account observation. Accepted/retired records also expose their current event’s delivery progress and errors. Unknown SAIDs return 404. GET requires no signature and performs no RPC or refresh. The sender keeps one request in flight and spaces starts by at least one second, -including successes. Connection failures, timeouts, HTTP 408/429 and 5xx errors +including successes. Up to three attempts handle connection failures, timeouts, HTTP 408/429 and 5xx errors (except 501/505) retry automatically with jittered backoff from 1–2 seconds to 150–300 seconds. A valid `Retry-After` is a minimum, even beyond that cap. Cooldown applies to the whole destination and survives restart. Only the expected @@ -71,7 +71,7 @@ account checks run, and Ethereum publication remains the oracle's responsibility | `verification` | `coordinating`, `credentials`, `eoa`, `worker`, `rpc`: initial credential/wallet/account verification; `constants`, `schema_cache`, `errors` support that contract. | | `associations` | `accepting`, `retiring`, `statusing`: application acceptance, verified association revocation and public stored status. | | `delivery` | `authing`, `delivering`: signed transport/replay protection and webhook attempts, retry pacing and ACK policy. | -| `persistence` | `records`, `basing`: durable record schemas and atomic verification, acceptance/outbox and delivery transitions. | +| `persistence` | `records`, `basing`, `registry`: durable record schemas and atomic verification, acceptance/outbox and delivery transitions. | These are sibling leaf component packages. Runtime composes them; workflow components depend on persistence and KERIpy evidence, not on runtime or each @@ -85,14 +85,23 @@ or unusable RPC responses leave unfinished work for retry. KERIpy acceptance is separate from receipt of bytes; KELs, TELs, credentials and schemas live in the KERIpy Habery/Reger stores, not in the work record. -Unfinished verification lives in `pending`; completed initial checks live in -`results` with a `verified` or `rejected` outcome. Completion writes the result -and removes pending work in one LMDB transaction. Duplicate Grants preserve the -first Grant and never re-enqueue completed work. Verified results retain the -wallet and initial account observation; they do not mean application acceptance, -webhook delivery or Ethereum endorsement. Restart rediscovers pending work. - -`AcceptanceDoer` reads completed results and locally accepted issuance evidence +Each worker handles one item at a time. A native Grant notice is durably handed +into `grant-active.` before its native notification is removed. Replay creates +`pending.` verification work. The coordinator moves one candidate into +`verifying.` and charges its attempt before starting the EOA check. Missing +material or transient RPC errors move it to `waiting.` with a persisted UTC retry +deadline. A time-ordered deadline index selects the next due item; no work-history +scan or in-memory retry calendar exists. Completion atomically writes `results.`, +removes active work and, on success, queues `accepting.`. + +Grant replay and verification each allow three attempts, five seconds apart. +Interrupted attempts count. Exhaustion retains diagnostics in `grant-dead.` or +`verification-dead.` until explicit operator retry. Definitively invalid proofs +produce a rejected result. Duplicate Grants preserve the original work and never +re-enqueue completed or dead-letter candidates. Restart resumes durable phases. +A verification result is not acceptance, webhook delivery or an Ethereum endorsement. + +`AcceptanceDoer` takes one unfinished `accepting.` record and locally accepted issuance evidence without repeating initial checks. Acceptance permanently binds the exact issuer/nonce to one SAID, atomically with immutable facts and any configured outbox obligation. Another SAID using that pair becomes locally `rejected` with `NONCE_REUSED`; its @@ -105,24 +114,23 @@ Acceptance runs with or without webhooks. With no target, public `delivery` is n enabling delivery later does not backfill events for locally accepted records. Restart recovers results awaiting acceptance. KERIpy evidence lives in a separate database and is not part of the application transaction. Missing evidence or -already-known revocation prevents first acceptance. Observation age does not +already-known revocation moves the acceptance to `acceptance-dead.` for inspection. Observation age does not invalidate an accepted record. -`RetirementDoer` scans bounded pages of accepted records against locally accepted -association TEL state. KERIpy `rev`/`brv` retires only that SAID and atomically -creates its second event when an original delivery exists, preserving original issuance facts, observation and -webhook destination. Duplicate evidence and restart do not create more events or -revive retirement. A different association for the same wallet is untouched; -ownership selection belongs to the oracle. - -IPEX Grant delivers supporting KEL/TEL artifacts; the Grant’s embedded -issuance or credential alone does not prove revocation. The existing shared parser -and escrows validate those artifacts. Retirement also recovers from stored KERIpy -state after restart, so it requires neither a retained cue nor another Grant. -Missing or escrowed evidence leaves accepted status unchanged. This local scan -performs no account/source reassessment or network refresh. Previously accepted -records still retire when webhook sending is disabled; their delivery obligations -remain stored for the original destination. +`VerifierReger` subclasses the pinned native registry at `putTel`, the final +accepted-TEL index write. It atomically writes a `verifier-revocations.` handoff +for `rev`/`brv` in that same registry environment. Native KERIpy validation and +escrows still decide whether an event is accepted. Unanchored evidence creates +no handoff. + +`RetirementDoer` consumes one handoff, retires only its exact accepted association +and commits its immutable second delivery event before acknowledging the handoff. +Restart safely repeats either side of this two-store commit boundary. Completed +association history is never scanned. Revocation before acceptance is caught by +the final verification check and the local acceptance guard. Original issuance +facts, observation and destination are preserved; other associations for the +wallet are untouched. Previously accepted records still retire with sending +disabled, retaining any original delivery obligations. `run_service()` owns shared stores through KERIpy context managers. `VerifierService` borrows those stores and composes the HIO tasks. HIO stops diff --git a/adrs/0004-component-organization.md b/adrs/0004-component-organization.md index 5cab98e..7fdbe38 100644 --- a/adrs/0004-component-organization.md +++ b/adrs/0004-component-organization.md @@ -46,12 +46,15 @@ Retain one VerifierBaser and one application LMDB transaction boundary. Completi writes results/removes pending work atomically. Acceptance and retirement each commit association status and its immutable outbox event together. Event creation stays beside these transitions; delivery sends stored bytes. KERIpy evidence -stores remain separate, with bounded recovery scans bridging commit gaps. +stores remain separate. Durable phase queues bridge commit gaps; the native +accepted-TEL index and its revocation handoff commit atomically in VerifierReger. +No completed-result or association-history scans schedule work. Keep authentication separate from ACK policy, verification separate from acceptance, and oracle ownership/chain publication outside this application. Preserve the coordinator's native-state recheck after RPC waits and the existing -HIO task/store lifetime. Table names, record fields and wire formats do not change. +HIO task/store lifetime. The subsequent durable-phase refactor changes storage +without compatibility readers; the authenticated event format remains unchanged. ## Import migration diff --git a/adrs/0005-accepted-association-nonces.md b/adrs/0005-accepted-association-nonces.md index 4064de8..153a75a 100644 --- a/adrs/0005-accepted-association-nonces.md +++ b/adrs/0005-accepted-association-nonces.md @@ -17,7 +17,7 @@ owns nonce syntax and signed commitments. obligation in one native synchronous LMDB write transaction. Insert without overwrite and inspect existing data in the same transaction. Inconsistent or orphaned claims abort acceptance. Native LMDB supplies process coordination; no -application locks, threads, queues or additional environment are needed. +application locks, threads or additional environment are needed for nonce claims. The typed `AcceptedNonce` record stores issuer, exact nonce and accepted SAID. Komer's ordinary issuer.nonce key is unambiguous under the credential profile and @@ -25,14 +25,14 @@ at most 173 bytes, within the pinned environment's 511-byte key limit. Hashing or custom key encodings add no value. Standard name/base/head-dir selects the existing application store. Persistent closure retains all claims. -KERIpy evidence and application state use separate transactions. A bounded -acceptance scan recovers completed verified results; invalid, pending or revoked +KERIpy evidence and application state use separate transactions. A dedicated +`accepting.` phase recovers completed verified results one at a time; invalid, pending or revoked evidence cannot burn a nonce. Target-free acceptance still claims the nonce, without an event. Later enabling delivery does not backfill those acceptances. ## Store and operational limits -The `issuer-nonce-ascii-v1` scope requires complete claim history. Startup rejects +The `durable-phases-v1` scope requires complete claim history. Startup rejects pre-policy or inconsistent acceptance stores; it does not migrate, backfill or recreate missing claims. The history audit currently holds accepted SAIDs in memory. Uniqueness applies within one preserved verifier store, not globally diff --git a/docs/operations.md b/docs/operations.md index 1c05527..895c722 100644 --- a/docs/operations.md +++ b/docs/operations.md @@ -30,7 +30,7 @@ KERIpy options for a new identity only. The application store is bound to its GEDA root and chain ID before workers start, including operation without webhook delivery. Changing either requires separate stores. Existing stores with completed results but no recorded scope are refused; preserve them and use fresh stores rather than guessing their original policy. Pre-policy stores are also refused: acceptance now requires permanent issuer/nonce -history under policy `issuer-nonce-ascii-v1`. Association nonces must contain +history under policy `durable-phases-v1`. Association nonces must contain 1–128 ASCII characters from `[A-Za-z0-9_-]`; no normalization is applied. Use a deliberate fresh store set; there is no migration or backfill. Never reset accepted history to evade nonce rejection. Enabling webhook delivery with the same root/chain remains supported, but does not @@ -81,6 +81,43 @@ when the association had an original outbox obligation. Local-only acceptance retires locally without an event. Retiring an old association does not retire its replacement. +## Verification and intake failures + +The service progresses one item per worker through dedicated durable phases: + +| Work | Ready / active | Waiting | Manual intervention | +| --- | --- | --- | --- | +| Grant replay | native Noter / `grant-active.` | `grant-waiting.` with `grant-due.` deadline index | `grant-dead.` | +| Initial verification | `pending.` / `verifying.` | `waiting.` with `verification-due.` deadline index | `verification-dead.` | +| Acceptance | `accepting.` | none: local evidence was already verified | `acceptance-dead.` | +| Verified revocation | `verifier-revocations.` in the native registry | none | unexpected storage errors stop the worker and retain work | + +Grant replay and verification allow three attempts with five-second UTC cooldowns. +The attempt commits before processing; an interruption consumes that attempt. +Due retries take precedence over fresh work. No batch paging, completed-history +scanning or in-memory retry timing participates. A missing Grant moves out of +native notifications so it cannot block later notices. Invalid Grants retain +diagnostics immediately; invalid credential proofs become terminal rejections. + +Public association GET distinguishes `pending`, `verifying`, `waiting` and +`dead-letter`, including attempts and the next eligible time. Acceptance failures +show `phase: acceptance`. Grant failures can precede knowing the credential SAID; +inspect `grant-dead.` records in the local application store for their notice ID, +Grant attributes and reason. Correct the missing material or RPC configuration, +stop the service, and explicitly resume the affected phase: + +```sh +eoa-verifier retry-grant "$NOTICE_ID" --name verifier --head-dir /var/lib/eoa-verifier +eoa-verifier retry-verification "$SAID" --name verifier --head-dir /var/lib/eoa-verifier +eoa-verifier retry-acceptance "$SAID" --name verifier --head-dir /var/lib/eoa-verifier +``` + +Retry renews only the selected operation's budget; it does not bypass validation, +revocation guards or nonce ownership. Known revocation cannot be repaired by retry. +These queues require fresh stores. There are no compatibility readers or migration. +The native `putTel` boundary is qualified against `gleif_keri==1.2.19`; upgrading +that dependency requires checking its accepted-event write order and requalifying. + ## Delivery failures Transient network/HTTP failures retry automatically with persisted destination @@ -88,7 +125,7 @@ cooldown, up to `--webhook-max-attempts` (default three). Exhaustion moves the e to the durable dead-letter queue. Each attempt signs the same immutable event bytes anew. Only an expected authenticated HTTP 200 ACK completes it. Observation age never triggers refresh. Malformed HTTP chunk framing closes the affected client without stopping sibling -tasks. RPC observations remain retryable; malformed webhook responses leave their +tasks. RPC observations use a three-attempt verification budget; malformed webhook responses leave their events blocked and unacknowledged for correction and explicit resumption. Permanent failures remain blocked until the cause is corrected; restart alone does not unblock them. Inspect public status and fix peer keys, authorization, diff --git a/protocol/verifier-api-v1/README.md b/protocol/verifier-api-v1/README.md index 03bcbd9..f6990d5 100644 --- a/protocol/verifier-api-v1/README.md +++ b/protocol/verifier-api-v1/README.md @@ -31,7 +31,9 @@ account rule against the configured chain ID/RPC at an identified canonical bloc Confirm KERIpy status after the initial RPC wait before accepting. These checks do not assess delegated-code safety or prove against later wallet-key theft. -Initial evidence or RPC unavailability leaves work `pending`; established failure +Initial evidence or RPC unavailability moves work to `waiting` with a durable +five-second cooldown. Three attempts exhaust into `dead-letter`; restart and +duplicate Grants do not renew the budget. Established failure produces `rejected`, and completed initial checks produce `verified`. With a webhook configured, acceptance commits status and an event. Without a webhook, acceptance commits locally without an outbox obligation (`delivery` is null). @@ -148,10 +150,11 @@ verifier status and cannot retire acceptance here. Contracts own their ## Stored status Public `GET /v1/associations/{said}/status` requires no caller KERI signature or -signed response. Return stored pending/verified/rejected/accepted/revoked status and reason, +signed response. Return stored pending/verifying/waiting/dead-letter/verified/rejected/accepted/revoked +status and reason, plus the last-known initial account observation: wallet address, chain ID, code, block number/hash and observation time. Unknown observations remain unknown. -Known pending/rejected candidates return `200`; unknown SAIDs return `404`. +Known candidates, including waiting and dead-letter work, return `200`; unknown SAIDs return `404`. Observation age is informational. GET performs no RPC, refresh or enrollment; its response does not replace authenticated status delivery to the oracle. Delivery progress describes the requested association's current event; shared diff --git a/src/eoa_verifier/associations/accepting.py b/src/eoa_verifier/associations/accepting.py index 134a759..0445af7 100644 --- a/src/eoa_verifier/associations/accepting.py +++ b/src/eoa_verifier/associations/accepting.py @@ -9,37 +9,35 @@ class AcceptanceDoer(doing.Doer): The accepting phase recovers completion-to-acceptance gaps after restart. Read locally stored issuance evidence; do not repeat cryptographic or account - verification. Missing local evidence leaves the completed result available for - recovery. Existing accepted status never expires or gets reverified here. + verification. Missing or revoked local evidence stops in a dead letter for + operator inspection. Existing accepted status never expires or gets reverified here. """ def __init__(self, *, baser, rgy, destination=None, peer_aid=None, **kwa): self.baser, self.rgy = baser, rgy self.destination, self.peer_aid = destination, peer_aid - self.after = "" super().__init__(**kwa) def recur(self, tyme): """Inspect one unfinished acceptance per turn, retaining KERIpy/application store separation.""" - page = self.baser.acceptance_batch(after=self.after) - if not page: - self.after = "" - for result in page: - self.after = result.associationSaid - if result.status != "verified" or self.baser.associations.get( - keys=(self.after,) - ): - continue - evidence = self.issuance_facts(self.after) - if evidence is not None: - association, nonce = evidence - self.baser.accept( - self.after, - association=association, - nonce=nonce, - destination=self.destination, - peer_aid=self.peer_aid, - ) + result = self.baser.next_acceptance() + if result is None: + return False + evidence = self.issuance_facts(result.associationSaid) + if evidence is None: + self.baser.stop_acceptance( + result.associationSaid, + "issuance evidence missing or revoked before acceptance", + ) + else: + association, nonce = evidence + self.baser.accept( + result.associationSaid, + association=association, + nonce=nonce, + destination=self.destination, + peer_aid=self.peer_aid, + ) return False def issuance_facts(self, said): diff --git a/src/eoa_verifier/associations/statusing.py b/src/eoa_verifier/associations/statusing.py index 8ee93fc..19ddad9 100644 --- a/src/eoa_verifier/associations/statusing.py +++ b/src/eoa_verifier/associations/statusing.py @@ -20,7 +20,8 @@ def on_get(self, req, rep, said): """ accepted = self.baser.associations.get(keys=(said,)) result = self.baser.results.get(keys=(said,)) - pending = self.baser.pending.get(keys=(said,)) + phase, pending = self.baser.verification_progress(said) + stopped = self.baser.acceptance_dead.get(keys=(said,)) if accepted is not None: data = asdict(accepted) event = ( @@ -39,6 +40,14 @@ def on_get(self, req, rep, said): if event is not None else None ) + elif stopped is not None: + data = { + "associationSaid": said, + "status": "dead-letter", + "phase": "acceptance", + "reason": stopped.reason, + "accountObservation": None, + } elif result is not None: data = { "associationSaid": said, @@ -56,8 +65,10 @@ def on_get(self, req, rep, said): elif pending is not None: data = { "associationSaid": said, - "status": "pending", + "status": phase, "reason": pending.reason, + "attempts": pending.attempts, + "nextAttemptAt": pending.nextAttemptAt, "accountObservation": None, } else: diff --git a/src/eoa_verifier/persistence/basing.py b/src/eoa_verifier/persistence/basing.py index 8eea3c6..48b2bef 100644 --- a/src/eoa_verifier/persistence/basing.py +++ b/src/eoa_verifier/persistence/basing.py @@ -3,9 +3,8 @@ import json import re from dataclasses import replace -from itertools import islice -from keri.db import dbing, koming +from keri.db import dbing, koming, subing from .records import ( AcceptedNonce, @@ -13,6 +12,7 @@ Delivery, DeliveryReference, DestinationSchedule, + GrantWork, PendingVerification, ReplayClaim, VerificationResult, @@ -34,6 +34,27 @@ def reopen(self, **kwa): self.pending = koming.Komer( db=self, subkey="pending.", schema=PendingVerification ) + self.verifying = koming.Komer( + db=self, subkey="verifying.", schema=PendingVerification + ) + self.waiting = koming.Komer( + db=self, subkey="waiting.", schema=PendingVerification + ) + self.verification_due = subing.Suber(db=self, subkey="verification-due.") + self.grant_due = subing.Suber(db=self, subkey="grant-due.") + self.verification_dead = koming.Komer( + db=self, subkey="verification-dead.", schema=PendingVerification + ) + self.grant_active = koming.Komer( + db=self, subkey="grant-active.", schema=GrantWork + ) + self.grant_waiting = koming.Komer( + db=self, subkey="grant-waiting.", schema=GrantWork + ) + self.grant_dead = koming.Komer(db=self, subkey="grant-dead.", schema=GrantWork) + self.acceptance_dead = koming.Komer( + db=self, subkey="acceptance-dead.", schema=VerificationResult + ) self.results = koming.Komer( db=self, subkey="results.", schema=VerificationResult ) @@ -66,7 +87,7 @@ def reopen(self, **kwa): def bind_verification_scope(self, *, trusted_geda_aid, chain_id): """Refuse another policy or previously completed results with unknown provenance.""" - scope = VerificationScope(trusted_geda_aid, chain_id, "issuer-nonce-ascii-v1") + scope = VerificationScope(trusted_geda_aid, chain_id, "durable-phases-v1") try: existing = self.scope.get(keys=("verification",)) except (TypeError, ValueError) as exc: @@ -86,30 +107,192 @@ def enqueue(self, work): """Insert new unfinished work once; completed or pending duplicates return False.""" key = work.associationSaid.encode() with self.env.begin(write=True) as txn: - if txn.get(key, db=self.results.sdb) is not None: + if any( + txn.get(key, db=table.sdb) is not None + for table in ( + self.results, + self.verifying, + self.waiting, + self.verification_dead, + ) + ): return False return txn.put( key, self.pending.serializer(work), db=self.pending.sdb, overwrite=False ) - def note_pending(self, said, reason): - """Update only waiting information, preserving identity and the first Grant reference.""" + def begin_grant(self, notice=None, *, now, max_attempts=3): + """Claim one native notice or resume an interrupted/local waiting replay. + + The caller removes the native notice only after this durable handoff. Its + ID remains in active work, so restart can finish that acknowledgement. + """ + with self.env.begin(write=True) as txn: + work = self.grant_active.deserializer( + txn.get(b"receiver", db=self.grant_active.sdb) + ) + if work is None: + work = due_record(txn, self.grant_due, self.grant_waiting, now) + if work is not None: + txn.delete(work.noticeId.encode(), db=self.grant_waiting.sdb) + elif notice is not None: + work = GrantWork(notice.rid, notice.attrs) + else: + return None + if work.attempts >= max_attempts: + work.reason = ( + work.reason or "Grant replay interrupted; attempt budget exhausted" + ) + txn.put( + work.noticeId.encode(), + self.grant_dead.serializer(work), + db=self.grant_dead.sdb, + ) + txn.delete(b"receiver", db=self.grant_active.sdb) + return None + work.attempts += 1 + txn.put( + b"receiver", + self.grant_active.serializer(work), + db=self.grant_active.sdb, + ) + return work + + def settle_grant( + self, work, *, reason="", next_attempt_at=0, invalid=False, max_attempts=3 + ): + """Acknowledge replay or atomically retain failed material for waiting/manual recovery.""" + with self.env.begin(write=True) as txn: + if reason or invalid: + target = ( + self.grant_dead + if invalid or work.attempts >= max_attempts + else self.grant_waiting + ) + work = replace(work, reason=reason, nextAttemptAt=next_attempt_at) + txn.put(work.noticeId.encode(), target.serializer(work), db=target.sdb) + if target is self.grant_waiting: + txn.put( + due_key(work.nextAttemptAt, work.noticeId), + work.noticeId.encode(), + db=self.grant_due.sdb, + ) + txn.delete(b"receiver", db=self.grant_active.sdb) + + def retry_grant(self, notice_id): + """Resume a corrected Grant dead letter without requiring another IPEX delivery.""" + key = notice_id.encode() + with self.env.begin(write=True) as txn: + work = self.grant_dead.deserializer(txn.get(key, db=self.grant_dead.sdb)) + if work is None: + raise ValueError("unknown Grant dead letter") + work = replace(work, attempts=0, nextAttemptAt=0, reason="") + txn.put(key, self.grant_waiting.serializer(work), db=self.grant_waiting.sdb) + txn.put(due_key(0, work.noticeId), key, db=self.grant_due.sdb) + txn.delete(key, db=self.grant_dead.sdb) + + def retry_acceptance(self, said): + """Recheck a stopped acceptance after restoring its local evidence.""" key = said.encode() with self.env.begin(write=True) as txn: - raw = txn.get(key, db=self.pending.sdb) - if raw is None: - raise ValueError("pending work is absent") - work = self.pending.deserializer(raw) - if work.reason != reason: - work.reason = reason - txn.put(key, self.pending.serializer(work), db=self.pending.sdb) + result = self.acceptance_dead.deserializer( + txn.get(key, db=self.acceptance_dead.sdb) + ) + if result is None: + raise ValueError("unknown acceptance dead letter") + result = replace(result, reason="") + txn.put(key, self.accepting.serializer(result), db=self.accepting.sdb) + txn.delete(key, db=self.acceptance_dead.sdb) + + def next_verification(self, *, now, max_attempts=3): + """Durably begin one attempt, resuming interrupted work before new work. + + Due retries take precedence over new work. A time-ordered index + selects eligible waiting work without walking the waiting records. + Interrupted attempts count against the same finite budget after restart. + """ + with self.env.begin(write=True) as txn: + for table in (self.verifying, self.waiting, self.pending): + if table is self.waiting: + work = due_record(txn, self.verification_due, self.waiting, now) + if work is None: + continue + key = work.associationSaid.encode() + else: + with txn.cursor(db=table.sdb) as cursor: + if not cursor.first(): + continue + key, raw = cursor.item() + work = table.deserializer(raw) + txn.delete(key, db=table.sdb) + if work.attempts >= max_attempts: + work.reason = ( + work.reason + or "verification interrupted; attempt budget exhausted" + ) + txn.put( + key, + self.verification_dead.serializer(work), + db=self.verification_dead.sdb, + ) + return None + work.attempts += 1 + work.reason = "verification attempt started; result not committed" + txn.put(key, self.verifying.serializer(work), db=self.verifying.sdb) + return work + return None + + def defer_verification(self, work, *, reason, next_attempt_at, max_attempts=3): + """Move the active attempt to durable waiting or dead letter in one commit.""" + key = work.associationSaid.encode() + work = replace(work, reason=reason, nextAttemptAt=next_attempt_at) + target = ( + self.verification_dead if work.attempts >= max_attempts else self.waiting + ) + with self.env.begin(write=True) as txn: + if txn.get(key, db=self.verifying.sdb) is None: + raise ValueError("active verification is absent") + txn.put(key, target.serializer(work), db=target.sdb) + if target is self.waiting: + txn.put( + due_key(work.nextAttemptAt, work.associationSaid), + key, + db=self.verification_due.sdb, + ) + txn.delete(key, db=self.verifying.sdb) + + def verification_progress(self, said): + """Read one candidate's phase without discovering work from result history.""" + for phase, table in ( + ("pending", self.pending), + ("verifying", self.verifying), + ("waiting", self.waiting), + ("dead-letter", self.verification_dead), + ): + work = table.get(keys=(said,)) + if work is not None: + return phase, work + return None, None + + def retry_verification(self, said): + """Explicitly give a dead-letter candidate a new bounded attempt budget.""" + key = said.encode() + with self.env.begin(write=True) as txn: + work = self.verification_dead.deserializer( + txn.get(key, db=self.verification_dead.sdb) + ) + if work is None: + raise ValueError("unknown verification dead letter") + work = replace(work, attempts=0, nextAttemptAt=0, reason="") + txn.put(key, self.pending.serializer(work), db=self.pending.sdb) + txn.delete(key, db=self.verification_dead.sdb) def finish(self, result): - """Atomically insert a result and remove pending work; reject conflicting completion. + """Atomically complete active verification and enqueue successful acceptance. The workflow chooses the outcome. Identical repeat completion is harmless; - a missing pending record cannot be completed for the first time. Serialization - or storage failure aborts the whole transaction, leaving pending recoverable. + a missing active record cannot be completed for the first time. Serialization + or storage failure aborts the whole transaction, leaving active work recoverable. """ key = result.associationSaid.encode() with self.env.begin(write=True) as txn: @@ -118,16 +301,12 @@ def finish(self, result): if self.results.deserializer(existing) != result: raise ValueError("conflicting verification result") return - if txn.get(key, db=self.pending.sdb) is None: - raise ValueError("pending work is absent") + if txn.get(key, db=self.verifying.sdb) is None: + raise ValueError("active verification is absent") txn.put(key, self.results.serializer(result), db=self.results.sdb) if result.status == "verified": txn.put(key, self.accepting.serializer(result), db=self.accepting.sdb) - txn.delete(key, db=self.pending.sdb) - - def pending_batch(self, *, after="", limit=32): - """Copy a bounded page strictly after the SAID; close its cursor before returning.""" - return self._batch(self.pending, after=after, limit=limit) + txn.delete(key, db=self.verifying.sdb) def claim_nonce(self, peer, nonce, expires_at): """Insert a peer/nonce claim after authentication; return False on replay. @@ -138,13 +317,24 @@ def claim_nonce(self, peer, nonce, expires_at): """ return self.replay_claims.put(keys=(peer, nonce), val=ReplayClaim(expires_at)) - def acceptance_batch(self, *, after="", limit=1): - """Copy unfinished acceptance only; completed results never schedule work.""" - return self._batch(self.accepting, after=after, limit=limit) + def next_acceptance(self): + """Read one local acceptance obligation; its transaction consumes it on success.""" + return first_record(self.accepting) - def association_batch(self, *, after="", limit=32): - """Copy a bounded status page for local TEL revocation reconciliation.""" - return self._batch(self.associations, after=after, limit=limit) + def stop_acceptance(self, said, reason): + """Dead-letter missing or revoked evidence instead of repeatedly rediscovering it.""" + key = said.encode() + with self.env.begin(write=True) as txn: + result = self.accepting.deserializer(txn.get(key, db=self.accepting.sdb)) + if result is None: + raise ValueError("acceptance work is absent") + result = replace(result, reason=reason) + txn.put( + key, + self.acceptance_dead.serializer(result), + db=self.acceptance_dead.sdb, + ) + txn.delete(key, db=self.accepting.sdb) def next_delivery(self): """Claim one ready event, or resume the single interrupted delivery.""" @@ -187,17 +377,6 @@ def retry_delivery(self, event_id): ) txn.delete(key, db=self.delivery_dead.sdb) - def _batch(self, table, *, after, limit): - """Seek strictly after a key and release the LMDB cursor before returning.""" - with self.env.begin(db=table.sdb) as txn, txn.cursor() as cursor: - if not cursor.set_range(after.encode()): - return [] - if after and cursor.key() == after.encode() and not cursor.next(): - return [] - return [ - table.deserializer(raw) for _, raw in islice(cursor.iternext(), limit) - ] - def nonce_key(self, issuer, nonce): """Use Komer's ordinary issuer.nonce key; neither component contains dots.""" if not isinstance(issuer, str) or not issuer or "." in issuer: @@ -486,3 +665,29 @@ def _status_delivery(status, *, status_revision, destination, peer_aid): payload["reasonCode"] = status.reason body = json.dumps(payload, separators=(",", ":"), sort_keys=True) return Delivery(status.eventId, status.associationSaid, destination, peer_aid, body) + + +def first_record(table): + """Detach the head of a phase and close its reader before any caller can mutate.""" + with table.db.env.begin(db=table.sdb) as txn, txn.cursor() as cursor: + return table.deserializer(cursor.value()) if cursor.first() else None + + +def due_key(when, identifier): + """Sort an unfinished retry deadline by nonnegative UTC microseconds, then ID.""" + return f"{int(when * 1_000_000):016x}.{identifier}".encode() + + +def due_record(txn, schedule, waiting, now): + """Consume one eligible deadline index inside its phase-transition transaction.""" + with txn.cursor(db=schedule.sdb) as cursor: + if not cursor.first(): + return None + deadline, key = cursor.item() + work = waiting.deserializer(txn.get(key, db=waiting.sdb)) + if work is None: + raise ValueError("retry schedule has no waiting work") + if work.nextAttemptAt > now: + return None + txn.delete(deadline, db=schedule.sdb) + return work diff --git a/src/eoa_verifier/persistence/records.py b/src/eoa_verifier/persistence/records.py index 7b60eaa..e263624 100644 --- a/src/eoa_verifier/persistence/records.py +++ b/src/eoa_verifier/persistence/records.py @@ -5,11 +5,24 @@ @dataclass class PendingVerification: - """Unfinished initial verification; membership in pending is the only workflow state.""" + """One verification attempt; table membership identifies its durable phase.""" associationSaid: str grantSaid: str reason: str = "" + attempts: int = 0 + nextAttemptAt: float = 0.0 + + +@dataclass +class GrantWork: + """Authenticated notice retained until replay succeeds or an operator intervenes.""" + + noticeId: str + attrs: dict + attempts: int = 0 + nextAttemptAt: float = 0.0 + reason: str = "" @dataclass diff --git a/src/eoa_verifier/receiving/grants.py b/src/eoa_verifier/receiving/grants.py index 764decc..b6bc2ac 100644 --- a/src/eoa_verifier/receiving/grants.py +++ b/src/eoa_verifier/receiving/grants.py @@ -2,8 +2,7 @@ from __future__ import annotations -import traceback -from itertools import islice +import time from typing import Any from hio.base import doing @@ -29,7 +28,7 @@ class GrantNotificationDoer(doing.Doer): Accepted Grant signatures authenticate delivery; they do not establish KERIpy ACDC acceptance. Embedded evidence is replayed through the shared parser, which may escrow it. The coordinator separately checks credential acceptance. - Missing Grant material leaves its notice pending for a later HIO turn. + Missing Grant material moves to durable waiting with a finite retry budget. """ def __init__( @@ -39,6 +38,9 @@ def __init__( hby, notifier, parser, + clock=time.time, + retry_delay=5.0, + max_attempts=3, **kwa, ): """Borrow a work store, Habery, KERIpy Notifier and shared inbound parser. @@ -50,7 +52,11 @@ def __init__( self.hby = hby self.notifier = notifier self.parser = parser - self.scan_after = b"" # KERIpy notice key; scheduling hint only. + self.clock, self.retry_delay, self.max_attempts = ( + clock, + retry_delay, + max_attempts, + ) super().__init__(**kwa) def recur(self, tyme): @@ -61,53 +67,44 @@ def recur(self, tyme): return False def process_notes(self) -> None: - """Consume KERIpy notices with attrs.r routing and attrs.d naming the Grant EXN. + """Handoff and replay at most one notice; missing material cannot block fresh notices. - Remove unrelated, successfully processed and invalid notices through Noter so - indexes/signatures are cleaned together. Report invalid input with a traceback; - retain missing material and advance past it. Read at most 32 notices per turn. - Unexpected parser/storage errors propagate and leave - the failing notice intact. Return None; KERIpy notification storage is borrowed. - """ - - batch = self._notice_batch() - if not batch: - self.scan_after = b"" - for key, notice in batch: - self.scan_after = key - attrs = notice.attrs - if attrs.get("r") != "/exn/ipex/grant": - self.notifier.noter.rem(notice.rid) - continue - - try: - self.process_grant_notice(attrs) - except GrantNotReadyError: - continue - except InvalidGrantError: - traceback.print_exc() - self.notifier.noter.rem(notice.rid) - else: - self.notifier.noter.rem(notice.rid) - - def _notice_batch(self): - """Seek past the last KERIpy key and copy at most 32 notices before mutation. - - Use a key cursor, not offset pagination that rescans the retained backlog. - No read transaction survives processing; an empty page wraps next turn. + Active work is durable before the native notice is removed. Replay and + enqueue are idempotent if interruption occurs before acknowledgement. + Missing material waits on a persistent UTC deadline; three attempts exhaust + the budget. Invalid material goes directly to a diagnostic dead letter. """ noter = self.notifier.noter - with noter.env.begin(db=noter.notes.sdb) as txn: - with txn.cursor() as cursor: - if not cursor.set_range(self.scan_after): - return [] - if self.scan_after and cursor.key() == self.scan_after: - if not cursor.next(): - return [] - return [ - (bytes(key), noter.notes.klas(raw=bytes(raw))) - for key, raw in islice(cursor.iternext(), 32) - ] + with noter.env.begin(db=noter.notes.sdb) as txn, txn.cursor() as cursor: + notice = ( + noter.notes.klas(raw=bytes(cursor.value())) if cursor.first() else None + ) + work = self.baser.begin_grant( + notice, now=self.clock(), max_attempts=self.max_attempts + ) + if work is None: + # Recover interruption before acknowledging a notice whose final + # replay attempt was already charged and subsequently dead-lettered. + if notice is not None and self.baser.grant_dead.get(keys=(notice.rid,)): + noter.rem(notice.rid) + return + noter.rem(work.noticeId) + try: + if work.attrs.get("r") == "/exn/ipex/grant": + self.process_grant_notice(work.attrs) + except GrantNotReadyError as exc: + self.baser.settle_grant( + work, + reason=str(exc) or type(exc).__name__, + next_attempt_at=self.clock() + self.retry_delay, + max_attempts=self.max_attempts, + ) + except InvalidGrantError as exc: + self.baser.settle_grant( + work, reason=str(exc) or type(exc).__name__, invalid=True + ) + else: + self.baser.settle_grant(work) def _replay_embed(self, ims): """Advance KERIpy parsing once for a complete, fixed embed frame. diff --git a/src/eoa_verifier/runtime/cli.py b/src/eoa_verifier/runtime/cli.py index c451017..2beb5eb 100644 --- a/src/eoa_verifier/runtime/cli.py +++ b/src/eoa_verifier/runtime/cli.py @@ -104,15 +104,19 @@ def main(argv=None): help="Retry lower-bound cap in seconds; upper is twice this (default: 150)", ) start.add_argument("--webhook-max-attempts", type=int, default=3) - retry = commands.add_parser( - "retry-delivery", help="Resume a corrected dead letter with service stopped" - ) - retry.add_argument("event_id") - retry.add_argument("--name", default="eoa-verifier") - retry.add_argument("--base", default="") - retry.add_argument("--head-dir") + for phase in ("delivery", "verification", "grant", "acceptance"): + retry = commands.add_parser( + f"retry-{phase}", + help=f"Resume a corrected {phase} dead letter with service stopped", + ) + retry.add_argument( + "identifier", help="Event ID, association SAID, or Grant notice ID" + ) + retry.add_argument("--name", default="eoa-verifier") + retry.add_argument("--base", default="") + retry.add_argument("--head-dir") args = vars(parser.parse_args(argv)) - if args["command"] == "retry-delivery": + if args["command"].startswith("retry-"): from keri.db import dbing from eoa_verifier.persistence.basing import VerifierBaser @@ -125,7 +129,13 @@ def main(argv=None): headDirPath=args["head_dir"], temp=False, ) as baser: - baser.retry_delivery(args["event_id"]) + actions = { + "retry-delivery": baser.retry_delivery, + "retry-verification": baser.retry_verification, + "retry-grant": baser.retry_grant, + "retry-acceptance": baser.retry_acceptance, + } + actions[args["command"]](args["identifier"]) except (ValueError, OSError) as exc: print(f"eoa-verifier: {exc}", file=sys.stderr) return 1 diff --git a/src/eoa_verifier/verification/coordinating.py b/src/eoa_verifier/verification/coordinating.py index db94d37..1ad9ec5 100644 --- a/src/eoa_verifier/verification/coordinating.py +++ b/src/eoa_verifier/verification/coordinating.py @@ -1,12 +1,11 @@ -"""Coordinate durable verification work and revalidate asynchronous results.""" +"""Advance one durable verification attempt through local proof and EOA checks.""" -from __future__ import annotations +import time from hio.base import doing from keri import kering -from eoa_verifier.persistence.basing import VerifierBaser -from eoa_verifier.persistence.records import PendingVerification, VerificationResult +from eoa_verifier.persistence.records import VerificationResult from eoa_verifier.verification.credentials import grant_candidate, verify_association from eoa_verifier.verification.errors import ( MissingCredentialArtifactsError, @@ -15,160 +14,118 @@ class VerificationCoordinator(doing.DoDoer): - """Own initial-verification scheduling, the EOA worker, and durable work updates. + """Own one asynchronous EOA check; the database owns progress and retry timing. - KERIpy credential checks precede dispatch and run once more after the initial - RPC wait to catch evidence received during that wait. These are local KERIpy - state reads, not periodic verification or network refresh. One association is - in flight; missing material and RPC failures leave unfinished work retryable. - A verified result is initial progress, not application acceptance. + Local evidence is checked before RPC and again after its response. Completed + results never schedule work. Missing evidence and transient RPC failures move + to waiting, then to dead letter when the finite attempt budget is exhausted. """ def __init__( self, *, - baser: VerifierBaser, + baser, rgy, - trusted_geda_aid: str, - association_schema: str, + trusted_geda_aid, + association_schema, eoa_verifier, - retry_delay: float = 5.0, + retry_delay=5.0, + max_attempts=3, + clock=time.time, **kwa, ): - """Borrow the work store and KERIpy Regery; own the supplied EOA child Doer. - - trusted_geda_aid and association_schema define the trust/profile policy. - eoa_verifier is required and exposes msgs/cues decks. retry_delay is HIO-clock - seconds between failed initial attempts. retry_at maps SAIDs to eligible times; - inflight is the dispatched SAID or None; scan_after is the last examined key. - These hints are in memory only: restart rediscovers durable unfinished work - and may retry sooner. kwa supplies HIO DoDoer scheduling options. - """ - self.baser = baser - self.rgy = rgy - self.trusted_geda_aid = trusted_geda_aid - self.association_schema = association_schema + """Borrow stores; own the EOA Doer. clock returns UTC Unix seconds.""" + self.baser, self.rgy = baser, rgy + self.trusted_geda_aid, self.association_schema = ( + trusted_geda_aid, + association_schema, + ) self.eoa_verifier = eoa_verifier - self.retry_delay = retry_delay - # These are scheduling hints only; operation state remains in VerifierBaser. - # Restart may retry sooner, but cannot lose or falsely complete the work. - self.retry_at = {} + self.retry_delay, self.max_attempts, self.clock = ( + retry_delay, + max_attempts, + clock, + ) + # Only dispatch correlation is transient. A new worker resumes durable active work. self.inflight = None - self.scan_after = "" super().__init__(doers=[eoa_verifier, doing.doify(self.verify_do)], **kwa) def verify_do(self, tymth, tock=0.0, **opts): - """Apply worker results and examine a bounded work page, then yield self.tock. - - HIO supplies the shared clock. This generator runs until unscheduled and has - no completion value; the parent owns the worker's shutdown. - """ + """Apply one response or begin one attempt per scheduler turn.""" yield tock while True: - self.process_results() - self.process_ready() + if not self.process_results(): + self.process_ready() yield self.tock - def process_results(self) -> None: - """Consume cues matching pending work and persist their status; return None. - - Ignore unmatched cues or work no longer pending. RPC failures set a retry - hint; local invalidity fails the row. Success rechecks locally accepted KERIpy - state before completing the row. Store successful account observations with the - result. Unexpected storage or programming errors propagate. - """ - while self.eoa_verifier.cues: - cue = self.eoa_verifier.cues.popleft() - said = cue["said"] - if said != self.inflight: - continue - self.inflight = None - op = self.baser.pending.get(keys=(said,)) - if op is None: - continue - if cue["kin"] == "retry": - self._retry(op, cue["error"]) - elif cue["kin"] == "failed": - self._finish(op, "rejected", reason=cue["error"]) - elif cue["kin"] == "verified": - try: - # A revocation can arrive while the RPC client is waiting. - verify_association( - rgy=self.rgy, - said=said, - schema_said=self.association_schema, - trusted_geda_aid=self.trusted_geda_aid, - ) - except MissingCredentialArtifactsError as exc: - self._retry(op, str(exc)) - except (VerificationError, kering.ValidationError) as exc: - self._finish(op, "rejected", reason=str(exc)) - else: - self._finish(op, "verified", eoaResult=cue["eoaResult"]) - - def process_ready(self) -> None: - """Skip scanning while busy; otherwise inspect at most one 32-record page. - - Advance past cooling-down rows and attempt at most one association. - An empty page resets the scan for a later turn. No database cursor survives - this method; mutations and network waits occur outside its read transaction. - """ + def process_results(self): + """Correlate one EOA cue and commit its next durable phase.""" + if not self.eoa_verifier.cues: + return + cue = self.eoa_verifier.cues.popleft() + if cue["said"] != self.inflight: + return + op = self.baser.verifying.get(keys=(self.inflight,)) + if op is None: + raise ValueError("dispatched verification has no active work") + if cue["kin"] == "retry": + self._retry(op, cue["error"]) + elif cue["kin"] == "failed": + self._finish(op, "rejected", reason=cue["error"]) + elif cue["kin"] == "verified": + try: + self._verify(op) + except MissingCredentialArtifactsError as exc: + self._retry(op, str(exc)) + except (VerificationError, kering.ValidationError) as exc: + self._finish(op, "rejected", reason=str(exc)) + else: + self._finish(op, "verified", eoaResult=cue["eoaResult"]) + else: + raise ValueError("unknown EOA result") + self.inflight = None + return True + def process_ready(self): + """Claim one attempt before local validation or external RPC dispatch.""" if self.inflight is not None: return - batch = self.baser.pending_batch(after=self.scan_after) - if not batch: - self.scan_after = "" + op = self.baser.next_verification( + now=self.clock(), max_attempts=self.max_attempts + ) + if op is None: return - for op in batch: - self.scan_after = op.associationSaid - if self.retry_at.get(op.associationSaid, 0) > self.tyme: - continue - self.verify_operation(op) - break # At most one KERIpy verification attempt per scheduler turn. - - def verify_operation(self, op: PendingVerification) -> None: - """Check one pending row’s KERI evidence and dispatch it or record a decision. - - Missing artifacts retain pending work and a retry hint; invalid evidence - produces a rejected result. Success queues the ACDC dictionary - and tracks it as in flight. Candidate Grant bytes may justify rejection but never - substitute for KERIpy credential acceptance. Persistence/programming errors propagate. - """ - try: - # KERIpy may discard an invalid child before logging its bytes. - # The accepted Grant already owns the immutable candidate; use - # it for rejection, never as a substitute for KERI acceptance. - candidate = grant_candidate(self.rgy, op.grantSaid) - association = verify_association( - rgy=self.rgy, - said=op.associationSaid, - schema_said=self.association_schema, - candidate=candidate, - trusted_geda_aid=self.trusted_geda_aid, - ) + association = self._verify(op) except MissingCredentialArtifactsError as exc: self._retry(op, str(exc)) - return except (VerificationError, kering.ValidationError) as exc: self._finish(op, "rejected", reason=str(exc)) - return - - # The database remains the work list. The queue contains only the - # current dispatch, so restart recovers work without queue persistence. - self.retry_at.pop(op.associationSaid, None) - self.inflight = op.associationSaid - self.eoa_verifier.msgs.append(association.sad) + else: + self.inflight = op.associationSaid + self.eoa_verifier.msgs.append(association.sad) + + def _verify(self, op): + """Require native acceptance; Grant bytes can justify rejection, never acceptance.""" + return verify_association( + rgy=self.rgy, + said=op.associationSaid, + schema_said=self.association_schema, + candidate=grant_candidate(self.rgy, op.grantSaid), + trusted_geda_aid=self.trusted_geda_aid, + ) def _retry(self, op, reason): - """Keep unfinished work durable and pace another attempt on the HIO clock.""" - self.baser.note_pending(op.associationSaid, reason) - self.retry_at[op.associationSaid] = self.tyme + self.retry_delay + """Persist both cooldown and budget; restarting never renews either.""" + self.baser.defer_verification( + op, + reason=reason, + next_attempt_at=self.clock() + self.retry_delay, + max_attempts=self.max_attempts, + ) def _finish(self, op, status, *, reason="", eoaResult=None): - """Persist the workflow decision and release its transient retry hint.""" + """Commit the result and, for success, its separate acceptance obligation.""" self.baser.finish( VerificationResult(op.associationSaid, status, reason, eoaResult or {}) ) - self.retry_at.pop(op.associationSaid, None) diff --git a/tests/associations/test_statusing.py b/tests/associations/test_statusing.py index 669bf0d..119f969 100644 --- a/tests/associations/test_statusing.py +++ b/tests/associations/test_statusing.py @@ -18,9 +18,10 @@ def test_public_get_returns_stored_status_and_old_observation(verified_store): app = falcon.App() app.add_route("/v1/associations/{said}/status", StatusEnd(baser)) client = TestClient(app) - baser.enqueue(PendingVerification("pending", "grant", "missing source")) baser.enqueue(PendingVerification("rejected", "grant")) + baser.next_verification(now=0) baser.finish(VerificationResult("rejected", "rejected", "wrong schema")) + baser.enqueue(PendingVerification("pending", "grant", "missing source")) for said, status in ( ("pending", "pending"), ("rejected", "rejected"), @@ -53,6 +54,7 @@ def test_public_status_does_not_disclose_other_delivery_activity(verified_store) # A different association's event shares this destination. result = baser.results.get(keys=("association",)) baser.enqueue(PendingVerification("other", "grant")) + baser.next_verification(now=0) baser.finish(VerificationResult("other", "verified", eoaResult=result.eoaResult)) other = baser.accept( "other", @@ -69,3 +71,31 @@ def test_public_status_does_not_disclose_other_delivery_activity(verified_store) assert "nextAttemptAt" not in before["delivery"] # Operators still have the complete durable schedule through local storage. assert baser.destinations.get(keys=(event.destination,)) == schedule + + +def test_waiting_and_dead_letter_are_passive_statuses(verified_store): + """Public reads expose operational failures without asserting an invalid credential.""" + import falcon.testing + from eoa_verifier.associations.statusing import StatusEnd + + baser = verified_store + app = falcon.App() + app.add_route("/v1/associations/{said}/status", StatusEnd(baser)) + client = falcon.testing.TestClient(app) + baser.enqueue(PendingVerification("waiting", "grant")) + work = baser.next_verification(now=100) + baser.defer_verification(work, reason="missing evidence", next_attempt_at=105) + status = client.simulate_get("/v1/associations/waiting/status").json + assert status["status"] == "waiting" and status["nextAttemptAt"] == 105 + work = baser.next_verification(now=105) + baser.defer_verification( + work, reason="missing evidence", next_attempt_at=110, max_attempts=2 + ) + assert ( + client.simulate_get("/v1/associations/waiting/status").json["status"] + == "dead-letter" + ) + baser.stop_acceptance("association", "revoked before acceptance") + stopped = client.simulate_get("/v1/associations/association/status").json + assert stopped["phase"] == "acceptance" and stopped["status"] == "dead-letter" + assert baser.accepted_nonces.cntAll() == 0 diff --git a/tests/conftest.py b/tests/conftest.py index aaa4c5d..e0cd221 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -28,6 +28,7 @@ def verified_store(tmp_path): cls=VerifierBaser, name="acceptance", headDirPath=str(tmp_path), temp=False ) as baser: baser.enqueue(PendingVerification("association", "grant")) + baser.next_verification(now=0) baser.finish( VerificationResult( "association", diff --git a/tests/delivery/test_delivering.py b/tests/delivery/test_delivering.py index c159f41..8516e8e 100644 --- a/tests/delivery/test_delivering.py +++ b/tests/delivery/test_delivering.py @@ -133,6 +133,7 @@ def on_post(self, req, rep): server = http.Server(host="127.0.0.1", port=port, app=app) server_doer = http.ServerDoer(server=server) baser.enqueue(PendingVerification("association", "grant")) + baser.next_verification(now=0) baser.finish( VerificationResult( "association", @@ -247,6 +248,7 @@ def recur(self, tyme): server = tcp.Server(host="127.0.0.1", port=free_port()) peer = BadResponsePeer(server=server) baser.enqueue(PendingVerification("association", "grant")) + baser.next_verification(now=0) baser.finish( VerificationResult( "association", @@ -296,6 +298,7 @@ def watch(tymth, tock=0.0, **kwa): def accept(baser, said): """Create a completed result and its event at one shared destination.""" baser.enqueue(PendingVerification(said, "grant")) + baser.next_verification(now=0) baser.finish( VerificationResult( said, "verified", eoaResult={"wallet": "wallet", "accountObservation": {}} diff --git a/tests/integration/test_ipex_verification.py b/tests/integration/test_ipex_verification.py index 5e4090e..0561ca6 100644 --- a/tests/integration/test_ipex_verification.py +++ b/tests/integration/test_ipex_verification.py @@ -151,12 +151,11 @@ def deliver(stream, said, expected): yield from send(stream) deadline = workflow.tyme + 10 while True: - store = ( - runtime.baser.pending + work = ( + runtime.baser.verification_progress(said)[1] if expected == "pending" - else runtime.baser.results + else runtime.baser.results.get(keys=(said,)) ) - work = store.get(keys=(said,)) if work is not None and ( expected == "pending" or work.status == expected ): @@ -287,7 +286,7 @@ def run(tymth, tock=0.0, **kwa): client_doer = http.ClientDoer(client=client) workflow.extend([runtime, client_doer]) assert runtime.hab.pre == aid - assert runtime.baser.pending.get(keys=(creder.said,)) is not None + assert runtime.baser.verification_progress(creder.said)[1] is not None # Supporting evidence alone resumes persisted work; no new Grant required. yield from deliver( streams["geda"] + streams["qvi"], creder.said, "verified" diff --git a/tests/persistence/test_accepted_nonces.py b/tests/persistence/test_accepted_nonces.py index 20392a7..93e77f5 100644 --- a/tests/persistence/test_accepted_nonces.py +++ b/tests/persistence/test_accepted_nonces.py @@ -39,6 +39,7 @@ def verify(baser, said): """Seed only initial verification for storage-boundary tests, not intake qualification.""" baser.enqueue(PendingVerification(said, "grant")) + baser.next_verification(now=0) baser.finish( VerificationResult( said, "verified", eoaResult={"wallet": "wallet", "accountObservation": {}} @@ -305,6 +306,7 @@ def test_invalid_nonce_is_rejected_without_consumption(nonce): credential = candidate() with dbing.openLMDB(cls=VerifierBaser) as baser: baser.enqueue(PendingVerification("candidate", "grant")) + baser.next_verification(now=0) baser.finish( VerificationResult( "candidate", diff --git a/tests/persistence/test_basing.py b/tests/persistence/test_basing.py index 4303567..617d6a6 100644 --- a/tests/persistence/test_basing.py +++ b/tests/persistence/test_basing.py @@ -22,7 +22,8 @@ def test_duplicates_completion_and_restart(tmp_path): try: work = PendingVerification("a", "first") assert baser.enqueue(work) - baser.note_pending("a", "missing source") + work = baser.next_verification(now=0) + baser.defer_verification(work, reason="missing source", next_attempt_at=5) assert not baser.enqueue(PendingVerification("a", "duplicate")) baser.enqueue(PendingVerification("b", "first")) result = VerificationResult( @@ -30,6 +31,7 @@ def test_duplicates_completion_and_restart(tmp_path): "verified", eoaResult={"wallet": "wallet", "accountObservation": {"chainId": 31337}}, ) + baser.next_verification(now=0) baser.finish(result) baser.finish(result) with pytest.raises(ValueError, match="conflicting"): @@ -37,12 +39,12 @@ def test_duplicates_completion_and_restart(tmp_path): assert not baser.enqueue(PendingVerification("b", "duplicate")) baser.close() baser.reopen() - assert baser.pending.get(keys=("a",)) == PendingVerification( - "a", "first", "missing source" + assert baser.waiting.get(keys=("a",)) == PendingVerification( + "a", "first", "missing source", 1, 5 ) assert baser.pending.get(keys=("b",)) is None assert baser.results.get(keys=("b",)) == result - assert baser.acceptance_batch() == [result] + assert baser.next_acceptance() == result finally: baser.close() @@ -52,6 +54,7 @@ def test_completion_rollback_after_result_write(): with dbing.openLMDB(cls=VerifierBaser) as baser: work = PendingVerification("a", "first") baser.enqueue(work) + work = baser.next_verification(now=0) real_env = baser.env class FailingTransaction: @@ -85,7 +88,7 @@ def begin(self, **kwa): pytest.raises(RuntimeError, match="between writes"), ): baser.finish(VerificationResult("a", "verified")) - assert baser.pending.get(keys=("a",)) == work + assert baser.verifying.get(keys=("a",)) == work assert baser.results.get(keys=("a",)) is None assert baser.accepting.cntAll() == 0 baser.finish(VerificationResult("a", "rejected", "invalid proof")) @@ -99,7 +102,7 @@ def test_acceptance_and_delivery_progress_survive_reopen(verified_store): baser.close() baser.reopen() accepted = accept_verified_result(baser) - assert baser.acceptance_batch() == [] + assert baser.next_acceptance() is None assert baser.delivery_ready.get(keys=(accepted.eventId,)) is not None baser.record_attempt(accepted.eventId) baser.delivery_result(accepted.eventId, error="connection failed") @@ -149,6 +152,7 @@ def test_rejected_result_cannot_create_acceptance_or_event(verified_store): """Rejected verification remains inspectable and never produces a success event.""" baser = verified_store baser.enqueue(PendingVerification("rejected", "grant")) + baser.next_verification(now=0) baser.finish(VerificationResult("rejected", "rejected", "wrong schema")) with pytest.raises(ValueError, match="verified result"): baser.accept( diff --git a/tests/receiving/test_grants.py b/tests/receiving/test_grants.py index aa901ba..3ad2e09 100644 --- a/tests/receiving/test_grants.py +++ b/tests/receiving/test_grants.py @@ -44,7 +44,7 @@ def test_consumed_notification_removes_note_and_signal(config, kind): @pytest.mark.parametrize("boundary", ["parser", "storage"]) -def test_internal_failure_preserves_notification(config, boundary): +def test_internal_failure_preserves_active_handoff(config, boundary): """Inject parser/storage errors after valid decoding and prove the KERIpy notice remains retryable.""" lifetime = ExitStack() runtime = lifetime.enter_context(entered_service(config)) @@ -71,13 +71,13 @@ def test_internal_failure_preserves_notification(config, boundary): pytest.raises(ValueError, match="internal failure"), ): grants.process_notes() - assert grants.notifier.noter.get(notice.rid)[0].raw == notice.raw + assert runtime.baser.grant_active.get(keys=("receiver",)).noticeId == notice.rid assert runtime.baser.pending.get(keys=(association["d"],)) is None finally: lifetime.close() -def test_missing_grant_retains_notification_until_available(config): +def test_missing_grant_waits_durably_without_blocking_native_notices(config): """An absent EXN leaves its persisted notification available for a later attempt.""" lifetime = ExitStack() runtime = lifetime.enter_context(entered_service(config)) @@ -86,7 +86,8 @@ def test_missing_grant_retains_notification_until_available(config): grants.notifier.add({"r": "/exn/ipex/grant", "d": "missing"}) notice, _ = grants.notifier.noter.getNotes()[0] grants.process_notes() - assert grants.notifier.noter.get(notice.rid)[0].raw == notice.raw + assert runtime.baser.grant_waiting.get(keys=(notice.rid,)).attempts == 1 + assert grants.notifier.noter.getNoteCnt() == 0 finally: lifetime.close() @@ -135,17 +136,15 @@ def recur(self, tyme): lifetime.close() -def test_notice_pages_advance_past_retained_work(config): - """Real KERIpy storage retains early notices without starving later work or siblings.""" +def test_one_notice_per_turn_and_bounded_missing_material(config): + """A missing Grant leaves the native queue; later notices and HIO siblings progress.""" from hio.base import doing - lifetime = ExitStack() - runtime = lifetime.enter_context(entered_service(config)) - try: + with entered_service(config) as runtime: grants = next(d for d in runtime.doers if isinstance(d, GrantNotificationDoer)) - for i in range(65): - grants.notifier.add({"r": "/exn/ipex/grant", "d": f"missing-{i}"}) - grants.notifier.add({"r": "/unrelated", "d": "last"}) + grants.clock = lambda: 100 + grants.notifier.add({"r": "/exn/ipex/grant", "d": "missing"}) + grants.notifier.add({"r": "/unrelated", "d": "later"}) counts = [] class Heartbeat(doing.Doer): @@ -153,12 +152,38 @@ def recur(self, tyme): counts.append(grants.notifier.noter.getNoteCnt()) return len(counts) == 3 - with patch.object( - grants, "process_grant_notice", wraps=grants.process_grant_notice - ) as process: - doing.Doist(tock=0.01, limit=0.03).do(doers=[grants, Heartbeat()]) - assert process.call_count <= 3 * 32 - assert counts[-1] < counts[0] - assert grants.notifier.noter.getNoteCnt() == 65 - finally: - lifetime.close() + doing.Doist(tock=0.01, limit=0.03).do(doers=[grants, Heartbeat()]) + assert counts[:2] == [1, 0] + assert runtime.baser.grant_waiting.cntAll() == 1 + for now in (105, 110): + grants.clock = lambda now=now: now + grants.process_notes() + assert runtime.baser.grant_waiting.cntAll() == 0 + assert runtime.baser.grant_dead.cntAll() == 1 + key, work = next(runtime.baser.grant_dead.getItemIter()) + assert work.attempts == 3 and "missing" in work.reason + runtime.baser.retry_grant(work.noticeId) + assert runtime.baser.grant_dead.cntAll() == 0 + assert runtime.baser.grant_waiting.get(keys=key).attempts == 0 + + +def test_interrupted_handoff_reopens_without_native_notice(config): + """A removed native notice is recoverable entirely from the application's active phase.""" + with entered_service(config) as runtime: + grants = next(d for d in runtime.doers if isinstance(d, GrantNotificationDoer)) + grants.notifier.add({"r": "/exn/ipex/grant", "d": "missing"}) + with ( + patch.object( + grants, "process_grant_notice", side_effect=RuntimeError("interrupted") + ), + pytest.raises(RuntimeError), + ): + grants.process_notes() + assert grants.notifier.noter.getNoteCnt() == 0 + work = runtime.baser.grant_active.get(keys=("receiver",)) + assert work.attempts == 1 + with entered_service(config) as runtime: + grants = next(d for d in runtime.doers if isinstance(d, GrantNotificationDoer)) + grants.process_notes() + assert runtime.baser.grant_active.cntAll() == 0 + assert runtime.baser.grant_waiting.get(keys=(work.noticeId,)).attempts == 2 diff --git a/tests/runtime/test_cli.py b/tests/runtime/test_cli.py index ab5be91..b2e1e22 100644 --- a/tests/runtime/test_cli.py +++ b/tests/runtime/test_cli.py @@ -16,3 +16,34 @@ def test_cli_documents_network_options_and_rejects_missing_config(capsys): with pytest.raises(SystemExit) as missing: main(["server", "start"]) assert missing.value.code == 2 + + +def test_retry_verification_command_uses_persistent_phase(tmp_path): + """The operator command renews only an exhausted candidate's retry budget.""" + from keri.db import dbing + from eoa_verifier.persistence.basing import VerifierBaser + from eoa_verifier.persistence.records import PendingVerification + + with dbing.openLMDB( + cls=VerifierBaser, name="operator", headDirPath=str(tmp_path), temp=False + ) as baser: + baser.enqueue(PendingVerification("candidate", "grant")) + work = baser.next_verification(now=0) + baser.defer_verification( + work, reason="RPC unavailable", next_attempt_at=5, max_attempts=1 + ) + arguments = [ + "retry-verification", + "candidate", + "--name", + "operator", + "--head-dir", + str(tmp_path), + ] + assert main(arguments) == 0 + with dbing.openLMDB( + cls=VerifierBaser, name="operator", headDirPath=str(tmp_path), temp=False + ) as baser: + assert baser.verification_dead.cntAll() == 0 + assert baser.pending.get(keys=("candidate",)).attempts == 0 + assert main(arguments) == 1 # Already resumed; no second budget reset. diff --git a/tests/verification/test_coordinating.py b/tests/verification/test_coordinating.py index a179513..45b28ba 100644 --- a/tests/verification/test_coordinating.py +++ b/tests/verification/test_coordinating.py @@ -16,27 +16,39 @@ from tests.support.services import entered_service -def test_pending_scan_excludes_results_and_bounds_pages(): - """Completed history never participates in pending scans; pages see intervening writes.""" - with dbing.openLMDB(cls=VerifierBaser) as baser: - for i in range(65): - baser.enqueue(PendingVerification(f"done-{i}", "first")) - baser.finish(VerificationResult(f"done-{i}", "verified")) - baser.enqueue(PendingVerification(f"{i:03}", "first")) - page = baser.pending_batch(limit=32) - assert len(page) == 32 - baser.enqueue(PendingVerification("065", "first")) - page = baser.pending_batch(after=page[-1].associationSaid, limit=32) - assert len(page) == 32 and page[-1].associationSaid == "063" - assert [w.associationSaid for w in baser.pending_batch(after="063")] == [ - "064", - "065", - ] - assert baser.pending_batch(after="065") == [] - - -def test_busy_worker_skips_scan_and_missing_artifacts_wait_fairly(): - """Use a controlled HIO clock and simulated missing evidence to check busy, fairness and cooldown rules.""" +def test_active_waiting_budget_and_manual_retry_survive_restart(tmp_path): + """Restart neither loses a dispatch nor resets its cooldown/attempt budget.""" + with dbing.openLMDB( + cls=VerifierBaser, name="phases", headDirPath=str(tmp_path), temp=False + ) as baser: + baser.enqueue(PendingVerification("a", "first")) + work = baser.next_verification(now=100) + assert work.attempts == 1 and baser.pending.cntAll() == 0 + baser.close() + baser.reopen() + work = baser.next_verification(now=100) + assert work.attempts == 2 # Interrupted dispatch consumes an attempt. + baser.defer_verification(work, reason="RPC unavailable", next_attempt_at=105) + assert not baser.enqueue(PendingVerification("a", "duplicate")) + baser.close() + baser.reopen() + assert baser.next_verification(now=104) is None + work = baser.next_verification(now=105) + assert work.attempts == 3 and work.grantSaid == "first" + baser.defer_verification(work, reason="RPC unavailable", next_attempt_at=110) + assert baser.verification_progress("a")[0] == "dead-letter" + assert baser.next_verification(now=1000) is None + assert not baser.enqueue(PendingVerification("a", "duplicate")) + baser.retry_verification("a") + work = baser.next_verification(now=1000) + assert work.attempts == 1 + baser.finish(VerificationResult("a", "rejected", "bad proof")) + assert baser.next_verification(now=1001) is None + assert not baser.enqueue(PendingVerification("a", "duplicate")) + + +def test_busy_worker_and_waiting_do_not_schedule_other_active_work(): + """A single in-flight check and persistent waiting allow fresh evidence its turn.""" with dbing.openLMDB(cls=VerifierBaser) as baser: for said in ("a", "b"): baser.enqueue(PendingVerification(said, "")) @@ -48,13 +60,12 @@ def test_busy_worker_skips_scan_and_missing_artifacts_wait_fairly(): trusted_geda_aid="", association_schema=ASSOCIATION_SCHEMA, eoa_verifier=worker, + clock=lambda: clock.tyme, ) - coordinator.wind(clock.tymen()) coordinator.inflight = "busy" - with patch.object(baser, "pending_batch", side_effect=AssertionError): + with patch.object(baser, "next_verification", side_effect=AssertionError): coordinator.process_ready() coordinator.inflight = None - # Simulate missing KERI evidence only; use actual work storage and clock. with ( patch("eoa_verifier.verification.coordinating.grant_candidate"), patch( @@ -65,7 +76,7 @@ def test_busy_worker_skips_scan_and_missing_artifacts_wait_fairly(): coordinator.process_ready() assert verify.call_count == 1 coordinator.process_ready() - assert verify.call_count == 2 # b gets a turn despite a still waiting. + assert verify.call_count == 2 for _ in range(5): coordinator.process_ready() assert verify.call_count == 2 @@ -74,13 +85,14 @@ def test_busy_worker_skips_scan_and_missing_artifacts_wait_fairly(): assert verify.call_count == 3 coordinator.process_ready() assert verify.call_count == 4 - assert baser.pending.get(keys=("a",)).reason == "missing" + assert baser.waiting.get(keys=("a",)).reason == "missing" def test_rpc_retry_and_success_move_only_on_completion(): - """A temporary RPC failure remains pending; a successful cue persists its observation.""" + """Cues move active work to waiting or acceptance; completed history is inert.""" with dbing.openLMDB(cls=VerifierBaser) as baser: baser.enqueue(PendingVerification("a", "first")) + baser.next_verification(now=0) worker = EoaVerifierDoer(rpc_url="http://unused", chain_id=31337) coordinator = VerificationCoordinator( baser=baser, @@ -88,20 +100,25 @@ def test_rpc_retry_and_success_move_only_on_completion(): trusted_geda_aid="", association_schema=ASSOCIATION_SCHEMA, eoa_verifier=worker, + clock=lambda: 0, ) - coordinator.wind(tyming.Tymist().tymen()) coordinator.inflight = "a" worker.cues.append({"kin": "retry", "said": "a", "error": "RPC unavailable"}) coordinator.process_results() - assert baser.pending.get(keys=("a",)).reason == "RPC unavailable" - assert baser.results.get(keys=("a",)) is None + assert baser.waiting.get(keys=("a",)).reason == "RPC unavailable" + assert baser.verifying.cntAll() == 0 and baser.results.cntAll() == 0 + baser.next_verification(now=5) coordinator.inflight = "a" observation = {"wallet": "wallet", "accountObservation": {"chainId": 31337}} worker.cues.append({"kin": "verified", "said": "a", "eoaResult": observation}) - with patch("eoa_verifier.verification.coordinating.verify_association"): + with ( + patch("eoa_verifier.verification.coordinating.grant_candidate"), + patch("eoa_verifier.verification.coordinating.verify_association"), + ): coordinator.process_results() - assert baser.pending.get(keys=("a",)) is None + assert baser.verification_progress("a") == (None, None) assert baser.results.get(keys=("a",)).eoaResult == observation + assert baser.next_acceptance().associationSaid == "a" def test_wrong_schema_is_coordinator_rejection_without_keripy_acceptance(config): @@ -142,3 +159,15 @@ def test_wrong_schema_is_coordinator_rejection_without_keripy_acceptance(config) grants.process_grant_notice(attrs) assert runtime.baser.results.get(keys=(creder.said,)) == result assert runtime.baser.pending.get(keys=(creder.said,)) is None + + +def test_completion_requires_an_active_attempt(): + """Ready work cannot skip its durable claim, including through direct callers.""" + import pytest + + with dbing.openLMDB(cls=VerifierBaser) as baser: + baser.enqueue(PendingVerification("a", "grant")) + with pytest.raises(ValueError, match="active verification"): + baser.finish(VerificationResult("a", "verified")) + assert baser.pending.get(keys=("a",)) is not None + assert baser.results.cntAll() == 0 From acea6613f6add016fa129221910b579d745d3e78 Mon Sep 17 00:00:00 2001 From: Kent Bull Date: Sat, 31 Oct 2026 21:33:14 -0600 Subject: [PATCH 4/4] Keep IPEX retry and assertion clocks on the same timeline The real HIO scheduler can catch up after slow store work, advancing a test deadline before the production UTC retry is due. Drive injected worker clocks from one epoch plus the shared HIO time across every service reopen. Keep the ten-second assertions and three-attempt budget unchanged and include durable phase diagnostics on failure. The previously failing local-only POST scenario passes against the installed wheel. This changes test scheduling only; application code is identical to the head that passed all 243 installed-wheel tests in CI. --- tests/integration/test_ipex_verification.py | 33 +++++++++++++++++---- 1 file changed, 27 insertions(+), 6 deletions(-) diff --git a/tests/integration/test_ipex_verification.py b/tests/integration/test_ipex_verification.py index 0561ca6..5654d8f 100644 --- a/tests/integration/test_ipex_verification.py +++ b/tests/integration/test_ipex_verification.py @@ -2,6 +2,7 @@ import shutil import subprocess +import time from contextlib import ExitStack from importlib.resources import files from uuid import uuid4 @@ -17,8 +18,10 @@ from keri.help import helping from eoa_verifier.associations.retiring import RetirementDoer +from eoa_verifier.receiving.grants import GrantNotificationDoer from eoa_verifier.runtime.config import ServiceConfig from eoa_verifier.verification.constants import LE_SCHEMA, QVI_SCHEMA +from eoa_verifier.verification.coordinating import VerificationCoordinator from eoa_verifier.verification.eoa import build_challenge from scripts.integration.issuers import ( KEY, @@ -97,7 +100,23 @@ def test_grant_verification_and_restart(tmp_path, method, delivery): webhook_aid=geda.pre if delivery else None, ) service_stores = stack.enter_context(ExitStack()) - runtime = service_stores.enter_context(verifier_service(config)) + epoch = time.time() + + def open_service(): + """Keep persistent retry deadlines on the test's HIO timeline across restart. + + Real Doist catches up after blocking setup/store work. Its virtual + deadlines can otherwise run ahead of a recently started UTC cooldown. + Use one epoch for every reopened worker; keep all retry budgets and + ten-second progress assertions unchanged. + """ + service = service_stores.enter_context(verifier_service(config)) + for doer in service.doers: + if isinstance(doer, (GrantNotificationDoer, VerificationCoordinator)): + doer.clock = lambda: epoch + workflow.tyme + return service + + runtime = open_service() client = http.Client(hostname="127.0.0.1", port=port) client_doer = http.ClientDoer(client=client) doers = [ @@ -160,7 +179,11 @@ def deliver(stream, said, expected): expected == "pending" or work.status == expected ): return work - assert workflow.tyme < deadline, (expected, work) + assert workflow.tyme < deadline, ( + expected, + work, + runtime.baser.verification_progress(said), + ) yield 0.01 def wait_status(said, expected): @@ -281,7 +304,7 @@ def run(tymth, tock=0.0, **kwa): aid = runtime.hab.pre workflow.remove([runtime, client_doer]) service_stores.close() - runtime = service_stores.enter_context(verifier_service(config)) + runtime = open_service() client = http.Client(hostname="127.0.0.1", port=port) client_doer = http.ClientDoer(client=client) workflow.extend([runtime, client_doer]) @@ -310,7 +333,6 @@ def run(tymth, tock=0.0, **kwa): # replay explicitly after the HTTP redelivery, rather than observing the # already-existing result before the duplicate has been processed. yield from send(evidence) - from eoa_verifier.receiving.grants import GrantNotificationDoer intake = next( d for d in runtime.doers if isinstance(d, GrantNotificationDoer) @@ -383,7 +405,7 @@ def run(tymth, tock=0.0, **kwa): assert runtime.baser.associations.get(keys=(creder.said,)) == accepted workflow.remove([runtime, client_doer]) service_stores.close() - runtime = service_stores.enter_context(verifier_service(config)) + runtime = open_service() client = http.Client(hostname="127.0.0.1", port=port) client_doer = http.ClientDoer(client=client) workflow.extend([runtime, client_doer]) @@ -408,7 +430,6 @@ def run(tymth, tock=0.0, **kwa): # Hold completion after a real RPC observation, then deliver KERIpy # revocation before applying the result. The final KERIpy recheck # must prevent initial success without asking RPC a second time. - from eoa_verifier.verification.coordinating import VerificationCoordinator coordinator = next( d for d in runtime.doers if isinstance(d, VerificationCoordinator)